编程语言
首页 > 编程语言> > python-Keras LSTM:检查模型输入尺寸时出错

python-Keras LSTM:检查模型输入尺寸时出错

作者:互联网

我是keras的新用户,并尝试实现LSTM模型.为了进行测试,我按如下所示声明了该模型,但是由于输入尺寸的差异而导致模型失败.尽管我在该站点中发现了类似的问题,但我自己找不到错误.

ValueError: 
Error when checking model input: 
expected lstm_input_4 to have 3 dimensions, but got array with shape (300, 100)

我的环境

> python 3.5.2
> keras 1.2.0(Theano)

06001

编辑1(在MarcinMożejko发表评论后无效)

谢谢MarcinMożejko.但是我有一个类似下面的错误.我更新了虚拟数据进行检查.该代码有什么问题?

ValueError: Error when checking model target: expected
timedistributed_36 to have 3 dimensions, but got array with shape
(208, 1)

def create_dataset(X, Y, loop_back=1):
    dataX, dataY = [], []
    for i in range(len(X) - loop_back-1):
        a = X[i:(i+loop_back), :]
        dataX.append(a)
        dataY.append(Y[i+loop_back, :])
    return np.array(dataX), np.array(dataY)

data_size = 300
dataset = np.zeros((data_size, feature_size), dtype=np.float32)
dataset_labels = np.zeros((data_size, 1), dtype=np.float32)

train_size = int(data_size * 0.7)
trainX = dataset[0:train_size, :]
trainY = dataset_labels[0:train_size, :]
testX = dataset[train_size:, :]
testY = dataset_labels[train_size:, 0]
trainX, trainY = create_dataset(trainX, trainY)
print(trainX.shape, trainY.shape) # (208, 1, 1) (208, 1)

# in_size = 100
feature_size = 1
out_size = 1
nb_hidden = 8

model = Sequential()
model.add(LSTM(nb_hidden, 
               name='lstm',
               activation='tanh',
               return_sequences=True,
               input_shape=(1, feature_size)))

model.add(TimeDistributed(Dense(out_size, activation='softmax')))
adadelta = Adadelta(clipnorm=1.)
model.compile(optimizer=adadelta,
              loss='categorical_crossentropy',
              metrics=['accuracy'])
model.fit(trainX, trainY, nb_epoch=10, batch_size=1)

解决方法:

这是Keras中LSTM的一个非常经典的问题. LSTM输入形状应为2d-形状(sequence_length,nb_of_features).另外的第三个维度来自示例维度-因此,馈送给模型的表格具有形状(nb_of_examples,sequence_length,nb_of_features).这就是您的问题出处.请记住,一维序列应显示为形状为(sequence_length,1)的二维数组.这应该是LSTM的输入形状:

model.add(LSTM(nb_hidden, 
           name='lstm',
           activation='tanh',
           return_sequences=True,
           input_shape=(in_size, 1)))

并记住将输入调整为适当的格式.

标签:keras,neural-network,deep-learning,lstm,python
来源: https://codeday.me/bug/20191111/2021101.html