遗传算法python源码,亲测可用

python实现遗传算法对标准测试函数(以Rastrigin函数为例)进行求解,效果还不错:


import numpy as np
import matplotlib.pyplot as plt

# 标准测试函数(以Rastrigin函数为例)
def rastrigin(x):
    return 10 * len(x) + sum([(xi**2 - 10 * np.cos(2 * np.pi * xi)) for xi in x])

class GeneticAlgorithm:
    def __init__(self, func, bounds, pop_size=200, elite_size=10, 
                 mutation_rate=0.01, generations=100):
        self.func = func
        self.bounds = bounds
        self.dim = len(bounds)
        self.pop_size = pop_size
        self.elite_size = elite_size
        self.mutation_rate = mutation_rate
        self.generations = generations
        
    def initialize_population(self):
        return np.random.uniform(
            low=[b[0] for b in self.bounds],
            high=[b[1] for b in self.bounds],
            size=(self.pop_size, self.dim)
        )
    
    def fitness(self, population):
        return 1 / (1 + np.array([self.func(ind) for ind in population]))
    
    def select(self, population, fitness):
        elite_idx = np.argsort(fitness)[-self.elite_size:]
        parents = population[elite_idx]
        return parents
    
    def crossover(self, parents):
        offspring = np.zeros((self.pop_size - self.elite_size, self.dim))
        for i in range(offspring.shape[0]):
            parent1, parent2 = parents[np.random.choice(len(parents), 2, replace=False)]
            alpha = np.random.random(self.dim)
            offspring[i] = alpha * parent1 + (1 - alpha) * parent2
        return offspring
    
    def mutate(self, offspring):
        for i in range(offspring.shape[0]):
            if np.random.random() < self.mutation_rate:
                j = np.random.randint(self.dim)
                offspring[i,j] = np.random.uniform(self.bounds[j][0], self.bounds[j][1])
        return offspring
    
    def run(self):
        pop = self.initialize_population()
        best_fitness = []
        
        for gen in range(self.generations):
            fit = self.fitness(pop)
            best_fitness.append(np.max(fit))
            
            parents = self.select(pop, fit)
            offspring = self.crossover(parents)
            offspring = self.mutate(offspring)
            
            pop = np.vstack([parents, offspring])
            
            if gen % 10 == 0:
                best_idx = np.argmax(fit)
                print(f"Gen {gen}: Best fitness = {1/fit[best_idx]-1:.4f}")
        
        best_idx = np.argmax(self.fitness(pop))
        best_solution = pop[best_idx]
        best_value = self.func(best_solution)
        
        return best_solution, best_value, best_fitness

# 参数设置
bounds = [(-5.12, 5.12)] * 2  # 二维Rastrigin函数搜索空间
ga = GeneticAlgorithm(rastrigin, bounds, generations=100)

# 运行算法
solution, value, fitness_history = ga.run()

# 输出结果
print(f"\n最优解: {solution}")
print(f"最优值: {value:.4f}")

# 绘制收敛曲线
plt.figure(figsize=(10,6))
plt.plot(1/np.array(fitness_history)-1, 'r-', linewidth=2)
plt.xlabel('Generation')
plt.ylabel('Best Fitness')
plt.title('Genetic Algorithm Convergence')
plt.grid(True)
plt.show()

效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iven-yin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值