蜣螂算法python
时间: 2023-10-24 07:26:34 浏览: 155
蜣螂算法(Firefly Algorithm)是一种启发式优化算法,模拟了萤火虫在寻找伴侣过程中的行为。它通过模拟萤火虫之间的相互吸引和斥力来搜索最优解。下面是一个用Python实现蜣螂算法的示例代码:
```python
import math
import random
class FireflyAlgorithm:
def __init__(self, problem_size, objective_func, lower_bound, upper_bound, population_size=50, alpha=0.5, beta0=1.0, gamma=1.0):
self.problem_size = problem_size
self.objective_func = objective_func
self.lower_bound = lower_bound
self.upper_bound = upper_bound
self.population_size = population_size
self.alpha = alpha
self.beta0 = beta0
self.gamma = gamma
self.population = []
def initialize_population(self):
for _ in range(self.population_size):
individual = [random.uniform(self.lower_bound, self.upper_bound) for _ in range(self.problem_size)]
self.population.append(individual)
def attractiveness(self, beta, distance):
return math.exp(-beta * distance)
def distance(self, x, y):
return math.sqrt(sum((xi - yi) ** 2 for xi, yi in zip(x, y)))
def move_fireflies(self):
for i in range(self.population_size):
for j in range(self.population_size):
if self.objective_func(self.population[j]) < self.objective_func(self.population[i]):
distance = self.distance(self.population[i], self.population[j])
beta = self.beta0 * math.exp(-self.gamma * distance ** 2)
for k in range(self.problem_size):
self.population[i][k] += self.alpha * (self.population[j][k] - self.population[i][k]) + beta * random.uniform(-1, 1)
def optimize(self, max_generations=100):
self.initialize_population()
for _ in range(max_generations):
self.move_fireflies()
best_solution = min(self.population, key=self.objective_func)
return best_solution
# 使用示例
def sphere_function(x):
return sum(xi ** 2 for xi in x)
algorithm = FireflyAlgorithm(problem_size=5, objective_func=sphere_function, lower_bound=-10, upper_bound=10)
best_solution = algorithm.optimize()
print("Best solution:", best_solution)
```
在上面的示例代码中,我们首先定义了一个`FireflyAlgorithm`类来实现蜣螂算法。在初始化方法中,我们传入问题的维度`problem_size`、目标函数`objective_func`、变量的取值范围`lower_bound`和`upper_bound`等参数。然后,我们使用`initialize_population`方法初始化种群,并使用`move_fireflies`方法模拟蜣螂的移动过程。最后,通过调用`optimize`方法,我们可以获取到找到的最优解。
在这个示例中,我们使用了经典的优化问题——球函数(Sphere Function)作为目标函数。你可以根据自己的需求来定义不同的目标函数和问题。
阅读全文