#これはPython 3環境がインストールされ、多くの有用な分析ライブラリが付属しています 。#https://github.com/kaggle/docker-python:それはkaggle / Pythonのドッキングウィンドウの画像によって定義されている #たとえば、ここでロードするには、いくつかの有用なパッケージです インポートmatplotlibのをPLTのよう.pyplot 輸入のSMTとしてstatsmodels.tsa.seasonal 輸入のNPとしてnumpyの#の線形代数 輸入 PDのようパンダ#のデータ処理、CSVファイルI / O(例えばpd.read_csv) をインポートランダム 輸入DTとして日時を から sklearnのインポートlinear_model からsklearn.metricsはインポートmean_absolute_errorの インポートをplotly #関連Kerasモジュールをインポート から keras.models インポートシーケンシャルを から keras.layers インポートアクティベーションを、高密度 から keras.layersがインポートLSTMを から keras.layers インポートドロップアウト #の入力データファイルは「でご利用いただけます。.. /入力/」ディレクトリ。 #例えば、(実行をクリックするか、Shiftキー+ Enterキーを押して)これを実行すると、入力されたディレクトリ内のファイルを一覧表示されます から、サブプロセスのインポート check_output
輸入OSの os.chdir(' F:\\ kaggleDataSet \\価格、ボリューム\\株式')
#は、データの読み込み #のカーネルは、それがディレクトリであるかのように、私たちは、zipファイルをナビゲートしてみましょう #サイズがゼロのファイルを読み込むしようとしているが、エラーをスローするので、それらをスキップします #X場合)os.listdir中のxのファイル名= [X(。 endswith(」TXT ')とos.path.getsize(X)> 0] #ファイル名= random.sample(ファイル名、1) ファイル名= [ ' prk.us.txt ' ' bgr.us.txt ' ' jci.us.txt ' ' aa.us.txt ' ' fr.us.txt ' ' star.us.txt 」、"sons.us.txt ' ' ipl_d.us.txt ' ' sna.us.txt ' ' utg.us.txt ' ] ファイル名 = [ファイル名[1 ] 印刷(ファイル名) データ = [] のためのファイル名でファイル名: DF = pd.read_csv(ファイル名、9月= ' ' ) ラベル、_、_(9月= = filename.split ' ' ) [DF ' ラベル' ] = ファイル名 DF [' 日' ] = pd.to_datetime(DF [ ' 日' ]) data.append(DF)
トレース= [] のための DF でのデータ: CLR = STR(R())+ STR(R())+ STR(R()) DF = df.sort_values(' 日' ) ラベル =のDF [ ' ラベル' ]。 ILOC [0] トレース = plotly.graph_objs.Scattergl(X = DF [ ' 日' ]、Y = DF [ ' 閉じる' ]) traces.append(トレース) レイアウト = plotly.graph_objs.Layout(タイトル= ' プロット' 、 ) 図 = plotly.graph_objs.Figure(データ=トレース、レイアウト=レイアウト) plotly.offline.init_notebook_mode(接続 = TRUE) plotly.offline.iplot(図、ファイル名 = ' DATAPLOT ')
df = data[0] window_len = 10 #Create a data point (i.e. a date) which splits the training and testing set split_date = list(data[0]["Date"][-(2*window_len+1):])[0] #Split the training and test set training_set, test_set = df[df['Date'] < split_date], df[df['Date'] >= split_date] training_set = training_set.drop(['Date','Label', 'OpenInt'], 1) test_set = test_set.drop(['Date','Label','OpenInt'], 1) #Create windows for training LSTM_training_inputs = [] for i in range(len(training_set)-window_len): temp_set = training_set[i:(i+window_len)].copy() for col in list(temp_set): temp_set[col] = temp_set[col]/temp_set[col].iloc[0] - 1 LSTM_training_inputs.append(temp_set) LSTM_training_outputs = (training_set['Close'][window_len:].values/training_set['Close'][:-window_len].values)-1 LSTM_training_inputs = [np.array(LSTM_training_input) for LSTM_training_input in LSTM_training_inputs] LSTM_training_inputs = np.array(LSTM_training_inputs) #Create windows for testing LSTM_test_inputs = [] for i in range(len(test_set)-window_len): temp_set = test_set[i:(i+window_len)].copy() for col in list(temp_set): temp_set[col] = temp_set[col]/temp_set[col].iloc[0] - 1 LSTM_test_inputs.append(temp_set) LSTM_test_outputs = (test_set['Close'][window_len:].values/test_set['Close'][:-window_len].values)-1 LSTM_test_inputs = [np.array(LSTM_test_inputs) for LSTM_test_inputs in LSTM_test_inputs] LSTM_test_inputs = np.array(LSTM_test_inputs)
def build_model(inputs, output_size, neurons, activ_func="linear",dropout=0.10, loss="mae", optimizer="adam"): model = Sequential() model.add(LSTM(neurons, input_shape=(inputs.shape[1], inputs.shape[2]))) model.add(Dropout(dropout)) model.add(Dense(units=output_size)) model.add(Activation(activ_func)) model.compile(loss=loss, optimizer=optimizer) return model
# initialise model architecture nn_model = build_model(LSTM_training_inputs, output_size=1, neurons = 32) # model output is next price normalised to 10th previous closing price # train model on data # note: eth_history contains information on the training error per epoch nn_history = nn_model.fit(LSTM_training_inputs, LSTM_training_outputs, epochs=5, batch_size=1, verbose=2, shuffle=True)
plt.plot(LSTM_test_outputs, label = "actual") plt.plot(nn_model.predict(LSTM_test_inputs), label = "predicted") plt.legend() plt.show() MAE = mean_absolute_error(LSTM_test_outputs, nn_model.predict(LSTM_test_inputs)) print('The Mean Absolute Error is: {}'.format(MAE))
#https://github.com/llSourcell/How-to-Predict-Stock-Prices-Easily-Demo/blob/master/lstm.py def predict_sequence_full(model, data, window_size): #Shift the window by 1 new prediction each time, re-run predictions on new window curr_frame = data[0] predicted = [] for i in range(len(data)): predicted.append(model.predict(curr_frame[np.newaxis,:,:])[0,0]) curr_frame = curr_frame[1:] curr_frame = np.insert(curr_frame, [window_size-1], predicted[-1], axis=0) return predicted predictions = predict_sequence_full(nn_model, LSTM_test_inputs, 10) plt.plot(LSTM_test_outputs, label="actual") plt.plot(predictions, label="predicted") plt.legend() plt.show() MAE = mean_absolute_error(LSTM_test_outputs, predictions) print('The Mean Absolute Error is: {}'.format(MAE))
结论
LSTM不能解决时间序列预测问题。对一个时间步长的预测并不比滞后模型好多少。如果我们增加预测的时间步长,性能下降的速度就不会像其他更传统的方法那么快。然而,在这种情况下,我们的误差增加了大约4.5倍。它随着我们试图预测的时间步长呈超线性增长。