LSTM ValueError:输入数组应具有与目标数组相同数量的样本

时间:2019-07-09 15:52:13

标签: python keras lstm

当我尝试拟合模型时遇到了一个问题,这是我的构建模型以及火车和测试数据的形状:

import keras
def buildModel(dataLength, labelLength):
    price=Input(shape=(dataLength, 51),name='price') 
#     price = Input(shape = (dataLength,1),name='price')
    sentiment = Input(shape=(dataLength, 51),name='sentiment')

    priceLayers = LSTM(64, return_sequences=False)(price)
    sentimentLayers = LSTM(64, return_sequences=False)(sentiment)

    output = keras.layers.concatenate(
        [priceLayers,sentimentLayers,]
    )
    output = Dense(labelLength, activation='linear',name='output')(output)

    model = Model(
        inputs = [price,sentiment],
        outputs=[output]
    )
    model.compile(optimizer='rmsprop',loss='mse')
    return model

from keras.layers import Input, Embedding, LSTM, Dense
from keras.models import Model

lstm = buildModel(22234,1)
lstm.fit([trainX,trainS],[trainY],validation_data=(
        [testX,testS],
        [testY]),epochs = 10)

trainX.shape = (1, 22234, 51)
testX.shape = (1, 9500, 51)

trainY.shape = (22234,)
testY.shape = (9500,)

trainS.shape = (1, 22234, 51)
testS.shape = (1, 9500, 51)

错误显示:

ValueError                                Traceback (most recent call last)
<ipython-input-40-4d75b702c980> in <module>()
      5 lstm.fit([trainX,trainS],[trainY],validation_data=(
      6         [testX,testS],
----> 7         [testY]),epochs = 10
      8 )
ValueError: Input arrays should have the same number of samples as target arrays. Found 1 input samples and 22234 target samples.

但是我不明白为什么它说我的输入样本和目标样本具有不同的大小,是因为X和S具有3维,而Y仅具有2D吗?我的想法是:输入必须是3D,所以我重塑了X和S。但是,Y是标签,不需要重塑

1 个答案:

答案 0 :(得分:0)

输入和目标的批次尺寸必须相同。该尺寸必须为0。

trainX.shape = (1, 22234, 51)

当输出的形状为(22234, 51, 1)时,需要为(22234,)

请勿尝试使用1作为time_step维度,因为具有单个时间步长的LSTM没有意义。

输入尺寸应为(batch_size, time_steps, n_features)。构建模型时无需指定batch_size。因此,您声明的形状应为(time_steps, n_features)。对于N次测量的序列,N是time_steps,n_features是一次测量的值数。