from scipy.optimize import minimize
import matplotlib.pyplot as plt
import numpy as np
def f_xy(xy):# input should be ndarray
r = xy + np.array([-5, -1])
return r.dot(r) + 10
sample_size = 100
xs = np.linspace(-10, 10, sample_size)
ys = np.linspace(-10, 20, sample_size)
xs, ys = np.meshgrid(xs, ys)
zs = np.array([f_xy(np.array([x, y])) for x, y in zip(xs.ravel(), ys.ravel())]).reshape(sample_size, sample_size)
plt.figure(figsize=(15, 5))
plt.contour(xs, ys, zs, levels = np.logspace(1, 3, 20), cmap=plt.cm.rainbow) # draw
# optimization
x0 = np.array([-7.5, 5]) # 초기값
result = sp.optimize.minimize(f_xy, x0) # optimization
if result['success']==True:
x_opt, y_opt = result['x']
plt.annotate('global optimum: {:.2f}'.format(result['fun']), xy=(x_opt, y_opt), xytext=(x_opt-2, y_opt+5),
fontsize=20, arrowprops=dict(facecolor='black', shrink=0.05, linewidth=1),
)
plt.scatter(x_opt, y_opt, s=500, color='red')
plt.arrow(x0[0], x0[1], x_opt-x0[0], y_opt-x0[1],
head_width=1, head_length=0.4, fc='k', ec='k', lw=2)
#plt.colorbar()
# plt.scatter를 쓸 경우에, plt.colorbar는 쓸 수 없음
plt.savefig('../../assets/images/markdown_img/180615_1514_optimization_contour.svg')
plt.show()
댓글남기기