Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用keras构建的LSTM模型的时间序列数据可视化预测和训练数据?_Python_Tensorflow_Machine Learning_Keras_Lstm - Fatal编程技术网

Python 如何使用keras构建的LSTM模型的时间序列数据可视化预测和训练数据?

Python 如何使用keras构建的LSTM模型的时间序列数据可视化预测和训练数据?,python,tensorflow,machine-learning,keras,lstm,Python,Tensorflow,Machine Learning,Keras,Lstm,我已经在本教程的基础上构建了一个示例LSTM: 但是,本教程没有显示实际的数据点,只有错误。这是我所有的数据,然后当我尝试将训练数据和预测数据放在同一个图上时会发生什么: 第二个简单地由以下材料制成: plt.plot(yhat) plt.plot(test_y) plt.plot(train_y) 我知道这是由于数据的标准化,但我不确定是否有办法回到像我的第一张图那样的东西,除了预测数据,而不是历史数据。有没有一种方法可以使用我在修改之前拥有的时间戳自变量来运行模型?理想情况下,我会想

我已经在本教程的基础上构建了一个示例LSTM:

但是,本教程没有显示实际的数据点,只有错误。这是我所有的数据,然后当我尝试将训练数据和预测数据放在同一个图上时会发生什么:

第二个简单地由以下材料制成:

plt.plot(yhat)
plt.plot(test_y)
plt.plot(train_y)
我知道这是由于数据的标准化,但我不确定是否有办法回到像我的第一张图那样的东西,除了预测数据,而不是历史数据。有没有一种方法可以使用我在修改之前拥有的时间戳自变量来运行模型?理想情况下,我会想象从训练到预测的价值观

(我还试图找出如何使用LSTM预测训练集之外的内容,但这是一个非常不同的主题!)

完整代码如下:

from math import sqrt
import numpy as np
from numpy import concatenate
from matplotlib import pyplot
import pandas as pd
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM

# convert series to supervised learning
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
    n_vars = 1 if type(data) is list else data.shape[1]
    df = DataFrame(data)
    cols, names = list(), list()
    # input sequence (t-n, ... t-1)
    for i in range(n_in, 0, -1):
        cols.append(df.shift(i))
        names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
    # forecast sequence (t, t+1, ... t+n)
    for i in range(0, n_out):
        cols.append(df.shift(-i))
        if i == 0:
            names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
        else:
            names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
    # put it all together
    agg = concat(cols, axis=1)
    agg.columns = names
    # drop rows with NaN values
    if dropnan:
        agg.dropna(inplace=True)
    return agg
# load dataset
dataset = read_csv('weeklyTrends-growthUnderlying.csv', header=0, index_col=0)
values = dataset.values
# ensure all data is float
values = values.astype('float32')
# normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
# frame as supervised learning
reframed = series_to_supervised(scaled, 1, 1)

print(reframed.head())

# Visualize/plot data
%matplotlib inline
import matplotlib.pyplot as plt
# x = dataset['timestamp'].values
y = dataset['value'].values
plt.plot(y)
plt.show()

# split into train and test sets
# 26,207 observations
values = reframed.values
n_train = 13000
train = values[:n_train, :]
test = values[n_train:, :]
# split into input and outputs
train_X, train_y = train[:, :-1], train[:, -1]
test_X, test_y = test[:, :-1], test[:, -1]
# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)

# design network
model = Sequential()
model.add(LSTM(32, return_sequences=True, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(LSTM(32))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(train_X, train_y, epochs=5, batch_size=72, validation_data=(test_X, test_y), verbose=2, shuffle=False)

# plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()

# make a prediction
# change predict from (train_X) to range of test and future data
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], test_X.shape[2]))

plt.plot(yhat)
plt.plot(test_y)
plt.plot(train_y)

# invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, 1:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
# invert scaling for actual
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, 1:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:,0]

# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)

model.summary()