質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Chainer

Chainerは、国産の深層学習フレームワークです。あらゆるニューラルネットワークをPythonで柔軟に書くことができ、学習させることが可能。GPUをサポートしており、複数のGPUを用いた学習も直感的に記述できます。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

4164閲覧

ChainerでActualエラーが出ます

退会済みユーザー

退会済みユーザー

総合スコア0

Chainer

Chainerは、国産の深層学習フレームワークです。あらゆるニューラルネットワークをPythonで柔軟に書くことができ、学習させることが可能。GPUをサポートしており、複数のGPUを用いた学習も直感的に記述できます。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2018/09/10 12:43

編集2018/09/10 12:44

見よう見まねでChainerに挑戦しているのですが、エラーが解決できず詰まってしまいました。
出力結果からそれとなく当たりを付けてprint(y)、print(t)を出力してみたのですが、見てみてもいまいち理解できませんでした。

お知恵を拝借できれば幸いです、よろしくお願いします。

以下プログラムです。

python

1import matplotlib.pyplot as plt 2import numpy as np 3import chainer 4import chainer.links as L 5import chainer.functions as F 6from chainer import Chain, Variable, datasets, optimizers 7from chainer import report, training 8from chainer.training import extensions 9 10# CSVファイルからデータを取得 11data = np.loadtxt(r"c:\users\owner\dropbox\python\zaif\xem_trades_1min.csv",delimiter=",",skiprows=1).astype(np.float32) 12 13# データを入力変数xと出力変数tに切り分け 14x, t = [], [] 15N = len(data) 16M = 30 # 入力変数の数:直近30サンプルを使用 17for n in range(M, N): 18 # 入力変数と出力変数の切り分け 19 _x = data[n-M: n] # 入力変数 20 _t = data[n] # 出力変数 21 # 計算用のリスト(x, t)に追加していく 22 x.append(_x) 23 t.append(_t) 24 25# 70%を訓練用、30%を検証用 26N_train = int(N * 0.7) 27x_train, x_test = x[:N_train], x[N_train:] 28t_train, t_test = t[:N_train], t[N_train:] 29 30# ###################################################################### 31 32class LSTM(Chain): 33 # モデルの構造を明記 34 def __init__(self, n_units, n_output): 35 super().__init__() 36 with self.init_scope(): 37 self.l1 = L.LSTM(None, n_units) # LSTMの層を追加 38 self.l2 = L.Linear(None, n_output) 39 40 # LSTM内で保持する値をリセット 41 def reset_state(self): 42 self.l1.reset_state() 43 44 # 損失関数の計算 45 def __call__(self, x, t, train=True): 46 y = self.predict(x, train) 47 print(y) 48 print(t) 49 loss = F.mean_squared_error(y, t) 50 if train: 51 report({'loss': loss}, self) 52 return loss 53 54 # 順伝播の計算 55 def predict(self, x, train=False): 56 h1 = self.l1(x) 57 h2 = self.l2(h1) 58 return h2 59 60class LSTMUpdater(training.StandardUpdater): 61 def __init__(self, data_iter, optimizer, device=None): 62 super(LSTMUpdater, self).__init__(data_iter, optimizer, device=None) 63 self.device = device 64 65 def update_core(self): 66 data_iter = self.get_iterator("main") 67 optimizer = self.get_optimizer("main") 68 69 batch = data_iter.__next__() 70 x_batch, y_batch = chainer.dataset.concat_examples(batch, self.device) 71 72 # ↓ ここで reset_state() を実行 73 optimizer.target.reset_state() 74 75 # その他は時系列系の更新と同じ 76 optimizer.target.cleargrads() 77 loss = optimizer.target(x_batch, y_batch) 78 loss.backward() 79 loss.unchain_backward() 80 optimizer.update() 81 82# chainer用のデータセットでメモリに乗る程度であれば、list(zip(...))を推奨 83train = list(zip(x_train, t_train)) 84test = list(zip(x_test, t_test)) 85 86# 再現性確保 87np.random.seed(1) 88 89# モデルの宣言 90model = LSTM(30, 1) 91 92# optimizerの定義 93optimizer = optimizers.Adam() # 最適化アルゴリズムはAdamを使用 94optimizer.setup(model) 95 96# iteratorの定義 97batchsize = 20 98train_iter = chainer.iterators.SerialIterator(train, batchsize) 99test_iter = chainer.iterators.SerialIterator(test, batchsize, repeat=False, shuffle=False) 100 101# updaterの定義 102updater = LSTMUpdater(train_iter, optimizer) 103 104# trainerの定義 105epoch = 30 106trainer = training.Trainer(updater, (epoch, 'epoch'), out='result') 107# trainerの拡張機能 108trainer.extend(extensions.Evaluator(test_iter, model)) # 評価データで評価 109trainer.extend(extensions.LogReport(trigger=(1, 'epoch'))) # 学習結果の途中を表示する 110# 1エポックごとに、trainデータに対するlossと、testデータに対するlossを出力させる 111trainer.extend(extensions.PrintReport(['epoch', 'main/loss', 'validation/main/loss', 'elapsed_time']), trigger=(1, 'epoch')) 112 113trainer.run() 114

以下出力結果です。

variable([[-0.12058719] [-0.1250692 ] [-0.12416833] [-0.12583536] [-0.11827108] [-0.12342366] [-0.12431259] [-0.11912934] [-0.12495534] [-0.12352941] [-0.12308349] [-0.12345908] [-0.126978 ] [-0.11943891] [-0.12412573] [-0.12325455] [-0.12690401] [-0.1271135 ] [-0.12175418] [-0.12275664]]) [12.3902 11.0913 11.39 11.27 12.3996 11.7 11.4504 12.3 11.255 11.4297 11.593 11.5601 11.3011 12.4398 11.375 11.3999 11.2402 11.3901 12.02 11.8603] Exception in main training loop: Invalid operation is performed in: MeanSquaredError (Forward) Expect: in_types[0].shape == in_types[1].shape Actual: (20, 1) != (20,) Traceback (most recent call last): File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\training\trainer.py", line 308, in run update() File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\training\updaters\standard_updater.py", line 149, in update self.update_core() File "C:\Users\Owner\Dropbox\python\zaif\learning_4.py", line 81, in update_core loss = optimizer.target(x_batch, y_batch) File "C:\Users\Owner\Dropbox\python\zaif\learning_4.py", line 53, in __call__ loss = F.mean_squared_error(y, t) File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\functions\loss\mean_squared_error.py", line 61, in mean_squared_error return MeanSquaredError().apply((x0, x1))[0] File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\function_node.py", line 243, in apply self._check_data_type_forward(in_data) File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\function_node.py", line 328, in _check_data_type_forward self.check_type_forward(in_type) File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\functions\loss\mean_squared_error.py", line 17, in check_type_forward in_types[0].shape == in_types[1].shape File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\utils\type_check.py", line 524, in expect expr.expect() File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\utils\type_check.py", line 482, in expect '{0} {1} {2}'.format(left, self.inv, right)) Will finalize trainer extensions and updater before reraising the exception. Traceback (most recent call last): File "C:\Users\Owner\Dropbox\python\zaif\learning_4.py", line 119, in <module> trainer.run() File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\training\trainer.py", line 322, in run six.reraise(*sys.exc_info()) File "C:\Users\Owner\Anaconda3\lib\site-packages\six.py", line 693, in reraise raise value File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\training\trainer.py", line 308, in run update() File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\training\updaters\standard_updater.py", line 149, in update self.update_core() File "C:\Users\Owner\Dropbox\python\zaif\learning_4.py", line 81, in update_core loss = optimizer.target(x_batch, y_batch) File "C:\Users\Owner\Dropbox\python\zaif\learning_4.py", line 53, in __call__ loss = F.mean_squared_error(y, t) File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\functions\loss\mean_squared_error.py", line 61, in mean_squared_error return MeanSquaredError().apply((x0, x1))[0] File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\function_node.py", line 243, in apply self._check_data_type_forward(in_data) File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\function_node.py", line 328, in _check_data_type_forward self.check_type_forward(in_type) File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\functions\loss\mean_squared_error.py", line 17, in check_type_forward in_types[0].shape == in_types[1].shape File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\utils\type_check.py", line 524, in expect expr.expect() File "C:\Users\Owner\Anaconda3\lib\site-packages\chainer\utils\type_check.py", line 482, in expect '{0} {1} {2}'.format(left, self.inv, right)) chainer.utils.type_check.InvalidType: Invalid operation is performed in: MeanSquaredError (Forward) Expect: in_types[0].shape == in_types[1].shape Actual: (20, 1) != (20,)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Q71

2018/09/28 12:24

actualはエラーではなく、期待と違う値が来た、その実態はこれだ、の「実態」です。tとyのshapeを見て下さい。
guest

回答1

0

ベストアンサー

30行目に以下を挿入で解決できました。

x = np.array(x)
t = np.array(t).reshape(len(t), 1)

Q71様ご指摘の通りでした、本当にありがとうございました。

投稿2018/10/07 00:27

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問