用Keras-LSTM预测未来价值

用Keras-LSTM预测未来价值,keras,deep-learning,lstm,prediction,Keras,Deep Learning,Lstm,Prediction,我创建了一个LSTM销售预测模型,该模型在列车和测试集上非常有效。现在我想预测整个数据集中的日期以外的日期 我试着遵循这个答案,但我真的不知道如何调整我的代码来做未来的预测 另外,我更改了我的代码 X_train, y_train = train_set_scaled[:, 1:], train_set_scaled[:, 0:1] X_train = X_train.reshape(X_train.shape[0], 1, X_train.shape[1]) X_test, y_test =

我创建了一个LSTM销售预测模型,该模型在列车和测试集上非常有效。现在我想预测整个数据集中的日期以外的日期

我试着遵循这个答案,但我真的不知道如何调整我的代码来做未来的预测

另外,我更改了我的代码

X_train, y_train = train_set_scaled[:, 1:], train_set_scaled[:, 0:1]
X_train = X_train.reshape(X_train.shape[0], 1, X_train.shape[1])
X_test, y_test = test_set_scaled[:, 1:], test_set_scaled[:, 0:1]
X_test = X_test.reshape(X_test.shape[0], 1, X_test.shape[1])

在尝试解决方案之后

以下是进行培训和建模的代码:

# changed to initial
for df in m:
    train_set, test_set = m[df][0:-6].values, m[df][-6:].values

    #apply Min Max Scaler
    scaler = MinMaxScaler(feature_range=(-1, 1))
    scaler = scaler.fit(train_set)

    # reshape training set
    train_set = train_set.reshape(train_set.shape[0], train_set.shape[1])
    train_set_scaled = scaler.transform(train_set)

    # reshape test set
    test_set = test_set.reshape(test_set.shape[0], test_set.shape[1])
    test_set_scaled = scaler.transform(test_set)

    #build the LSTM Model
    X_train, y_train = train_set_scaled[:, 1:], train_set_scaled[:, 0:1]
    X_train = X_train.reshape(X_train.shape[0], 1, X_train.shape[1])
    X_test, y_test = test_set_scaled[:, 1:], test_set_scaled[:, 0:1]
    X_test = X_test.reshape(X_test.shape[0], 1, X_test.shape[1])

    print('Fitting model for: {}'.format(df))

    #fit our LSTM Model
    model = Sequential()
    model.add(LSTM(4, batch_input_shape=(1, X_train.shape[1], X_train.shape[2]), stateful=True))
    model.add(Dense(1))
    model.compile(loss='mean_squared_error', optimizer='adam')
    model.fit(X_train, y_train, nb_epoch=500, batch_size=1, verbose=1, shuffle=False)

#     model.save('lstm_model.h5')


    print('Predictions for: {}'.format(df))

    #check prediction
    y_pred = model.predict(X_test,batch_size=1)

    print('Inverse Transform for: {}'.format(df))

    #inverse transformation to see actual sales
    #reshape y_pred
    y_pred = y_pred.reshape(y_pred.shape[0], 1, y_pred.shape[1])
    #rebuild test set for inverse transform
    pred_test_set = []
    for index in range(0,len(y_pred)):
        print (np.concatenate([y_pred[index],X_test[index]],axis=1))
        pred_test_set.append(np.concatenate([y_pred[index],X_test[index]],axis=1))
    #reshape pred_test_set
    pred_test_set = np.array(pred_test_set)
    pred_test_set = pred_test_set.reshape(pred_test_set.shape[0], pred_test_set.shape[2])
    #inverse transform
    pred_test_set_inverted = scaler.inverse_transform(pred_test_set)


我希望预测超出数据集中的数据范围

更新:我训练了模型,并在测试集上进行了预测。将这些作为另一个LSTM模型的输入,以拟合和预测12个月。这对我有用。也改变了我的最后一个致密层(以上),一次预测1个点,而不是像以前那样预测7个点。 下面是代码:

from numpy import array
for df in d:
    if df in list_df:
        # df_ADIDAS DYN PUL DEO 150 FCA5421
        #KEEP

        result_list = []
        sales_dates = list(d["{}".format(df)][-7:].Month)
        act_sales = list(d["{}".format(df)][-7:].Sale)
        for index in range(0,len(pred_test_set_inverted)):
            result_dict = {}
            result_dict['pred_value'] = int(pred_test_set_inverted[index][0] + act_sales[index]) #change to 0 ffrom act_sales[index]
            result_dict['date'] = sales_dates[index] #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>REVIEW
            result_list.append(result_dict)

        df_result = pd.DataFrame(result_list)
        predictions = list(df_result['pred_value'])

        forecasts = []
        result_list
        for i in range(len(result_list)):
            forecasts.append(result_list[i]['pred_value'])

        def split_sequence(sequence, n_steps):
            X, y = list(), list()
            for i in range(len(sequence)):
                # find the end of this pattern
                end_ix = i + n_steps
                # check if we are beyond the sequence
                if end_ix > len(sequence)-1:
                    break
                # gather input and output parts of the pattern
                seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]
                X.append(seq_x)
                y.append(seq_y)
            return array(X), array(y)

        # choose a number of time steps
        n_steps = 4
        # split into samples
        X, y = split_sequence(forecasts, n_steps)
        # summarize the data
        #     for i in range(len(X)):
        #         print(X[i], y[i])

        n_features = 1
        X = X.reshape((X.shape[0], X.shape[1], n_features))
        # define model
        model = Sequential()
        model.add(LSTM(50, activation='relu', input_shape=(n_steps, n_features)))
        model.add(Dense(1))
        model.compile(optimizer='adam', loss='mse')
        # fit model
        model.fit(X, y, epochs=200, verbose=0)
        # demonstrate prediction
        x_input = array(predictions[-4:])
        x_input = x_input.reshape((1, n_steps, n_features))
        yhat = model.predict(x_input, verbose=0)
        #print(yhat)

        currentStep = yhat[:, -1:]

        print('Twelve Month Prediction for {}'.format(df))
        for i in range(12):
            if i == 0:
                x_input = x_input.reshape((1, n_steps, n_features))
                yhat = model.predict(x_input, verbose=0)
                print(yhat)
            else:
                x0_input = np.append(x_input, [currentStep[i-1]])
                x0_input = x0_input.reshape((1, n_steps+1, n_features))
                x_input = x0_input[:,1:]
                yhat = model.predict(x_input)
                currentStep = np.append(currentStep, yhat[:,-1:])
                print(yhat)

你的最后一个致密层表示你一次预测7个点。保存这些预测并再次将它们输入模型以预测下一个7。这使得它同时有14个预测。等等或者将节点数量和y的形状从7更改为相应的数量,然后再次训练。

谢谢。我正在做这个,我会发布一个更新。嗨,我是一个新手。我已经将我的模型用于预测,但无法将其传递给新模型进行预测。你能分享你的代码吗。你能用你的代码开始一个新问题吗?我不明白你的解决方案。您拥有的新模型只对您已经拥有的测试集进行了预测?如果
model.fit()
中没有原始数据中的任何数据,这怎么可能有任何准确性?
from numpy import array
for df in d:
    if df in list_df:
        # df_ADIDAS DYN PUL DEO 150 FCA5421
        #KEEP

        result_list = []
        sales_dates = list(d["{}".format(df)][-7:].Month)
        act_sales = list(d["{}".format(df)][-7:].Sale)
        for index in range(0,len(pred_test_set_inverted)):
            result_dict = {}
            result_dict['pred_value'] = int(pred_test_set_inverted[index][0] + act_sales[index]) #change to 0 ffrom act_sales[index]
            result_dict['date'] = sales_dates[index] #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>REVIEW
            result_list.append(result_dict)

        df_result = pd.DataFrame(result_list)
        predictions = list(df_result['pred_value'])

        forecasts = []
        result_list
        for i in range(len(result_list)):
            forecasts.append(result_list[i]['pred_value'])

        def split_sequence(sequence, n_steps):
            X, y = list(), list()
            for i in range(len(sequence)):
                # find the end of this pattern
                end_ix = i + n_steps
                # check if we are beyond the sequence
                if end_ix > len(sequence)-1:
                    break
                # gather input and output parts of the pattern
                seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]
                X.append(seq_x)
                y.append(seq_y)
            return array(X), array(y)

        # choose a number of time steps
        n_steps = 4
        # split into samples
        X, y = split_sequence(forecasts, n_steps)
        # summarize the data
        #     for i in range(len(X)):
        #         print(X[i], y[i])

        n_features = 1
        X = X.reshape((X.shape[0], X.shape[1], n_features))
        # define model
        model = Sequential()
        model.add(LSTM(50, activation='relu', input_shape=(n_steps, n_features)))
        model.add(Dense(1))
        model.compile(optimizer='adam', loss='mse')
        # fit model
        model.fit(X, y, epochs=200, verbose=0)
        # demonstrate prediction
        x_input = array(predictions[-4:])
        x_input = x_input.reshape((1, n_steps, n_features))
        yhat = model.predict(x_input, verbose=0)
        #print(yhat)

        currentStep = yhat[:, -1:]

        print('Twelve Month Prediction for {}'.format(df))
        for i in range(12):
            if i == 0:
                x_input = x_input.reshape((1, n_steps, n_features))
                yhat = model.predict(x_input, verbose=0)
                print(yhat)
            else:
                x0_input = np.append(x_input, [currentStep[i-1]])
                x0_input = x0_input.reshape((1, n_steps+1, n_features))
                x_input = x0_input[:,1:]
                yhat = model.predict(x_input)
                currentStep = np.append(currentStep, yhat[:,-1:])
                print(yhat)