简体   繁体   English

LSTM Keras中的尺寸不匹配

[英]Dimension Mismatch in LSTM Keras

I want to create a basic RNN that can add two bytes. 我想创建一个可以添加两个字节的基本RNN。 Here are the input and outputs, which are expected of a simple addition 以下是输入和输出,可以简单地添加

X = [[0, 0], [0, 1], [1, 1], [0, 1], [1, 0], [1, 0], [1, 1], [1, 0]]

That is, X1 = 00101111 and X2 = 01110010 即, X1 = 00101111X2 = 01110010 X1 = 00101111

Y = [1, 0, 1, 0, 0, 0, 0, 1]

I created the following sequential model 我创建了以下顺序模型

model = Sequential()
model.add(GRU(output_dim = 16, input_length = 2, input_dim = 8))
model.add(Activation('relu'`))
model.add(Dense(2, activation='softmax'))
model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
model.summary()

The error I get is something along 我得到的错误是一些东西

expected lstm_input_1 to have 3 dimensions, but got array with shape (8L, 2L) 预期lstm_input_1有3个尺寸,但得到的形状有阵列(8L, 2L)

So if I increase the dimensions by changing X to 因此,如果我通过将X更改为增加尺寸

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

Then the error changes to 然后错误变为

expected lstm_input_1 to have shape (None, 8, 2) but got array with shape (8L, 1L, 2L) 预期lstm_input_1有形状(None, 8, 2) lstm_input_1 (None, 8, 2)但是有形状的数组(8L, 1L, 2L)

In Keras the Sequential models expect an input of shape (batch_size, sequence_length, input_dimension) . 在Keras中,Sequential模型期望输入形状(batch_size, sequence_length, input_dimension) I suspect you need to change the two last dimensions of your input array. 我怀疑你需要改变输入数组的最后两个维度。 Remember, the batch dimension is not explicitly defined. 请记住,未明确定义批量维度。

将X更改为[[[0, 0], [0, 1], [1, 1], [0, 1], [1, 0], [1, 0], [1, 1], [1, 0]]]使其形状为(1, 8, 2)

Keras as input requiers 3D data, as stated in error. Keras作为输入需要3D数据,如错误所述。 It is samples, time steps, features. 它是样品,时间步骤,功能。 Since you have (8L, 2L) Keras takes it as 2D - [samples, features]. 由于你有(8L,2L)Keras将其视为2D - [样本,特征]。 In order to fix it, do something like this 为了解决它,做这样的事情

def reshape_dataset(train):
    trainX = numpy.reshape(train, (train.shape[0], 1, train.shape[1]))
    return numpy.array(trainX)

x = reshape_dataset(your_dataset)

now X should be 8L,1,2L which is [samples, time steps, features] - 3D 现在X应该是8L,1,2L ,这是[样本,时间步长,特征] - 3D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM