最適化アルゴリズム(一)粒子群アルゴリズム

1320 ワード

import numpy as np


def pso(fitness, D=1, c1=2, c2=2, w=0.8, N=200, M=1000):

    #                   

    # fitness        
    # D        
    # c1,c2       
    # w       
    # N       
    # M          

    #         
    x = np.random.rand(N, D)
    v = np.random.rand(N, D)

    #           
    p = np.zeros(N)

    #              
    y = [0] * N

    #              
    for i in range(N):
        p[i] = fitness(x[i])
        y[i] = x[i]

    #          
    pg = x[-1]
    for i in range(N-1):
        if fitness(x[i]) < fitness(pg):
            pg = x[i]

    #    
    for t in range(M):
        for i in range(N):

            #           
            v[i] = w * v[i] + c1 * np.random.random() * (y[i] - x[i]) + c2 * np.random.random() * (pg - x[i])
            x[i] += v[i]

            #           
            if fitness(x[i]) < p[i]:
                p[i] = fitness(x[i])
                y[i] = list(x[i])
                
            #          
            if p[i] < fitness(pg):
                pg = y[i]

    #                
    return pg, fitness(pg)


def func(x):
    x1, x2, x3 = x
    return x1 ** 2 + x2 ** 2 + x3 ** 2


xm, fv = pso(func, 3)

print(xm, fv)

# [8.900130642125157e-17, 1.810901815514498e-17, 4.631944512800519e-17] 1.039466008019917e-32