亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python3實(shí)現(xiàn)單目標(biāo)粒子群算法

 更新時(shí)間:2019年11月14日 08:38:17   作者:zhf026  
這篇文章主要為大家詳細(xì)介紹了python3實(shí)現(xiàn)單目標(biāo)粒子群算法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了python3單目標(biāo)粒子群算法的具體代碼,供大家參考,具體內(nèi)容如下

關(guān)于PSO的基本知識(shí)......就說一下算法流程

1) 初始化粒子群;

    隨機(jī)設(shè)置各粒子的位置和速度,默認(rèn)粒子的初始位置為粒子最優(yōu)位置,并根據(jù)所有粒子最優(yōu)位置,選取群體最優(yōu)位置。

2) 判斷是否達(dá)到迭代次數(shù);

    若沒有達(dá)到,則跳轉(zhuǎn)到步驟3)。否則,直接輸出結(jié)果。

3) 更新所有粒子的位置和速度;

4) 計(jì)算各粒子的適應(yīng)度值。

     將粒子當(dāng)前位置的適應(yīng)度值與粒子最優(yōu)位置的適應(yīng)度值進(jìn)行比較,決定是否更新粒子最優(yōu)位置;將所有粒子最優(yōu)位置的適應(yīng)度值與群體最優(yōu)位置的適應(yīng)度值進(jìn)行比較,決定是否更新群體最優(yōu)位置。然后,跳轉(zhuǎn)到步驟2)。

直接扔代碼......(PS:1.參數(shù)動(dòng)態(tài)調(diào)節(jié);2.例子是二維的)

首先,是一些準(zhǔn)備工作...

# Import libs
import numpy as np
import random as rd
import matplotlib.pyplot as plt
 
# Constant definition
MIN_POS = [-5, -5]         # Minimum position of the particle
MAX_POS = [5, 5]          # Maximum position of the particle
MIN_SPD = [-0.5, -0.5]        # Minimum speed of the particle
MAX_SPD = [1, 1]          # Maximum speed of the particle
C1_MIN = 0
C1_MAX = 1.5
C2_MIN = 0
C2_MAX = 1.5
W_MAX = 1.4
W_MIN = 0

然后是PSO類

# Class definition
class PSO():
 """
  PSO class
 """
 
 def __init__(self,iters=100,pcount=50,pdim=2,mode='min'):
  """
   PSO initialization
   ------------------
  """
 
  self.w = None         # Inertia factor
  self.c1 = None        # Learning factor
  self.c2 = None        # Learning factor
 
  self.iters = iters       # Number of iterations
  self.pcount = pcount       # Number of particles
  self.pdim = pdim        # Particle dimension
  self.gbpos = np.array([0.0]*pdim)    # Group optimal position
  
  self.mode = mode        # The mode of PSO
 
  self.cur_pos = np.zeros((pcount, pdim))  # Current position of the particle
  self.cur_spd = np.zeros((pcount, pdim))  # Current speed of the particle
  self.bpos = np.zeros((pcount, pdim))   # The optimal position of the particle
 
  self.trace = []        # Record the function value of the optimal solution
  
 
 def init_particles(self):
  """
   init_particles function
   -----------------------
  """
 
  # Generating particle swarm
  for i in range(self.pcount):
   for j in range(self.pdim):
    self.cur_pos[i,j] = rd.uniform(MIN_POS[j], MAX_POS[j])
    self.cur_spd[i,j] = rd.uniform(MIN_SPD[j], MAX_SPD[j])
    self.bpos[i,j] = self.cur_pos[i,j]
 
  # Initial group optimal position
  for i in range(self.pcount):
   if self.mode == 'min':
    if self.fitness(self.cur_pos[i]) < self.fitness(self.gbpos):
     gbpos = self.cur_pos[i]
   elif self.mode == 'max':
    if self.fitness(self.cur_pos[i]) > self.fitness(self.gbpos):
     gbpos = self.cur_pos[i]
 
 def fitness(self, x):
  """
   fitness function
   ----------------
   Parameter:
    x : 
  """
  
  # Objective function
  fitval = 5*np.cos(x[0]*x[1])+x[0]*x[1]+x[1]**3 # min
  # Retyrn value
  return fitval
 
 def adaptive(self, t, p, c1, c2, w):
  """
  """
 
  #w = 0.95 #0.9-1.2
  if t == 0:
   c1 = 0
   c2 = 0
   w = 0.95
  else:
   if self.mode == 'min':
    # c1
    if self.fitness(self.cur_pos[p]) > self.fitness(self.bpos[p]):
     c1 = C1_MIN + (t/self.iters)*C1_MAX + np.random.uniform(0,0.1)
    elif self.fitness(self.cur_pos[p]) <= self.fitness(self.bpos[p]):
     c1 = c1
    # c2 
    if self.fitness(self.bpos[p]) > self.fitness(self.gbpos):
     c2 = C2_MIN + (t/self.iters)*C2_MAX + np.random.uniform(0,0.1)
    elif self.fitness(self.bpos[p]) <= self.fitness(self.gbpos):
     c2 = c2
    # w
    #c1 = C1_MAX - (C1_MAX-C1_MIN)*(t/self.iters)
    #c2 = C2_MIN + (C2_MAX-C2_MIN)*(t/self.iters)
    w = W_MAX - (W_MAX-W_MIN)*(t/self.iters)
   elif self.mode == 'max':
    pass
 
  return c1, c2, w
 
 def update(self, t):
  """
   update function
   ---------------
    Note that :
     1. Update particle position
     2. Update particle speed
     3. Update particle optimal position
     4. Update group optimal position
  """
 
  # Part1 : Traverse the particle swarm
  for i in range(self.pcount):
   
   # Dynamic parameters
   self.c1, self.c2, self.w = self.adaptive(t,i,self.c1,self.c2,self.w)
   
   # Calculate the speed after particle iteration
   # Update particle speed
   self.cur_spd[i] = self.w*self.cur_spd[i] \
        +self.c1*rd.uniform(0,1)*(self.bpos[i]-self.cur_pos[i])\
        +self.c2*rd.uniform(0,1)*(self.gbpos - self.cur_pos[i])
   for n in range(self.pdim):
    if self.cur_spd[i,n] > MAX_SPD[n]:
     self.cur_spd[i,n] = MAX_SPD[n]
    elif self.cur_spd[i,n] < MIN_SPD[n]:
     self.cur_spd[i,n] = MIN_SPD[n]
 
   # Calculate the position after particle iteration
   # Update particle position 
   self.cur_pos[i] = self.cur_pos[i] + self.cur_spd[i]
   for n in range(self.pdim):
    if self.cur_pos[i,n] > MAX_POS[n]:
     self.cur_pos[i,n] = MAX_POS[n]
    elif self.cur_pos[i,n] < MIN_POS[n]:
     self.cur_pos[i,n] = MIN_POS[n]
    
  # Part2 : Update particle optimal position
  for k in range(self.pcount):
   if self.mode == 'min':
    if self.fitness(self.cur_pos[k]) < self.fitness(self.bpos[k]):
     self.bpos[k] = self.cur_pos[k]
   elif self.mode == 'max':
    if self.fitness(self.cur_pos[k]) > self.fitness(self.bpos[k]):
     self.bpos[k] = self.cur_pos[k]
 
  # Part3 : Update group optimal position
  for k in range(self.pcount):
   if self.mode == 'min':
    if self.fitness(self.bpos[k]) < self.fitness(self.gbpos):
     self.gbpos = self.bpos[k]
   elif self.mode == 'max':
    if self.fitness(self.bpos[k]) > self.fitness(self.gbpos):
     self.gbpos = self.bpos[k]
 
 def run(self):
  """
   run function
   -------------
  """
 
  # Initialize the particle swarm
  self.init_particles()
 
  # Iteration
  for t in range(self.iters):
   # Update all particle information
   self.update(t)
   #
   self.trace.append(self.fitness(self.gbpos))

然后是main...

def main():
 """
  main function
 """
 
 for i in range(1):
  
  pso = PSO(iters=100,pcount=50,pdim=2, mode='min')
  pso.run()
   
  #
  print('='*40)
  print('= Optimal solution:')
  print('= x=', pso.gbpos[0])
  print('= y=', pso.gbpos[1])
  print('= Function value:')
  print('= f(x,y)=', pso.fitness(pso.gbpos))
  #print(pso.w)
  print('='*40)
  
  #
  plt.plot(pso.trace, 'r')
  title = 'MIN: ' + str(pso.fitness(pso.gbpos))
  plt.title(title)
  plt.xlabel("Number of iterations")
  plt.ylabel("Function values")
  plt.show()
 #
 input('= Press any key to exit...')
 print('='*40)
 exit() 
 
 
if __name__ == "__main__":
 
 main()

最后是計(jì)算結(jié)果,完美結(jié)束?。?!

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python3將變量寫入SQL語句的實(shí)現(xiàn)方式

    python3將變量寫入SQL語句的實(shí)現(xiàn)方式

    這篇文章主要介紹了python3將變量寫入SQL語句的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • Python網(wǎng)絡(luò)爬蟲之爬取微博熱搜

    Python網(wǎng)絡(luò)爬蟲之爬取微博熱搜

    這篇文章主要介紹了Python網(wǎng)絡(luò)爬蟲之爬取微博熱搜的相關(guān)知識(shí),非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-04-04
  • Python簡(jiǎn)單I/O操作示例

    Python簡(jiǎn)單I/O操作示例

    這篇文章主要介紹了Python簡(jiǎn)單I/O操作,結(jié)合實(shí)例形式分析了Python針對(duì)文件的I/O讀寫及cPickle模塊相關(guān)使用操作技巧,需要的朋友可以參考下
    2019-03-03
  • 使用Bazel編譯TensorBoard教程

    使用Bazel編譯TensorBoard教程

    今天小編就為大家分享一篇使用Bazel編譯TensorBoard教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • python實(shí)現(xiàn)飛船大戰(zhàn)

    python實(shí)現(xiàn)飛船大戰(zhàn)

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)飛船大戰(zhàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • TensorFlow中tf.batch_matmul()的用法

    TensorFlow中tf.batch_matmul()的用法

    這篇文章主要介紹了TensorFlow中tf.batch_matmul()的用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • Flask??請(qǐng)求鉤子的實(shí)現(xiàn)

    Flask??請(qǐng)求鉤子的實(shí)現(xiàn)

    這篇文章主要給大家分享了Flask請(qǐng)求鉤子的實(shí)現(xiàn),在客戶端和服務(wù)器交互的過程中,有些準(zhǔn)備工作或掃尾工作需要處理,比如:在請(qǐng)求開始時(shí),建立數(shù)據(jù)庫連接;在請(qǐng)求開始時(shí),根據(jù)需求進(jìn)行權(quán)限校驗(yàn);在請(qǐng)求結(jié)束時(shí),指定數(shù)據(jù)的交互格式;下面來看看文章詳細(xì)介紹內(nèi)容吧
    2021-11-11
  • 使用Python實(shí)現(xiàn)壓縮pptx的功能

    使用Python實(shí)現(xiàn)壓縮pptx的功能

    當(dāng)處理大型PPTX文件時(shí),其中包含許多高分辨率照片時(shí),文件大小可能會(huì)顯著增加,為了解決這個(gè)問題,我們可以使用Python編程語言和python-pptx庫來壓縮PPTX文件中的照片,下面我們就來看看具體操作吧
    2024-02-02
  • 你知道怎么改進(jìn)Python 二分法和牛頓迭代法求算術(shù)平方根嗎

    你知道怎么改進(jìn)Python 二分法和牛頓迭代法求算術(shù)平方根嗎

    這篇文章主要介紹了Python編程實(shí)現(xiàn)二分法和牛頓迭代法求平方根代碼的改進(jìn),具有一定參考價(jià)值,需要的朋友可以了解下,希望能夠給你帶來幫助
    2021-08-08
  • Python制作進(jìn)度條的四種方法總結(jié)

    Python制作進(jìn)度條的四種方法總結(jié)

    如果你之前沒用過進(jìn)度條,八成是覺得它會(huì)增加不必要的復(fù)雜性或者很難維護(hù),其實(shí)不然。要加一個(gè)進(jìn)度條其實(shí)只需要幾行代碼,快跟隨小編一起學(xué)習(xí)學(xué)習(xí)吧
    2022-11-11

最新評(píng)論