遗传算法(一)
来源:互联网 发布:tcp ip的网络层 编辑:程序博客网 时间:2024/05/19 03:20
import numpy as npimport matplotlib.pyplot as pltDNA_SIZE = 10 # DNA lengthPOP_SIZE = 100 # population sizeCROSS_RATE = 0.8 # mating probability (DNA crossover)MUTATION_RATE = 0.003 # mutation probabilityN_GENERATIONS = 200X_BOUND = [0, 5] # x upper and lower boundsdef F(x): return np.sin(10*x)*x + np.cos(2*x)*x # to find the maximum of this function# find non-zero fitness for selectiondef get_fitness(pred): return pred + 1e-3 - np.min(pred)# convert binary DNA to decimal and normalize it to a range(0, 5)def translateDNA(pop): return pop.dot(2 ** np.arange(DNA_SIZE)[::-1]) / (2**DNA_SIZE-1) * X_BOUND[1]def select(pop, fitness): # nature selection wrt pop's fitness idx = np.random.choice(np.arange(POP_SIZE), size=POP_SIZE, replace=True, p=fitness/fitness.sum()) return pop[idx]def crossover(parent, pop): # mating process (genes crossover) if np.random.rand() < CROSS_RATE: i_ = np.random.randint(0, POP_SIZE, size=1) # select another individual from pop cross_points = np.random.randint(0, 2, size=DNA_SIZE).astype(np.bool) # choose crossover points parent[cross_points] = pop[i_, cross_points] # mating and produce one child return parentdef mutate(child): for point in range(DNA_SIZE): if np.random.rand() < MUTATION_RATE: child[point] = 1 if child[point] == 0 else 0 return childpop = np.random.randint(0, 2, (1, DNA_SIZE)).repeat(POP_SIZE, axis=0) # initialize the pop DNAplt.ion() # something about plottingx = np.linspace(*X_BOUND, 200)plt.plot(x, F(x))for _ in range(N_GENERATIONS): F_values = F(translateDNA(pop)) # compute function value by extracting DNA # something about plotting if 'sca' in globals(): sca.remove() sca = plt.scatter(translateDNA(pop), F_values, s=200, lw=0, c='red', alpha=0.5); plt.pause(0.05) # GA part (evolution) fitness = get_fitness(F_values) print("Most fitted DNA: ", pop[np.argmax(fitness), :]) pop = select(pop, fitness) pop_copy = pop.copy() for parent in pop: child = crossover(parent, pop_copy) child = mutate(child) parent[:] = child # parent is replaced its childplt.ioff(); plt.show()
阅读全文
0 0
- 遗传算法(一)
- 遗传算法(一)
- Matlab遗传算法(一)
- 遗传算法入门(一)
- 遗传算法入门(一)
- 深入浅出遗传算法(一)------初探遗传算法
- 遗传算法入门到掌握(一)
- 遗传算法入门到掌握(一)
- 遗传算法入门到掌握(一)
- 遗传算法入门到掌握(一)
- 遗传算法入门到掌握(一)
- 遗传算法入门到掌握(一)
- 遗传算法入门到掌握(一)
- 遗传算法入门到掌握(一)
- 遗传算法入门到掌握(一)
- 遗传算法入门到掌握(一)
- 遗传算法入门到掌握(一)
- 遗传算法入门到掌握(一)
- java多线程(二)---------------ThreadLocal总结
- Android Activity生命周期
- 职场礼仪常识、职场注意事项
- java反编译指令集
- git忽略mode的配置
- 遗传算法(一)
- substring-with-concatenation-of-all-words
- mt6631 BT /无线/ GPS /调频 设计的通知
- 第五章 创建高性能的索引
- WPF项目选择一个好的框架的重要性
- hbase 1.2.6 安装
- http请求参数——燚龘飝
- Unity-UGUI根据标签宽度实现瀑布流布局--FlowLayoutGroup
- 汽车加油行驶问题