import matplotlib.pyplot as plt
import math

from calobjValue import calobjValue
from calfitValue import calfitValue
from selection import selection
from crossover import crossover
from mutation import mutation
from best import best
from geneEncoding import geneEncoding

print('y = 10 * math.sin(5 * x) + 7 * math.cos(4 * x)')


# 计算2进制序列代表的数值
def b2d(b, max_value, chrom_length):
	t = 0
	for j in range(len(b)):
		t += b[j] * (math.pow(2, j))
	t = t * max_value / (math.pow(2, chrom_length) - 1)
	return t

pop_size = 500		# 种群数量
max_value = 10      # 基因中允许出现的最大值
chrom_length = 10		# 染色体长度
pc = 0.6			# 交配概率
pm = 0.01           # 变异概率
results = [[]]		# 存储每一代的最优解,N个二元组
fit_value = []		# 个体适应度
fit_mean = []		# 平均适应度

# pop = [[0, 1, 0, 1, 0, 1, 0, 1, 0, 1] for i in range(pop_size)]
pop = geneEncoding(pop_size, chrom_length)

for i in range(pop_size):
	obj_value = calobjValue(pop, chrom_length, max_value)        # 个体评价
	fit_value = calfitValue(obj_value)      # 淘汰
	best_individual, best_fit = best(pop, fit_value)		# 第一个存储最优的解, 第二个存储最优基因
	results.append([best_fit, b2d(best_individual, max_value, chrom_length)])
	selection(pop, fit_value)		# 新种群复制
	crossover(pop, pc)		# 交配
	mutation(pop, pm)       # 变异

results = results[1:]
results.sort()
print(results[-1])
print(best_individual)
print(best_fit)
print(obj_value[1])


print(results)
print('y = %f, x = %f' % (results[-1][0], results[-1][1]))

X = []
Y = []
for i in range(500):
	X.append(i)
	t = results[i][0]
	Y.append(t)

plt.plot(X, Y)

plt.show()

# 解释下每行代码的意思内容:
# 1. 导入matplotlib.pyplot和math库,用于绘图和数学计算。
# 2. 导入其他自定义的函数和类,用于遗传算法的各个步骤。
# 3. 打印出待优化的目标函数。
# 4. 定义一个函数b2d,用于将二进制序列转换为对应的数值。
# 5. 设置种群数量、基因中允许出现的最大值、染色体长度、交配概率和变异概率等参数。
# 6. 初始化结果列表,用于存储每一代的最优解和适应度。
# 7. 使用基因编码生成初始种群。
# 8. 进行遗传算法的迭代过程。
# 9. 计算个体的目标函数值。
# 10. 计算个体的适应度。
# 11. 找到当前种群中的最优解和适应度。
# 12. 将最优解和适应度存储到结果列表中。
# 13. 进行选择操作,根据适应度进行淘汰。
# 14. 进行交配操作,根据交配概率进行交叉配对。
# 15. 进行变异操作,根据变异概率进行基因突变。
# 16. 去除结果列表中的初始空列表。
# 17. 对结果列表进行排序,找到最优解。
# 18. 打印出最优解、最优基因和最优适应度。
# 19. 打印出个体的目标函数值。
# 20. 打印出结果列表。
# 21. 打印出最优解的数值表示。
# 22. 绘制结果列表中最优解的变化曲线。

这段代码使用 Python 实现了一个简单的遗传算法,并使用 matplotlib 库绘制了最优解的变化曲线。代码中包含了遗传算法的基本步骤,例如种群初始化、适应度评估、选择、交叉、变异等。最终,代码将找到目标函数 y = 10 * sin(5 * x) + 7 * cos(4 * x) 的最优解。

希望这段代码可以帮助你理解遗传算法的基本原理。

遗传算法优化目标函数 - Python 实现

原文地址: https://www.cveoy.top/t/topic/fN8p 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录