前提・実現したいこと
pythonのkerasのlstmを使ってbitcoinの機械学習をしようとしています。
modelを作り訓練用のデータを読み込ませようとしたところ以下のエラーメッセージが発生しました。
発生している問題・エラーメッセージ
InvalidArgumentError Traceback (most recent call last) <ipython-input-103-7934a75cb485> in <module> 1 history = lstm_model.fit(train_x, train_y, epochs=10, verbose=2, batch_size=batch_size, ----> 2 shuffle=False, validation_data=(test_x, test_y)) ~\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing) 1098 _r=1): 1099 callbacks.on_train_batch_begin(step) -> 1100 tmp_logs = self.train_function(iterator) 1101 if data_handler.should_sync: 1102 context.async_wait() ~\Anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py in __call__(self, *args, **kwds) 826 tracing_count = self.experimental_get_tracing_count() 827 with trace.Trace(self._name) as tm: --> 828 result = self._call(*args, **kwds) 829 compiler = "xla" if self._experimental_compile else "nonXla" 830 new_tracing_count = self.experimental_get_tracing_count() ~\Anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py in _call(self, *args, **kwds) 853 # In this case we have created variables on the first call, so we run the 854 # defunned version which is guaranteed to never create variables. --> 855 return self._stateless_fn(*args, **kwds) # pylint: disable=not-callable 856 elif self._stateful_fn is not None: 857 # Release the lock early so that multiple threads can perform the call ~\Anaconda3\lib\site-packages\tensorflow\python\eager\function.py in __call__(self, *args, **kwargs) 2941 filtered_flat_args) = self._maybe_define_function(args, kwargs) 2942 return graph_function._call_flat( -> 2943 filtered_flat_args, captured_inputs=graph_function.captured_inputs) # pylint: disable=protected-access 2944 2945 @property ~\Anaconda3\lib\site-packages\tensorflow\python\eager\function.py in _call_flat(self, args, captured_inputs, cancellation_manager) 1917 # No tape is watching; skip to running the function. 1918 return self._build_call_outputs(self._inference_function.call( -> 1919 ctx, args, cancellation_manager=cancellation_manager)) 1920 forward_backward = self._select_forward_and_backward_functions( 1921 args, ~\Anaconda3\lib\site-packages\tensorflow\python\eager\function.py in call(self, ctx, args, cancellation_manager) 558 inputs=args, 559 attrs=attrs, --> 560 ctx=ctx) 561 else: 562 outputs = execute.execute_with_cancellation( ~\Anaconda3\lib\site-packages\tensorflow\python\eager\execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name) 58 ctx.ensure_initialized() 59 tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, ---> 60 inputs, attrs, num_outputs) 61 except core._NotOkStatusException as e: 62 if name is not None: InvalidArgumentError: Specified a list with shape [32,7] from a tensor with shape [14,7] [[{{node TensorArrayUnstack/TensorListFromTensor}}]] [[sequential_17/lstm_28/PartitionedCall]] [Op:__inference_train_function_43207] Function call stack: train_function -> train_function -> train_function
該当のソースコード
python
1import numpy as np 2import pandas as pd 3import quandl 4import matplotlib.pyplot as plt 5from sklearn.preprocessing import MinMaxScaler 6from sklearn.model_selection import train_test_split 7# put your api key 8quandl.ApiConfig.api_key = "api_key" 9df = quandl.get("BITFINEX/BTCJPY") 10# dataframeを正規化 11mm = MinMaxScaler() 12df_min_max = pd.DataFrame(mm.fit_transform(df), 13 index=df.index, columns=df.columns) 14#train_dfとtest_dfに分ける 15train_df, test_df = train_test_split(df_min_max, test_size=0.2, shuffle=False) 16#説明変数xに過去6日間のデータ、目的変数yに翌日のlastのデータを追加したリストを作る 17interval = 6 18def make_data(data): 19 x = [] 20 y = [] 21 last = list(data["Last"]) 22 for i in range(len(last)): 23 if i < interval: continue 24 y.append(last[i]) 25 xa = [] 26 for p in range(interval): 27 d = i + p - interval 28 xb = [] 29 for feature in data: 30 features = data[feature] 31 xb.append(features[d]) 32 xa.append(xb) 33 x.append(xa) 34 return (x, y) 35train_x, train_y = make_data(train_df) 36test_x, test_y = make_data(test_df) 37train_x = np.array(train_x) 38test_x = np.array(test_x) 39print(train_x.shape) #(846, 6, 7)となる 40print(test_x.shape) #(207, 6, 7)となる 41train_y = np.array(train_y) 42test_y = np.array(test_y) 43print(train_y.shape) #(846,)となる 44print(test_y.shape) #(207,)となる 45#lstm_modelを作る 46batch_size=32 47learning_rate=0.001 48from keras.models import Sequential 49from keras.layers import LSTM 50from keras.layers import Dense, Dropout 51from keras import optimizers 52lstm_model = Sequential() 53lstm_model.add(LSTM(100, batch_input_shape=(batch_size, 6, 7), 54 dropout=0.0, recurrent_dropout=0.0, stateful=True, return_sequences=True, 55 kernel_initializer='random_uniform')) 56lstm_model.add(Dropout(0.4)) 57lstm_model.add(LSTM(60, dropout=0.0)) 58lstm_model.add(Dropout(0.4)) 59lstm_model.add(Dense(20,activation='relu')) 60lstm_model.add(Dense(1,activation='sigmoid')) 61optimizer = optimizers.RMSprop(lr=learning_rate) 62lstm_model.compile(loss='mean_squared_error', optimizer=optimizer) 63#lstm_modelをfitする 64history = lstm_model.fit(train_x, train_y, epochs=10, verbose=2, batch_size=batch_size, 65 shuffle=False, validation_data=(test_x, test_y)) #ここでエラー
試したこと
batch_input_shapeの値に問題があると思い様々な数値(14など)に変えたのですがうまくいきません。
補足情報(FW/ツールのバージョンなど)
python3
参考にさせていただいたサイト
https://qiita.com/satken2/items/5d95f1580f65bed50add
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/03/26 00:00