アプリ版:「スタンプのみでお礼する」機能のリリースについて

以下のpythonの記述を実行させると、38行目のと41行目のprint文の結果が下記のような結果のなってしまって、リストのtheta_valuesにtheta_currentをアペンドできずに全てtheta_currentの最後の値で
書き変わってしまうようなのですが、理由が分かりかねています。何かアドバイスいただけると助かります。
[38行目のprint文の結果]
[[0.05839135]
[0.6532885 ]]
[[0.06289175]
[0.77000978]]
[[0.05782293]
[0.79134812]]
[[0.05106363]
[0.79572981]]
[[0.04401438]
[0.79709618]]
[41行目のprint文の結果]
[array([[0.04401438],
[0.79709618]]), array([[0.04401438],
[0.79709618]]), array([[0.04401438],
[0.79709618]]), array([[0.04401438],
[0.79709618]]), array([[0.04401438],
[0.79709618]])]

ここから、

1 import numpy as np
2 import matplotlib.pyplot as plt
3
4 # Xの一番左の列に1を挿入する
5 def add_column(X):
6  return np.insert(X, 0, 1, axis=1)
7
8 # 予測を行う(h(x; θ)を計算する)
9 def predict(X, theta):
10 X_prime = add_column(X)
11 return np.dot(theta.T, X_prime.T).T
12
13 # 損失を計算する (J(θ)をコードに落とし込む)
14 def loss(X, y, theta):
15 return (1 / (2 * X.shape[0])) * np.sum((predict(X, theta) - y) ** 2)
16
17 food_truck_data = np.loadtxt('food_truck.txt', delimiter=',')
18 X = food_truck_data[:, 0, np.newaxis]
19 y = food_truck_data[:, 1, np.newaxis]
20
21 theta_init = np.zeros((2, 1))
22 loss(X, y, theta_init)
23
24 # 勾配降下法におけるJ(θ)の微分を計算する
25 def loss_gradient(X, y, theta):
26 X_prime = add_column(X)
27 return (1 / X.shape[0]) * np.dot((predict(X, theta) - y).T, X_prime).T
28
29 # 勾配降下法
30 def run_gd(loss, loss_gradient, X, y, theta_init, lr=0.01, n_iter=5):
31 theta_current = theta_init.copy()
32 loss_values = []
33 theta_values = []
34
35 for i in range(n_iter):
36  loss_value = loss(X, y, theta_current)
37  theta_current -= lr * loss_gradient(X, y, theta_current)
38  print(theta_current)
39  loss_values.append(loss_value)
40  theta_values.append(theta_current)
41 print(theta_values)
42
43 return theta_current, loss_values, theta_values
44
45 theta_est, loss_values, theta_values = run_gd(loss, loss_gradient, X, y, the ta_init)

質問者からの補足コメント

  • 38行目のtheta_currentも(2, 1)のndarrayです。

    No.1の回答に寄せられた補足コメントです。 補足日時:2022/12/06 22:10
  • 40行目のtheta_values.append(theta_current)をtheta_values.append(theta_current.tolist())
    にしてリストでappendするとうまくいく様です。でもインターラクティブモードで実験してみるとリストへのndarrayのappendは問題なくできる様なのですが、何故この場合はうまくいかないのでしょうか?

      補足日時:2022/12/07 09:34

A 回答 (1件)

41行目の print で出すときに


array(なんとか)
と出ていることに疑問はないのだろうか.
この回答への補足あり
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!