scikit-opt
點擊進入官網下載,或者按照官網上寫的 pip install 安裝
3.1 模擬退火算法用於多元函數優化
from sko.SA import SA
def demo_func(x):
x1, x2, x3 = x
return x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2
sa = SA(func=demo_func, x0=[1, 1, 1])
x_star, y_star = sa.fit()
print(x_star, y_star)
import matplotlib.pyplot as plt
import pandas as pd
plt.plot(pd.DataFrame(sa.f_list).cummin(axis=0))
plt.show()
3.2 模擬退火算法解決TSP問題
TSP問題(旅行商問題)
作爲demo,生成模擬數據(代碼與遺傳算法解決TSP問題一樣,這裏省略)
調用模擬退火算法
from sko.SA import SA_TSP
sa_tsp = SA_TSP(func=demo_func, x0=range(num_points))
best_points, best_distance = sa_tsp.fit()
畫出結果
fig, ax = plt.subplots(1, 1)
best_points_ = np.concatenate([best_points, [best_points[0]]])
best_points_coordinate = points_coordinate[best_points_, :]
ax.plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r')
plt.show()
以上代碼全部整理到 這裏,加上實現下面這個動畫的代碼