エラー
ValueError: Length mismatch: Expected axis has 1 elements, new values have 5 elements
読み込みデータ
date open high low close
2016-01-04 2703 2725 2663 2663
2016-01-05 2658 2669 2647 2647
2016-01-06 2649 2700 2614 2625
2016-01-07 2604 2624 2566 2569
pytho3
1import numpy as np 2import pandas as pd 3import matplotlib.pyplot as plt 4from sklearn import preprocessing 5from keras.models import Sequential 6from keras.layers.core import Dense, Activation 7from keras.layers.recurrent import LSTM 8 9class Prediction : 10 11 def __init__(self): 12 self.length_of_sequences = 10 13 self.in_out_neurons = 1 14 self.hidden_neurons = 300 15 16 17 def load_data(self, data, n_prev=10): 18 X, Y = [], [] 19 for i in range(len(data) - n_prev): 20 X.append(data.iloc[i:(i+n_prev)].as_matrix()) 21 Y.append(data.iloc[i+n_prev].as_matrix()) 22 retX = np.array(X) 23 retY = np.array(Y) 24 return retX, retY 25 26 27 def create_model(self) : 28 model = Sequential() 29 model.add(LSTM(self.hidden_neurons, \ 30 batch_input_shape=(None, self.length_of_sequences, self.in_out_neurons), \ 31 return_sequences=False)) 32 model.add(Dense(self.in_out_neurons)) 33 model.add(Activation("linear")) 34 model.compile(loss="mape", optimizer="adam") 35 return model 36 37 38 def train(self, X_train, y_train) : 39 model = self.create_model() 40 # 学習 41 model.fit(X_train, y_train, batch_size=10, nb_epoch=100) 42 return model 43 44 45if __name__ == "__main__": 46 47 prediction = Prediction() 48 49 # データ準備 50 data = None 51 for year in range(2015, 2016): 52 data_ = pd.read_csv('1547_' + str(year) + '.csv',encoding="shift_jis") 53 data = data_ if (data is None) else pd.concat([data,data_]) 54 data.columns = ['date','open','high','low','close'] 55 data['date'] = pd.to_datetime(data['date'], format='%Y-%m-%d') 56 57 # 終値のデータを標準化 58 data['close'] = preprocessing.scale(data['close']) 59 data = data.sort_values(by='date') 60 data = data.reset_index(drop=True) 61 data = data.loc[:, ['date', 'close']] 62 63 # 2割をテストデータへ 64 split_pos = int(len(data) * 0.8) 65 x_train, y_train = prediction.load_data(data[['close']].iloc[0:split_pos], prediction.length_of_sequences) 66 x_test, y_test = prediction.load_data(data[['close']].iloc[split_pos:], prediction.length_of_sequences) 67 68 model = prediction.train(x_train, y_train) 69 70 predicted = model.predict(x_test) 71 result = pd.DataFrame(predicted) 72 result.columns = ['predict'] 73 result['actual'] = y_test 74 result.plot() 75 plt.show()
回答1件
あなたの回答
tips
プレビュー