Para "te enseña a usar una simple red neuronal y la serie de pronóstico LSTM tiempo" modificación del código y la interpretación

enlace de texto y el código aquí: para enseñarle a utilizar una red neuronal sencilla y hora LSTM serie de pronóstico (con código)

Sin embargo, en el proceso de probar, el código fuente de algunos problemas, directamente ejecutar el código original no funciona. La mayor parte de la interpretación original del código escrito en un muy claro, sólo para añadir aquí.

En este trabajo el entorno de prueba: Python3.6 Jupyter Notebook, TensorFlow + Keras

Este artículo utiliza redes neuronales artificiales (Artificial Neural Network, ANN) y la red neuronal recurrente memoria a largo plazo (Long memoria a corto plazo recurrente red neuronal, LSTM RNN) modelo de datos de series de tiempo, el objetivo es el uso de ANN para predecir las fluctuaciones y LSTM S & P 500 en secuencia de tiempo.

Desde aquí ( https://ca.finance.yahoo.com/quote/%5Evix/history?ltr=1 ) Descargar la volatilidad de los S & P 500 conjuntos de datos, se puede elegir el intervalo de tiempo que desea descargar el conjunto de datos.

Empezarán a llamar el código. El primero es el modelo ANN

import pandas as pd
import numpy as np
%matplotlib inline 
#在Jupyter Notebook要PLOT出图像,必须加这个
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import r2_score
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import EarlyStopping
from keras.optimizers import Adam
from keras.layers import LSTM
#并将数据加载到Pandas 的dataframe中。
df = pd.read_csv("E:\data\VIX.csv")
#我们可以快速浏览前几行。
print(df.head())
#删除不需要的列,然后将“日期”列转换为时间数据类型,并将“日期”列设置为索引。
df.drop(['Open', 'High', 'Low', 'Close', 'Volume'], axis=1, inplace=True)
df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index(['Date'], drop=True)
df.head(10)

Fuera [1]:

Fuera [2]:

(Sólo Utilizamos estos datos Adj Cerrar)

#我们绘制一个时间序列线图。
plt.figure(figsize=(10, 6))
df['Adj Close'].plot();

#按日期“2018–09–20”将数据拆分为训练集和测试集
split_date = pd.Timestamp('2018-09-20')
df = df['Adj Close']
train = df.loc[:split_date]
test = df.loc[split_date:]
plt.figure(figsize=(10, 6))
ax = train.plot()
test.plot(ax=ax)
plt.legend(['train', 'test']);

Afuera:

#将训练和测试数据缩放为[-1,1]。
train=np.array(train).reshape(-1,1)
test=np.array(test).reshape(-1,1)

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

 

Antes de la reducción de la normalización:

origin_data = escalador .inverse_transform (y_pred_test) '''

La última parte de los datos se combina con la reducción de

#获取训练和测试数据。
X_train = train_sc[:-1]
y_train = train_sc[1:]
X_test = test_sc[:-1]
y_test = test_sc[1:]
#获取训练和测试数据。
X_train = train_sc[:-1]
y_train = train_sc[1:]
X_test = test_sc[:-1]
y_test = test_sc[1:]

Explicación, la secuencia predicha a = np.array ([2,3,4,5,6,7])

impresión (A [: - 1]) # eliminar el último elemento

imprimir (una [1:]) # desde el segundo elemento

Afuera:

[2 3 4 5 6]

[3 4 5 6 7]

De entrada x = [2 3 4 5 6]

Correspondiente Label y = [3 4 5 6 7] (Progresivo predicción de la siguiente) ''

#用于时间序列预测的简单人工神经网络ANN
ann=Sequential()
ann.add(Dense(12, input_dim=1, activation='relu'))
ann.add(Dense(1))
ann.compile(loss='mean_squared_error', optimizer='adam')
early_stop = EarlyStopping(monitor='loss', patience=2, verbose=1)
history= ann.fit(X_train, y_train, epochs=100, batch_size=1, verbose=1, callbacks=[early_stop], shuffle=False)

#进行预测
y_pred_test = ann.predict(X_test)

y_train_pred =ann.predict(X_train)

print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train, y_train_pred)))

print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test, y_pred_test)))

 

Afuera:

The R2 score on the Train set is:     0.851
The R2 score on the Test set is:      0.823

Y agregó:

R2 coeficiente de determinación (bondad de ajuste)

Cuanto mejor sea el modelo: r2 → 1

Modelo peor: R2 → 0

#显示6项数据
print('显示数据:')
print(y_test[:6].reshape([1,6]))
print(y_pred_test[:6].reshape([1,6]))
#将归一化数据还原
y_test_pred_origin=scaler.inverse_transform(y_pred_test)
y_test_origin=scaler.inverse_transform(y_test)
print('数据还原:')
print('真实值:'+'%s'%y_test_origin[:6].reshape([1,6]))
print('预测值:'+'%s'%y_test_pred_origin[:6].reshape([1,6]))

Salida: (detrás de las previsiones y la evaluación real de índice MSE)

 

#显示TEST真实值和预测值的对比图
plt.figure(figsize=(10, 6))

plt.plot(y_test, label='True')

plt.plot(y_pred_test, label='NN')

plt.title("NN's Prediction")

plt.xlabel('Observation')

plt.ylabel('Adj Close Scaled')

plt.legend()

plt.show();

AFUERA:

modelos LSTM

x_train=X_train.reshape(1509,1,1)#注意input x_train 的shape
lstm_model = Sequential()
lstm_model.add(LSTM(7,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, y_train, epochs=100, batch_size=1, verbose=1, shuffle=False, callbacks=[early_stop])

LSTM ANN de forma de entrada de modelo y de que hay una diferencia, que primero deben ser convertidos a X_train, detrás X_test bien.

AFUERA:

predecir

x_test=X_test.reshape(251,1,1) #251 is the length of X_test
y_pred_test_lstm = lstm_model.predict(x_test)
y_train_pred_lstm = lstm_model.predict(x_train)
print("The R2 score on the Train set is:t{:0.3f}".format(r2_score(y_train, y_train_pred_lstm)))
print("The R2 score on the Test set is:t{:0.3f}".format(r2_score(y_test, y_pred_test_lstm)))

AFUERA:

#显示TEST真实值和预测值的对比图
plt.figure(figsize=(10, 6))
plt.plot(y_test, label='True')
plt.plot(y_pred_test_lstm, label='LSTM')
plt.title("LSTM's Prediction")
plt.xlabel('Observation')
plt.ylabel('Adj Close scaled')
plt.legend()
plt.show()

AFUERA:

#比较了两种模型的测试MSE
ann_test_mse = ann.evaluate(X_test, y_test, batch_size=1)
lstm_test_mse = lstm_model.evaluate(x_test, y_test, batch_size=1)
print('ANN: %f'%ann_test_mse)
print('LSTM: %f'%lstm_test_mse)

Afuera:

resumen:

De hecho, no hay muchos lugares a ser modificadas, esto es un ejemplo relativamente simple, puede no estar familiarizado con las contribuciones de tiempo, por numpy y pandas que pagar más para aprender y practicar.

Publicado 10 artículos originales · ganado elogios 10 · vistas 7516

Supongo que te gusta

Origin blog.csdn.net/qq_41647438/article/details/101147892
Recomendado
Clasificación