果蠅優化算法-FOA

import numpy as np
import matplotlib.pyplot as plt

sample = 50
iter_times = 100

def initParams(bestX,bestY,sample): 
    position = []
    fitness = []
    for num in range(sample):
        x,y = bestX+2*np.random.rand()-1,bestY+2*np.random.rand()-1
        S = 1/np.sqrt(x**2+y**2)
        smell = S**2-5
        position.append((x,y))
        fitness.append(smell)
    
    bestIndex = np.argmin(fitness)
    bestX,bestY = position[bestIndex]
    bestSmell = fitness[bestIndex]
    return bestX,bestY,bestSmell

bestX,bestY,bestSmell = initParams(10*np.random.rand(),10*np.random.rand(),sample)
xlist,ylist,value = [],[],[]
for time in range(iter_times):
    tmpX,tmpY,tmpSmell = initParams(bestX,bestY,sample)
    if tmpSmell < bestSmell:
        bestX = tmpX
        bestY = tmpY
        bestSmell = tmpSmell
        xlist.append(bestX)
        ylist.append(bestY)
        value.append(bestSmell)

fig,ax = plt.subplots(1,2,figsize=(12,4))
ax[0].plot(xlist,ylist,'--',color='red')
ax[0].grid(linestyle='--',color='violet')
ax[0].set_title('orit of fly',fontsize=20,color='purple')
ax[1].plot(range(1,iter_times+1),value,'-',color='lime')
ax[1].grid(linestyle='--',color='blue')
ax[1].set_title('prediction value',fontsize=20,color='purple')

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章