PSOアルゴリズムpython実装


PSOアルゴリズムpython実装
csdnの上であるpsoアルゴリズムのコードが不完全であることを見て、ある運行が成功しないで、下で自分で書いたことを貼って、この作者に基づいてhttps://blog.csdn.net/ztf312/article/details/75669685のコードは、コメントを付けて同時に実行できます.
コード#コード#
import numpy as np  
import random   
import matplotlib.pyplot as plt

#----------------------PSO    ---------------------------------  
class PSO():  
   
    def __init__(self,pN,dim,max_iter):  #                             
        #self.w = 0.8 
        self.ws = 0.9
        self.we = 0.4
        self.c1 = 1.49445     
        self.c2 = 1.49445     
        self.r1= 0.6  
        self.r2= 0.3  
        self.pN = pN                #      
        self.dim = dim              #      
        self.max_iter = max_iter    #      
        self.X = np.zeros((self.pN,self.dim))       #       (        )  
        self.Xmax = 2  
        self.Xmin = 1
        self.V = np.zeros((self.pN,self.dim))       #       (        )
        self.Vmax = 0.5 
        self.Vmin = -0.5
        self.pbest = np.zeros((self.pN,self.dim))   #          
        self.gbest = np.zeros((1,self.dim))         #      
        self.p_fit = np.zeros(self.pN)              #              
        self.fit = 0             #         
          

#---------------------    Sphere  -----------------------------  
    def function(self,x):  
        y = np.sin(10*np.pi*x)/x
        return y

    
#---------------------     ----------------------------------  
    def init_Population(self):
        for i in range(self.pN):                                #      
            
            for j in range(self.dim):                           #        
                self.X[i][j] = random.uniform(1,2)               #                 (      )
                self.V[i][j] = random.uniform(-0.5,0.5)          #                 (      )
            
            self.pbest[i] = self.X[i]                            #                  
            tmp = self.function(self.X[i])                       #           
            self.p_fit[i] = tmp                                  #                
            
            if(tmp > self.fit):                                  #                      
                self.fit = tmp  
                self.gbest = self.X[i]  

                
#---------------------      ----------------------------------  
    def iterator(self):  
        fitness = []  
        for t in range(self.max_iter):
            w =  self.ws - (self.ws - self.we) * (t / self.max_iter)
            for i in range(self.pN):  
                
                #    
                self.V[i]  = w*self.V[i] + self.c1*self.r1*(self.pbest[i] - self.X[i]) + self.c2*self.r2*(self.gbest - self.X[i])
                if self.V[i] > self.Vmax:
                    self.V[i] = self.Vmax
                elif self.V[i] < self.Vmin:
                    self.V[i] = self.Vmin
                
                #    
                self.X[i] = self.X[i] + self.V[i]
                if self.X[i] > self.Xmax:
                    self.X[i] = self.Xmax
                elif self.X[i] < self.Xmin:
                    self.X[i] = self.Xmin
            
            for i in range(self.pN):         #  gbest\pbest  
                
                temp = self.function(self.X[i])  
                
                if(temp > self.p_fit[i]):      #        
                    self.pbest[i] = self.X[i]
                    self.p_fit[i] = temp 
               
                if(temp > self.fit):           #        
                    self.gbest = self.X[i]  
                    self.fit = temp  
              
            fitness.append(self.fit)  
            print('    :',self.fit)#      
            x1 = self.fit
            print('     :',self.X[i])
            y1 = self.X[i]
        return fitness, x1, y1

#----------------------    -----------------------  
my_pso = PSO(pN=20,dim=1,max_iter=50)  
my_pso.init_Population()  
fitness,x1,y1 = my_pso.iterator()

plt.figure(1)  
plt.title("Figure1")  
plt.xlabel("iterators", size=14)  
plt.ylabel("fitness", size=14)  
t = np.array([t for t in range(0,50)])  
fitness = np.array(fitness)  
plt.plot(t,fitness, color='b',linewidth=3) 
plt.show() 

plt.figure()  
plt.plot(aa,np.sin(10*np.pi*aa)/aa, color='b',linewidth=3) 
plt.scatter(y1, x1, marker = 'x',color = 'red', s = 100 ,label = 'First')
plt.show()