训练模型后,如何使用LSTM python获取当前的下一个预测值

时间:2019-11-28 04:47:00

标签: python tensorflow machine-learning keras lstm

在这里,根据我的数据创建LSTM模型。然后我根据数据预测值。

然后,我想做的是现在要向训练模型中添加新的输入,然后根据新输入,我要根据训练LSTM模型预测一小时后的下一个值。

但是我不知道该怎么做。有人知道怎么做吗?

这是我的训练模型代码。

model = Sequential()
model.add(LSTM(16, return_sequences=True,input_shape=(None,x_train_n.shape[2])))  # returns a sequence of vectors of dimension 32
model.add(LSTM(16, return_sequences=True))  # returns a sequence of vectors of dimension 32
model.add(LSTM(8))  # return a single vector of dimension 32
model.add(Dense(1))
batchsize = 32
model.compile(loss="mean_squared_error",optimizer="adam")
history = model.fit(x_train_n,y_train_n, batch_size = batchsize, nb_epoch=30,validation_data=(x_test_n, y_test_n),shuffle =True)

model.reset_states()
pred = model.predict(x_test_n)

根据之前的数据,我创建了LSTM神经网络模型。

现在,我想向模型中添加新的输入,并预测下一个小时的X1值

date                       x1       x2   x3   x4
2019/8/23 06:30:00         20        0   0    0

然后预测下一个x1值at t+1 = x1 ?

根据@ southv89,我编写了代码:

from tensorflow.keras import models, layers

n_chars = 1
timesteps = num_time_steps
inp = layers.Input(shape=(timesteps, x_train_n.shape[2]))
lstm = layers.LSTM(100, return_sequences=True)
out1 = lstm(inp)
dense = layers.Dense(n_chars, activation='sigmoid')
out2 = layers.TimeDistributed(dense)(out1)
model = models.Model(inp, out2)
model.summary()

inp_infer = layers.Input(shape=(1, x_train.shape[1]))
# Inputs to feed LSTM states back in
h_inp_infer = layers.Input(shape=(100,))
c_inp_infer = layers.Input(shape=(100,))
# We need return_state=True so we are creating a new layer
 lstm_infer = layers.LSTM(100, return_state=True, return_sequences=True)
 out1_infer, h, c  = lstm_infer(inp_infer, initial_state=[h_inp_infer, c_inp_infer])
out2_infer = layers.TimeDistributed(dense)(out1_infer)
 import numpy as np
 x = np.random.randint(0,2,size=(1, 1, x_.shape[1]))
 h = np.zeros(shape=(1, 100))
 c = np.zeros(shape=(1, 100))
 seq_len = 10
 for _ in range(seq_len):
    print(x)
    y_pred, h, c = model_infer.predict([x, h, c])
    y_pred = x[:,0,:]
    y_onehot = np.zeros(shape=(x.shape[0],n_chars))
    y_onehot[np.arange(x.shape[0]),np.argmax(y_pred,axis=1)] = 1.0
    x = np.expand_dims(y_onehot, axis=1)

    model_infer = models.Model([inp_infer, h_inp_infer, c_inp_infer], [out2_infer, h, c])

     lstm_infer.set_weights(lstm.get_weights())
      model_infer.summary()

值是这样的:

[[[0 0 1 1 1 1 1 0]]]

这里是0,1

根据此代码,我有疑问:

  1. 这里1,0即将到来,那么我如何才能反转此值以获得值?
  2. 如何添加新的csv文件以获得x1列预测值?
  3. 此代码将如何影响预测未来价值?

您能解释这些问题吗?

0 个答案:

没有答案