检查目标时出错:预期的暗淡错误

时间:2019-01-07 01:55:39

标签: tensorflow keras lstm

问题描述

当我使用Tensorflow的keras处理文本分类器项目时,会出现问题。

Error when checking target: expected dense_3 to have 2 dimensions, but got array with shape (4500, 4, 4)

有关调试信息的东西

Layer (type)                 Output Shape              Param #   
=================================================================
lstm_9 (LSTM)                (150, 1, 32)              772224    
_________________________________________________________________
lstm_10 (LSTM)               (150, 1, 32)              8320      
_________________________________________________________________
lstm_11 (LSTM)               (150, 32)                 8320      
_________________________________________________________________
dense_3 (Dense)              (150, 4)                  132       
=================================================================
Total params: 788,996
Trainable params: 788,996
Non-trainable params: 0

相关代码

timesteps = 1
data_dim = 6000
num_classes = 4
batch_size = 150

x_train = train_x_array
x_val = val_x_array

x_train = keras.preprocessing.sequence.pad_sequences(x_train, maxlen=6000, value=0)
x_val = keras.preprocessing.sequence.pad_sequences(x_val, maxlen=6000, value=0)
print('x_train shape: {}'.format(x_train.shape))
print('x_val shape: {}'.format(x_val.shape))

x_train = x_train.reshape([batch_size * 30, timesteps, data_dim])
x_val = x_val.reshape([batch_size * 10, timesteps, data_dim])
print('x_train shape: {}'.format(x_train.shape))
print('x_val shape: {}'.format(x_val.shape))

// x_train shape: (4500, 6000)
// x_val shape: (1500, 6000)
// x_train shape: (4500, 1, 6000)
// x_val shape: (1500, 1, 6000)

model = Sequential()
model.add(LSTM(32, return_sequences=True, stateful=True,
               batch_input_shape=(batch_size, timesteps, data_dim)))
model.add(LSTM(32, return_sequences=True, stateful=True))
model.add(LSTM(32, stateful=True))
model.add(Dense(4, activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.summary()

model.fit(x_train, y_train,
          batch_size=batch_size, epochs=3, shuffle=False,
          validation_data=(x_val, y_val))

如何解决此问题?

lstm_11的输出形状为2维,为什么density_3会出现此问题?

1 个答案:

答案 0 :(得分:0)

提到的代码似乎没有问题,您的模型应该可以完美地训练,但是我相信这不是您实际用于训练的代码。从错误消息(4500)v / s在代码150中指定的batch_size的批处理大小可以明显看出这一点。还要在最后一个lstm层中明确提及return_state = False