改进萤火虫优化算法(python代码)

1.效果图

改进萤火虫优化算法(python代码)_第1张图片

 2.改进萤火虫代码

import numpy as np
import matplotlib.pyplot as plt

def rastrigin(x):
    d = len(x)
    return 10*d + np.sum(x**2 - 10*np.cos(2*np.pi*x))

def firefly_algorithm(dim, fobj, nfireflies=20, alpha=0.5, betamin=0.2, gamma=1.0, lb=-5.12, ub=5.12, maxiter=100):
    
    X = np.random.uniform(lb, ub, (nfireflies, dim))
    I = np.array([fobj(x) for x in X])
    
    curve = np.zeros(maxiter)
    
    for t in range(maxiter):
        curve[t] = np.min(I)
        
        for i in range(nfireflies):
            for j in range(nfireflies):
                if I[j] < I[i]:
                    r = np.sqrt(np.sum((X[i]-X[j])**2))
                    beta = betamin + (1 - betamin)*np.exp(-gamma*r**2)
                    X[i] += alpha*beta*(X[j]-X[i]) 

你可能感兴趣的:(优化算法优化神经网络,python,算法,numpy)