生活随笔
收集整理的這篇文章主要介紹了
遗传算法实例-求解函数极值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前面在《遺傳算法通識》中介紹了基本原理,這里結合實例,看看遺傳算法是怎樣解決實際問題的。
有一個函數:
f ( x ) = x + 10 sin 5 x + 7 cos 4 x
求其在區間[-10,10]之間的最大值。下面是該函數的圖像:
在本例中,我們可以把x作為個體的染色體,函數值f(x)作為其適應度值,適應度越大,個體越優秀,最大的適應度就是我們要求的最大值。 直接看代碼吧(直接看注釋就能看懂)。
import numpy
as np
import matplotlib.pyplot
as plt
def fitness (x) :return x +
10 * np.sin(
5 * x) +
7 * np.cos(
4 * x)
class indivdual :def __init__ (self) :self.x =
0 self.fitness =
0 def __eq__ (self, other) :self.x = other.xself.fitness = other.fitness
def initPopulation (pop, N) :for i
in range(N):ind = indivdual()ind.x = np.random.uniform(-
10 ,
10 )ind.fitness = fitness(ind.x)pop.append(ind)
def selection (N) :return np.random.choice(N,
2 )
def crossover (parent1, parent2) :child1, child2 = indivdual(), indivdual()child1.x =
0.9 * parent1.x +
0.1 * parent2.xchild2.x =
0.1 * parent1.x +
0.9 * parent2.xchild1.fitness = fitness(child1.x)child2.fitness = fitness(child2.x)
return child1, child2
def mutation (pop) :ind = np.random.choice(pop)ind.x = np.random.uniform(-
10 ,
10 )ind.fitness = fitness(ind.x)
def implement () :N =
20 POP = []iter_N =
500 initPopulation(POP, N)
for it
in range(iter_N):a, b = selection(N)
if np.random.random() <
0.75 : child1, child2 = crossover(POP[a], POP[b])new = sorted([POP[a], POP[b], child1, child2], key=
lambda ind: ind.fitness, reverse=
True )POP[a], POP[b] = new[
0 ], new[
1 ]
if np.random.random() <
0.1 : mutation(POP)POP.sort(key=
lambda ind: ind.fitness, reverse=
True )
return POPpop = implement()
某一次執行中生成的種群結果: x= 7.856668536350623 f(x)= 24.8553618344 x= 7.856617137410436 f(x)= 24.8553599496 x= 7.855882244973719 f(x)= 24.855228419 x= 7.858162713580771 f(x)= 24.8549986778 x= 7.854666292636083 f(x)= 24.8545814476 x= 7.8546151621339035 f(x)= 24.8545425164 x= 7.854257103484315 f(x)= 24.8542433686 x= 7.8540369711896485 f(x)= 24.8540364169 x= 7.859755006757047 f(x)= 24.8537223172 x= 7.853295380711855 f(x)= 24.85321014 x= 7.853150338317231 f(x)= 24.853025258 x= 7.865253897257472 f(x)= 24.8422607373 x= 7.865398960184752 f(x)= 24.8418103374 x= 7.83788118828644 f(x)= 24.7909840929 x= 1.6190862308608494 f(x)= 18.1988285173 x= 1.6338610617810327 f(x)= 17.9192791105 x= 2.9228585632615074 f(x)= 16.2933631636 x= 2.95557040313432 f(x)= 16.1223714647 x= -1.2700947285555912 f(x)= 0.575714213108 x= -9.208677771536376 f(x)= -13.4869432732
得到的最優解結果為: x= 7.856668536350623 f(x)= 24.8553618344 從圖像上看符合要求。其結果圖像如下,紅色點表示種群中個體的位置。
def func (x) :return x +
10 * np.sin(
5 * x) +
7 * np.cos(
4 * x)
x = np.linspace(-
10 ,
10 ,
10000 )
y = func(x)
scatter_x = np.array([ind.x
for ind
in pop])
scatter_y = np.array([ind.fitness
for ind
in pop])
plt.plot(x, y)
plt.scatter(scatter_x, scatter_y, c=
'r' )
plt.show()
總結
以上是生活随笔 為你收集整理的遗传算法实例-求解函数极值 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。