智能优化课,老师让实现遗传算法,每行加注释,略感无语。。。我发现我正好有现成的,加了下注释。
import numpy as np
import random
from matplotlib import pyplot as plt
mutation_rate = 0.001
max_iter = 500
m = 20
n = 4
def func(x):
return 15 * x - x ** 2
class Gene():
def __init__(self, n, func: 'function'):
'''
## 基因类
---
n: 基因长度
func: 用于计算适应度的函数
'''
self.n = n
self.func = func
self.gene = [0 for i in range(self.n)]
def mutation(self):
for i in range(self.n):
if random.uniform(0, 1) <= mutation_rate:
self.gene[i] ^= 1
def cal_fitness(self):
num = 0
for i in self.gene:
num *= 2
num += i
return self.func(num)
def cross(n, g1: Gene, g2: Gene):
'''
## 基因交叉函数
---
n: 最大切断位置
g1: 基因1
g2: 基因2
'''
pos = random.randint(0, n)
g1_r = g1.gene[pos:]
g2_r = g2.gene[pos:]
g1.gene[pos:] = g2_r
g2.gene[pos:] = g1_r
def next_gene(genes: list[Gene]):
'''
## 求下一代基因
---
genes: 当前所有基因
'''
select_prob = []
total_prob = 0.0
for g in genes:
prob = g.cal_fitness()
select_prob.append(prob)
total_prob += prob
new_genes: list[Gene] = []
for i in range(len(genes)):
prob = random.randint(0, total_prob)
c = -1
while prob > 0:
c += 1
prob -= select_prob[c]
new_genes.append(genes[i])
for i in range(int(len(genes) / 2)):
cross(new_genes[i].n, new_genes[i], new_genes[i + 1])
new_genes[i].mutation()
new_genes[i + 1].mutation()
return new_genes
def best_gene(genes: list[Gene]):
'''
## 求一代中最好的基因
---
genes: 所有基因
'''
best = 0
for gene in genes:
fit = gene.cal_fitness()
if fit > best:
best = fit
return best
if __name__ == '__main__':
genes = [Gene(n, func) for i in range(m)]
value = []
i = 0
while i < max_iter:
genes = next_gene(genes)
value.append(best_gene(genes))
i += 1
print(max(value))
ax1 = plt.subplot(1, 2, 1)
x = np.arange(-30, 30)
plt.plot(x, func(x))
ax2 = plt.subplot(1, 2, 2)
plt.plot(value)
plt.show()
有问题请大佬指正。
|