天天看點

Python實作 模拟退火算法庫

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()
           
Python實作 模拟退火算法庫

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()
           
Python實作 模拟退火算法庫

以上代碼全部整理到 這裡,加上實作下面這個動畫的代碼

Python實作 模拟退火算法庫