遗传算法python实现_Python遗传算法代码实例讲解
目錄
實(shí)例:
求解函數(shù)的最大值y=xsin(10x)+xsin(2x),自變量取值:0--5,用Python畫(huà)出的圖像如下
(注:此代碼好像有一些感覺(jué)不對(duì)的地方,首先:沒(méi)有保留那些適應(yīng)度低的個(gè)體
pop = select(pop, fitness) '''這一行代碼,壓根就是把適應(yīng)度低的個(gè)體給干沒(méi)了。'''
for parent in pop:
child = crossover(parent, pop_copy)
child = mutate(child)
parent[:] = child '''這個(gè)for循環(huán),沒(méi)有對(duì)交叉變異后的個(gè)體進(jìn)行適應(yīng)度篩選啊'''
)
代碼講解:
'''
1初始化種群:返回一個(gè)元素為 二進(jìn)制的矩陣,每一行代表一個(gè)個(gè)體,每個(gè)個(gè)體由二進(jìn)制數(shù)字表示x值
2:代表二進(jìn)制,POP_SIZE:矩陣行數(shù),DNA_SIZE:矩陣列數(shù)。
'''
pop = np.random.randint(2, size=(POP_SIZE, DNA_SIZE))
'''
2,計(jì)算適應(yīng)度并且原則優(yōu)良種群,(有放回的抽取),循環(huán)很多代
pop:代表二進(jìn)制種群,translateDNA(pop):將其轉(zhuǎn)化十進(jìn)制,在計(jì)算適應(yīng)度,在select選擇優(yōu)良種群
'''
F_values = F(translateDNA(pop)) #求函數(shù)值
fitness = get_fitness(F_values) #得到使用度,這里例子函數(shù)值就是適應(yīng)度
pop = select(pop, fitness)
#此時(shí)的pop是經(jīng)過(guò)篩選的好的總?cè)?#xff0c;也是一個(gè)二進(jìn)制表現(xiàn)方式,里面有很多一樣的個(gè)體,因?yàn)槭褂梅呕刈ト?/p>
'''
3,經(jīng)過(guò)一波篩選后,接下來(lái)該交叉變異了,為了得到更好的x值,因?yàn)槌跏蓟膞值使得個(gè)體分布不均勻
'''
pop_copy = pop.copy() #復(fù)制一份優(yōu)良種群,用于交叉變異
for parent in pop:
child = crossover(parent, pop_copy) #交叉
child = mutate(child) #交叉后的種群在進(jìn)行變異
parent[:] = child
#將child賦值給parent
難度較大的代碼:
crossover() mutate() parent[:] = child
'''
crossover
交叉:parent:表示每一個(gè)二進(jìn)制個(gè)體,pop:優(yōu)良的種群,如100個(gè)個(gè)體
返回交叉后的一個(gè)個(gè)體,也是二進(jìn)制表示方式
這個(gè)函數(shù)的功能就是
parent[cross_points] = pop[i_, cross_points]
'''
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
# 從0-POP_SIZE,隨機(jī)選擇一個(gè)數(shù)字,
cross_points = np.random.randint(0, 2, size=DNA_SIZE).astype(np.bool)
#array([ True, False, False, True, True, False, False, True, True,
#True])
#隨機(jī)生成一個(gè)10個(gè)元素的數(shù)組,元素為0和1,在轉(zhuǎn)化成bool型
# choose crossover points
parent[cross_points] = pop[i_, cross_points]
#這個(gè)語(yǔ)句有難度:
'''
將parent為T(mén)rue的元素,將被改變,False的元素不變.將被改變的元素改變成 pop矩陣第 i_ 行里面被選擇為true的元素,
注意,parent的是cross_points, pop 也是cross_points,必須保持一致,才可以實(shí)現(xiàn)交叉生成一個(gè)新的個(gè)體,這個(gè)個(gè)體是父母基因的交叉結(jié)果
'''
# mating and produce one child
return parent #將新個(gè)體返回出去
'''
變異:將交叉后得到的個(gè)體,(這個(gè)個(gè)體不一定就是好的個(gè)體,很可能是不好的適應(yīng)度不高的個(gè)體)
進(jìn)行變異,
核心代碼:
child[point] = 1 if child[point] == 0 else 0
'''
def mutate(child):
for point in range(DNA_SIZE):
if np.random.rand() < MUTATION_RATE:
child[point] = 1 if child[point] == 0 else 0
'''
point是把child這個(gè)個(gè)體基因遍歷一遍,按照幾率進(jìn)行將0變成1,
注意:并不是將所有的0變成1,而是有幾率的 if np.random.rand() < MUTATION_RATE:
'''
return child
全部代碼:
"""
Visualize Genetic Algorithm to find a maximum point in a function.
Visit my tutorial website for more: https://morvanzhou.github.io/tutorials/
"""
import numpy as np
import matplotlib.pyplot as plt
DNA_SIZE = 10 # DNA length
POP_SIZE = 100 # population size
CROSS_RATE = 0.8 # mating probability (DNA crossover)
MUTATION_RATE = 0.003 # mutation probability
N_GENERATIONS = 200
X_BOUND = [0, 5] # x upper and lower bounds
def 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 selection
def 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]) / float(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 parent
def mutate(child):
for point in range(DNA_SIZE):
if np.random.rand() < MUTATION_RATE:
child[point] = 1 if child[point] == 0 else 0
return child
pop = np.random.randint(2, size=(POP_SIZE, DNA_SIZE)) # initialize the pop DNA
plt.ion() # something about plotting
x = 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 by its child
plt.ioff(); plt.show()
總結(jié)
以上是生活随笔為你收集整理的遗传算法python实现_Python遗传算法代码实例讲解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: css 解析器 java_Java 的
- 下一篇: k8s挂载目录_K8S中挂载目录引发的血