粒子群优化算法的实践 - 多个约束条件
flyfish
粒子群优化算法的实践 - 目标函数的可视化
粒子群优化算法的实践 - 向量减法
在粒子群优化算法的代码实践中
代码写法是
#非线性约束 (x[0] - 1) ** 2 + (x[1] - 1) ** 2 - 1<=0
constraint_ueq = (
lambda x: (x[0] - 1) ** 2 + (x[1] - 1) ** 2-1
,
)
也是函数
def constraint_ueq(x):
if ((x[0] - 1) ** 2 + (x[1] - 1) ** 2-1) <=0:
return False
return True
u是否定,返回False,是否定,双重否定表肯定
即符合条件(x[0] - 1) ** 2 + (x[1] - 1) ** 2 - 1<=0
、
运行结果是
增加多个约束条件是
两个if条件是or的关系
def constraint_ueq(x):
if ((x[0] - 1) ** 2 + (x[1] - 1) ** 2-1) <=0:
return False
if x[0]>=0 or x[1]<=0:
return False
return True
运行结果是
完整是
import numpy as np
from sko.PSO import PSO
def demo_func(X):
x, y = X
return (x-3.14)**2 + (y-3.14)**2 + np.sin(3*x+3.14) + np.cos(4*y-3.14)
#非线性约束 (x[0] - 1) ** 2 + (x[1] - 1) ** 2 - 1<=0
# constraint_ueq = (
# lambda x: (x[0] - 1) ** 2 + (x[1] - 1) ** 2-1
# ,
# )
# 不等式约束实现
# u是否定,返回False,是否定,双重否定表肯定
# def constraint_ueq(x):
# if ((x[0] - 1) ** 2 + (x[1] - 1) ** 2-1) <=0:
# return False
# return True
def constraint_ueq(x):
if ((x[0] - 1) ** 2 + (x[1] - 1) ** 2-1) <=0:
return False
if x[0]>=0 or x[1]<=0:
return False
return True
constraint_ueq=[constraint_ueq]
max_iter = 30
# lb None 每个参数的最小值
# ub None 每个参数的最大值
pso = PSO(func=demo_func, n_dim=2, pop=40, max_iter=max_iter, lb=[-1, -1], ub=[5, 5],constraint_ueq=constraint_ueq)
pso.record_mode = True
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
record_value = pso.record_value
X_list, V_list = record_value['X'], record_value['V']
fig, ax = plt.subplots(1, 1)
ax.set_title('title', loc='center')
line = ax.plot([], [], 'b.')
X_grid, Y_grid = np.meshgrid(np.linspace(0,5,100), np.linspace(0,5,100))
Z_grid = demo_func((X_grid, Y_grid))
ax.contour(X_grid, Y_grid, Z_grid, 10)
ax.set_xlim([0,5])
ax.set_ylim([0,5])
draw_circle=plt.Circle((1.8, 1.5), 0.5,fill=False,color='r')
ax.add_artist(draw_circle)
plt.ion()
p = plt.show()
def update_scatter(frame):
i, j = frame // 10, frame % 10
ax.set_title('iter = ' + str(i))
X_tmp = X_list[i] + V_list[i] * j / 10.0
plt.setp(line, 'xdata', X_tmp[:, 0], 'ydata', X_tmp[:, 1])
return line
ani = FuncAnimation(fig, update_scatter, blit=True, interval=25, frames=max_iter * 10)
plt.show()
ani.save('PSO_2.gif', writer='pillow')