前提・実現したいこと
Pythonで準ニュートン法の実装をしています。
以下のようなエラーが出たのですが
どう直せばよいのでしょうか?
y = np.matrix(-(dsc_f(x_1,x_2)[0]) + dsc_f(pre_x_1,pre_x_2)[0], -(dsc_f(x_1,x_2)[1]) + dsc_f(pre_x_1,pre_x_2)[1]).T #-dsc_f(x_1, x_2)+dsc_f(pre_x_1,pre_x_2)とするとbad operand type for unary -: 'tuple'となったので
がよくないのかなと考えてみたのですがあまりうまくいかず…
発生している問題・エラーメッセージ
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-166-10dbead19cdf> in <module>() 29 30 #準(quasi-)ニュートン法~初期値a ---> 31 QNa_1,QNa_2 = q_newton(1.2, 1.2, 0.1, 0.1, 0.1) 32 print(QNa_1,QNa_2) 33 #準(quasi-)ニュートン法~初期値b <ipython-input-166-10dbead19cdf> in q_newton(x_1, x_2, a_0, c, p) 18 s = np.matrix([x_1 - pre_x_1,x_2-pre_x_2]).T 19 y = np.matrix(-(dsc_f(x_1,x_2)[0]) + dsc_f(pre_x_1,pre_x_2)[0], -(dsc_f(x_1,x_2)[1]) + dsc_f(pre_x_1,pre_x_2)[1]).T ---> 20 B = B-(B * s *(B * s).T) / (s.T * B * s) + (y * y.T) / (s.T * y) #BFGS更新公式 21 d = np.linalg.solve(B,g) 22 while (f(x_1 + a * d[0],x_2 + a * d[1]) > f(x_1,x_2) - c * a * abs(np.linalg.norm(d))):#armijoの条件 ~\Anaconda3\lib\site-packages\numpy\matrixlib\defmatrix.py in __mul__(self, other) 213 if isinstance(other, (N.ndarray, list, tuple)) : 214 # This promotes 1-D vectors to row vectors --> 215 return N.dot(self, asmatrix(other)) 216 if isscalar(other) or not hasattr(other, '__rmul__') : 217 return N.dot(self, other) ValueError: shapes (1,2) and (1,1) not aligned: 2 (dim 1) != 1 (dim 0)
該当のソースコード
Python
1def q_newton(x_1,x_2,a_0,c,p): 2 eps = 1e-5 3 h_1 = [x_1,] #x_1のhistory 4 h_2 = [x_2,] 5 pre_x_1,pre_x_2 = x_1,x_2 #更新公式でs=x_k+1-x_kを使うので 6 B = np.matrix(hessian(x_1,x_2)) 7 g = np.array(dsc_f(x_1,x_2)) 8 d = np.linalg.solve(B,g) 9 x_1, x_2 = [x_1 + d[0],x_2 + d[1]] 10 h_1.append(x_1) 11 h_2.append(x_2) 12 iteration_max = 50 13 a = a_0 14 for i in range(iteration_max): 15 if (np.linalg.norm(dsc_f(x_1,x_2)) < eps): #停止条件 16 break 17 else: 18 s = np.matrix([x_1 - pre_x_1,x_2-pre_x_2]).T 19 y = np.matrix(-(dsc_f(x_1,x_2)[0]) + dsc_f(pre_x_1,pre_x_2)[0], -(dsc_f(x_1,x_2)[1]) + dsc_f(pre_x_1,pre_x_2)[1]).T 20 #-dsc_f(x_1, x_2)+dsc_f(pre_x_1,pre_x_2)とするとbad operand type for unary -: 'tuple'となったので 21 B = B-(B * s *(B * s).T) / (s.T * B * s) + (y * y.T) / (s.T * y) #BFGS更新公式 22 d = np.linalg.solve(B,g) 23 while (f(x_1 + a * d[0],x_2 + a * d[1]) > f(x_1,x_2) - c * a * abs(np.linalg.norm(d))):#armijoの条件 24 a = a * p #↑をみたすように小さくしていく 25 pre_x_1,pre_x_2 = [x_1,x_2] 26 x_1,x_2 = [x_1 + a * d[0], x_2 + a * d[1]] 27 h_1.append(x_1) 28 h_2.append(x_2) 29 return h_1 - 1,h_2 -1 30 31#準(quasi-)ニュートン法~初期値a 32QNa_1,QNa_2 = q_newton(1.2, 1.2, 0.1, 0.1, 0.1) 33print(QNa_1,QNa_2) 34#準(quasi-)ニュートン法~初期値b 35QNb_1,QNb_2 = q_newton(-1.2, 1, 0.1, 0.1, 0.1) 36print(QNa_1,QNa_2)
試したこと
各成分に分解すると出来る
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。