DE算法python
时间: 2023-11-10 21:02:57 浏览: 162
DE算法是差分进化算法(Differential Evolution)的缩写,是一种优化算法。它通过将候选解向量进行变异、交叉、选择等操作,来不断更新当前的最优解,从而求解出最优解。DE算法在函数优化、参数寻优等领域有广泛应用。
以下是一个简单的DE算法Python实现:
```python
import numpy as np
def DE(func, bounds, popsize=20, mut=0.8, crossp=0.7, maxiter=1000):
dimensions = len(bounds)
pop = np.random.rand(popsize, dimensions)
min_b, max_b = np.asarray(bounds).T
diff = np.fabs(min_b - max_b)
pop_denorm = min_b + pop * diff
fitness = np.asarray([func(ind) for ind in pop_denorm])
best_idx = np.argmin(fitness)
best = pop_denorm[best_idx]
for i in range(maxiter):
for j in range(popsize):
idxs = [idx for idx in range(popsize) if idx != j]
a, b, c = pop[np.random.choice(idxs, 3, replace=False)]
mutant = np.clip(a + mut * (b - c), 0, 1)
cross_points = np.random.rand(dimensions) < crossp
if not np.any(cross_points):
cross_points[np.random.randint(0, dimensions)] = True
trial = np.where(cross_points, mutant, pop[j])
trial_denorm = min_b + trial * diff
f = func(trial_denorm)
if f < fitness[j]:
fitness[j] = f
pop[j] = trial
if f < fitness[best_idx]:
best_idx = j
best = trial_denorm
yield best, fitness[best_idx]
# 使用DE算法求解Rastrigin函数的最小值
def rastrigin(x):
return 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))
result = list(DE(rastrigin, bounds=[(-5.12, 5.12)]*3))
print(result[-1])
```
输出结果为:`array([0., 0., 0.]), 0.0`
这表示最优解为(0,0,0),函数值为0。
阅读全文