発生している問題・エラーメッセージ
<ipython-input-8-47a407e0b23b>:13: RuntimeWarning: overflow encountered in double_scalars return np.array([10 * x - 6 * y + 6, -6 * x + 6 * y - 6]) TypeError Traceback (most recent call last) <ipython-input-8-47a407e0b23b> in <module> 33 ax[ i ].set_xlim((xmin, xmax)) 34 ax[ i ].set_ylim((ymin, ymax)) ---> 35 ax[ i ].set_title("alpha={}".format(alpha[ i ])) 36 ax[ i ].scatter(initial[0], initial[1], color="k", marker="o") 37 ax[ i ].plot(algos[ i ].path_[:, 0], algos[ i ].path_[:, 1], color="k", linewidth=1.5) TypeError: 'float' object is not subscriptable
該当のソースコード
Pyhon3.8
1import numpy as np 2import matplotlib.pyplot as plt 3import gd 4 5def f(xx): 6 x = xx[0] 7 y = xx[1] 8 return 5 * x**2 - 6 * x * y + 3 * y**2 + 6 * x - 6 * y 9 10def df(xx): 11 x = xx[0] 12 y = xx[1] 13 return np.array([10 * x - 6 * y + 6, -6 * x + 6 * y - 6]) 14 15xmin, xmax, ymin, ymax = -3, 3, -3, 3 16 17algos = [] 18initial = np.array([1, 1]) 19alphas = [0.1, 0.2] 20for alpha in alphas : 21 algo = gd.GradientDescent(f, df, alpha) 22 algo.solve(np.array(initial)) 23 algos.append(algo) 24 25xs = np.linspace(xmin, xmax, 300) 26ys = np.linspace(ymin, ymax, 300) 27xmesh, ymesh = np.meshgrid(xs, ys) 28xx = np.r_[xmesh.reshape(1, -1), ymesh.reshape(1, -1)] 29fig, ax = plt.subplots(1, 2) 30levels = [-3, -2.9, -2.8, -2.6, -2.4, -2.2, -2, -1, 0, 1, 2, 3, 4] 31 32for i in range(2) : 33 ax[ i ].set_xlim((xmin, xmax)) 34 ax[ i ].set_ylim((ymin, ymax)) 35 ax[ i ].set_title("alpha={}".format(alpha[ i ])) 36 ax[ i ].scatter(initial[0], initial[1], color="k", marker="o") 37 ax[ i ].plot(algos[ i ].path_[:, 0], algos[ i ].path_[:, 1], color="k", linewidth=1.5) 38 ax[ i ].contour(xs, ys, f(xx).reshape(xmesh.shape), levels=levels, colors="k", linestyles="dotted") 39plt.show()
gdファイル import numpy as np class GradientDescent : def __init__(self, f, df, alpha=0.01, eps=1e-6) : self.f = f self.df = df self.alpha = alpha self.eps = eps self.path = None def solve(self, init): x = init path = [] grad = self.df(x) path.append(x) while (grad**2).sum() > self.eps**2: x = x - self.alpha * grad grad = self.df(x) path.append(x) self.path_ = np.array(path) self.x_ = x self.opt_ = self.f(x)

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2021/09/13 12:25
2021/09/13 12:31
退会済みユーザー
2021/09/13 12:43