使用螳螂优化算法来寻找目标函数f(x)=x^2的最小值,以下是Python代码:
import random
import numpy as np
class Mantis:
def __init__(self, dim, num):
self.dim = dim
self.num = num
self.x = np.random.rand(num, dim)
self.v = np.zeros((num, dim))
self.fitness = np.zeros(num)
self.fitness_best = np.inf
self.x_best = np.zeros(dim)
self.w = 0.9
self.c1 = 1.5
self.c2 = 1.5
def optimize(self, func, max_iter=1000):
for i in range(max_iter):
for j in range(self.num):
r1 = random.random()
r2 = random.random()
r3 = random.random()
v1 = self.w*self.v[j] + self.c1*r1*(self.x_best - self.x[j]) + self.c2*r2*(self.x_best - self.x[j]) + self.c2*r3*(self.x[np.random.randint(0, self.num)] - self.x[j])
x1 = self.x[j] + v1
x1 = np.clip(x1, 0, 1)
fitness1 = func(x1)
if fitness1 < self.fitness[j]:
self.x[j] = x1
self.fitness[j] = fitness1
self.v[j] = v1
if fitness1 < self.fitness_best:
self.x_best = x1
self.fitness_best = fitness1
return self.x_best, self.fitness_best
def func(x):
return x[0]**2
mantis = Mantis(1, 20)
x_best, fitness_best = mantis.optimize(func)
print("最优解: ", x_best)
print("最小值: ", fitness_best)
该代码提供了一种可行的基于螳螂优化算法的解决方案,可用于解决多种优化问题,具有一定的优化性能和适应性。在使用该代码时,您需要按照具体问题设计相应的评价函数并将其作为参数传递给optimize函数。
暂无评论