python 时间序列预测,python时间序列预测的方法

首页 > 教育 > 作者:YD1662024-05-09 01:33:51

然后将训练和测试数据扩展到[- 1,1]。

scaler = MinMaxScaler(feature_range=(-1, 1)) train_sc = scaler.fit_transform(train) test_sc = scaler.transform(test)

最后,获取训练数据和测试数据。

X_train = train_sc[:-1] y_train = train_sc[1:] X_test = test_sc[:-1] y_test = test_sc[1:]

创建用于时间序列预测的简单ANN

nn_model = Sequential() nn_model.add(Dense(12, input_dim=1, activation='relu')) nn_model.add(Dense(1)) nn_model.compile(loss='mean_squared_error', optimizer='adam') early_stop = EarlyStopping(monitor='loss', patience=2, verbose=1) history = nn_model.fit(X_train, y_train, epochs=100, batch_size=1, verbose=1, callbacks=[early_stop], shuffle=False)

python 时间序列预测,python时间序列预测的方法(5)

这里没有显示全部输出,但我们可以看到它在第19个周期就停止了。

y_pred_test_nn = nn_model.predict(X_test) y_train_pred_nn = nn_model.predict(X_train) print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train, y_train_pred_nn))) print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test, y_pred_test_nn)))

python 时间序列预测,python时间序列预测的方法(6)

LSTM

在创建LSTM时,我们将使用pandas中的shift函数将整列移动1.在下面的代码片段中,我们将列向下移动1.然后我们需要将所有输入变量转换为以3D矢量形式表示。

train_sc_df = pd.DataFrame(train_sc, columns=['Y'], index=train.index) test_sc_df = pd.DataFrame(test_sc, columns=['Y'], index=test.index) for s in range(1,2): train_sc_df['X_{}'.format(s)] = train_sc_df['Y'].shift(s) test_sc_df['X_{}'.format(s)] = test_sc_df['Y'].shift(s) X_train = train_sc_df.dropna().drop('Y', axis=1) y_train = train_sc_df.dropna().drop('X_1', axis=1) X_test = test_sc_df.dropna().drop('Y', axis=1) y_test = test_sc_df.dropna().drop('X_1', axis=1) X_train = X_train.as_matrix() y_train = y_train.as_matrix() X_test = X_test.as_matrix() y_test = y_test.as_matrix() X_train_lmse = X_train.reshape(X_train.shape[0], X_train.shape[1], 1) X_test_lmse = X_test.reshape(X_test.shape[0], X_test.shape[1], 1) print('Train shape: ', X_train_lmse.shape) print('Test shape: ', X_test_lmse.shape)

python 时间序列预测,python时间序列预测的方法(7)

lstm_model = Sequential() lstm_model.add(LSTM(7, input_shape=(1, X_train_lmse.shape[1]), activation='relu', kernel_initializer='lecun_uniform', return_sequences=False)) lstm_model.add(Dense(1)) lstm_model.compile(loss='mean_squared_error', optimizer='adam') early_stop = EarlyStopping(monitor='loss', patience=2, verbose=1) history_lstm_model = lstm_model.fit(X_train_lmse, y_train, epochs=100, batch_size=1, verbose=1, shuffle=False, callbacks=[early_stop])

python 时间序列预测,python时间序列预测的方法(8)

上一页1234下一页

栏目热文

文档排行

本站推荐

Copyright © 2018 - 2021 www.yd166.com., All Rights Reserved.