研究论文时,实现了一个简单的遗传算法原型,写在这里供大家参考指正
运行结果如下:
代码如下
main.py:
# 尝试用遗传算法来计算一个函数的最大值
import random
import numpy
from bitopt import Bit
from bitopt import cross
import numpy as np
from matplotlib import pyplot as plt
def generate_first(in_chromosomeNum, space_num):
ret_array = []
for i in range(in_chromosomeNum):
ret_array.append(random.randint(1, space_num))
return ret_array
# 轮盘赌函数
def Roulette(in_adaptablity):
sum_adapt = sum(in_adaptablity)
selecter = random.random() # 生成 0 - 1的随机值
Probability_Total = 0
for index, item in enumerate(in_adaptablity):
# 这里的in_adaptablity 数组为浮点数数组
Probability_Total = Probability_Total + item / sum_adapt
if Probability_Total > selecter:
return index
def select(in_chromosomeMatrix, in_adaptablity):
# 根据轮盘赌原则选择两个个体,以进行繁殖
a_index = Roulette(in_adaptablity)
b_index = Roulette(in_adaptablity)
if in_adaptablity[a_index] <= in_adaptablity[b_index]:
return in_chromosomeMatrix[b_index]
else:
return in_chromosomeMatrix[a_index]
def new_individual(in_a: int, in_b: int):
# 这里进行交叉变异操作,以产生子个体
a_bit = Bit(in_a)
b_bit = Bit(in_b)
max_index = max(a_bit.ret_len(), b_bit.ret_len()) - 1
r_p = random.random()
if r_p < 0.90: # 0.9交叉概率
r_index = random.randint(0, max_index) # 单点交叉的位点
cross(a_bit, b_bit, r_index, max_index) # 二进制交叉
r_p = random.random()
if r_p < 0.01: # 1/100概率变异
r_index = random.randint(0, max_index) # 单点交叉的位点
a_bit.reverse(r_index)
return a_bit.ret_num(), b_bit.ret_num()
def generate_next(in_chromosomeMatrix, in_adaptablity,space_num):
new_chromosomeMatrix = []
while len(new_chromosomeMatrix) < len(in_chromosomeMatrix): # 直到繁殖的数量达到预先给定的种群大小
a = select(in_chromosomeMatrix, in_adaptablity) # 选择出两个优良个体
b = select(in_chromosomeMatrix, in_adaptablity) # 选择出两个优良个体
new_a, new_b = new_individual(a, b)
if 0 <= new_a <= space_num and 0 <= new_b <= space_num: # 二进制交叉后可能会产生不属于考虑范围的值,应该剔除
new_chromosomeMatrix.append(new_a)
new_chromosomeMatrix.append(new_b)
# print("generate next generation.")
# print(new_chromosomeMatrix)
return new_chromosomeMatrix
def calAdaptability(in_chromosomeMatrix, target_func, start, end, space_num):
# 使用函数值的高低来表示可靠度 应当全部是正值
my_map = lambda x: float(end - start) / space_num * x
myfunc = target_func
ret_array = []
for i in range(len(in_chromosomeMatrix)):
ret_array.append(myfunc(my_map(in_chromosomeMatrix[i])))
# print(ret_array[i])
return ret_array
def ga_algo(iterNum, chromosomeNum, target_func, start, end, space_num):
chromosomeMatrix = generate_first(chromosomeNum, space_num)
adaptabilityMatrix = []
# fig, ax = plt.subplots()
# plt.show()
plt.ion() # 交互模式
for i in range(iterNum):
# print("{}===>>", i)
adaptabilityMatrix = calAdaptability(chromosomeMatrix, target_func, start, end, space_num)
# print(adaptabilityMatrix)
chromosomeMatrix = generate_next(chromosomeMatrix, adaptabilityMatrix,space_num)
# 画图
plt.cla()
x = np.linspace(start, end, space_num)
y = target_func(x)
plt.plot(x, y)
x1 = numpy.array(list(map(lambda x: x / float(space_num) * (end - start), chromosomeMatrix)))
y1 = target_func(x1)
# print(y1)
plt.scatter(x1, y1, color='red')
plt.title("{} th".format(i + 1))
plt.pause(1)
print("end.")
print(list(map(lambda x: x / float(10000) * 5, chromosomeMatrix)))
plt.ioff()
plt.show()
def target_func(x):
# 这里写下你的目标函数
# return -x ** 2 + 5 * x + 1
return 10 * np.sin(5 * x) + 7 * np.fabs(x - 5) + 10
if __name__ == '__main__':
ga_algo(50, 100, target_func, 0, 5, 10000)
bitopt.py
# 对正整数进行二进制操作
class Bit:
def __init__(self, in_num):
self._storage_num = in_num
for item in range(0, in_num + 1):
if 2 ** item >= in_num + 1:
self._len = item
break
def is_valid_index(self, index):
if index <= self._len - 1 and self._len >= 0:
return True
else:
return False
def ret_num(self):
return self._storage_num
def ret_len(self):
return self._len
def set_num(self, in_num):
self._storage_num = in_num
for item in range(1, in_num):
if 2 ** item >= in_num + 1:
self._len = item
break
# 返回给定位上的值
def __getitem__(self, index):
if self._storage_num & (1 << index) == 0:
return 0
else:
return 1
# 给指定位赋值
def __setitem__(self, index, value: bool):
if value is True:
self._storage_num = self._storage_num | (1 << index) # 将指定位置一
else:
self._storage_num = self._storage_num & (~(1 << index)) # 将指定位清零
# 给指定位取反
def reverse(self, index):
self._storage_num = self._storage_num ^ (1 << index)
# 两个Bit应该是同一个长度
def cross(bit_a: Bit, bit_b: Bit, index_start, index_end):
max_index = max(bit_a.ret_len(), bit_b.ret_len()) - 1
if 0 <= index_start <= index_end <= max_index:
to_clear_high = 2 ** (index_end + 1) - 1
to_clear_low = ~(2 ** index_start - 1)
a_mid = bit_a.ret_num() & to_clear_high & to_clear_low # 得到a中间 0000aaaaa0000
b_mid = bit_b.ret_num() & to_clear_high & to_clear_low # 得到b中间 0000bbbbb0000
bit_a.set_num(bit_a.ret_num() & (~a_mid)) # 将中间清零 => aaaa00000aaaa
bit_a.set_num(bit_a.ret_num() | b_mid) # 将b的中间放到a的中间 最终得到 aaaabbbbbaaaa
bit_b.set_num(bit_b.ret_num() & (~b_mid)) # 同样 => bbbb00000bbbb
bit_b.set_num(bit_b.ret_num() | a_mid) # 最终得到 bbbbaaaaabbbb
return True
else:
return False