生活随笔
收集整理的這篇文章主要介紹了
粒子群算法实例-求解函数极值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前面介紹了《粒子群算法》的基本原理,這里結合實例,看看粒子群算法是怎樣解決實際問題的。采用過的函數和《遺傳算法實例》中的一樣:
f ( x ) = x + 10 sin 5 x + 7 cos 4 x
求其在區間[-10,10]之間的最大值。下面是該函數的圖像: 在本例中,我們可以把x作為個體的染色體,函數值f(x)作為其適應度值,適應度越大,個體越優秀,最大的適應度就是我們要求的最大值。 直接看代碼吧(直接看注釋就能看懂)。
import numpy
as np
class particle :def __init__ (self) :self.pos =
0 self.speed =
0 self.pbest =
0 class PSO :def __init__ (self) :self.w =
0.5 self.c1 =
1 self.c2 =
1 self.gbest =
0 self.N =
20 self.POP = [] self.iter_N =
100 def fitness (self, x) :return x +
10 * np.sin(
5 * x) +
7 * np.cos(
4 * x)
def g_best (self, pop) :for bird
in pop:
if bird.fitness > self.fitness(self.gbest):self.gbest = bird.pos
def initPopulation (self, pop, N) :for i
in range(N):bird = particle()bird.pos = np.random.uniform(-
10 ,
10 )bird.fitness = self.fitness(bird.pos)bird.pbest = bird.fitnesspop.append(bird)self.g_best(pop)
def update (self, pop) :for bird
in pop:speed = self.w * bird.speed + self.c1 * np.random.random() * (bird.pbest - bird.pos) + self.c2 * np.random.random() * (self.gbest - bird.pos)pos = bird.pos + speed
if -
10 < pos <
10 : bird.pos = posbird.speed = speedbird.fitness = self.fitness(bird.pos)
if bird.fitness > self.fitness(bird.pbest):bird.pbest = bird.pos
def implement (self) :self.initPopulation(self.POP, self.N)
for i
in range(self.iter_N):self.update(self.POP)self.g_best(self.POP)pso = PSO()
pso.implement()
for ind
in pso.POP:print(
"x=" , ind.pos,
"f(x)=" , ind.fitness)
某一次執行中生成的種群結果: x= 7.44390041845 f(x)= 2.34326279816 x= 9.48378207609 f(x)= 13.3821268397 x= 6.3672261374 f(x)= 17.0548851104 x= 7.85674414126 f(x)= 24.855362869 x= 7.85674414216 f(x)= 24.855362869 x= 7.85674414201 f(x)= 24.855362869 x= 7.85674414185 f(x)= 24.855362869 x= 8.02319542929 f(x)= 20.1093330013 x= 7.85674414327 f(x)= 24.855362869 x= 7.85674414414 f(x)= 24.855362869 x= 7.85674414288 f(x)= 24.855362869 x= 7.85674414296 f(x)= 24.855362869 x= 7.85674414178 f(x)= 24.855362869 x= 7.85674414174 f(x)= 24.855362869 x= 7.8567441494 f(x)= 24.855362869 x= 6.44588532539 f(x)= 19.2820411821 x= 7.85674414041 f(x)= 24.855362869 x= 9.93067628809 f(x)= 1.12241685006 x= 7.8567441425 f(x)= 24.855362869 x= 8.81867117742 f(x)= 4.6512749143 得到的最優解結果為: X=7.85674414174 f(x)=24.855362869 從圖像上看符合要求。其結果圖像如下,紅色點表示種群中個體的位置。
import matplotlib.pyplot
as plt
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.pos
for ind
in pso.POP])
scatter_y = np.array([ind.fitness
for ind
in pso.POP])
plt.plot(x, y)
plt.scatter(scatter_x, scatter_y, c=
'r' )
plt.show()
總結
以上是生活随笔 為你收集整理的粒子群算法实例-求解函数极值 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。