model = Sequential() model.add(Embedding(630, 210)) model.add(LSTM(1024, dropout = 0.2, return_sequences = True)) model.add(LSTM(1024, dropout = 0.2, return_sequences = True)) model.add(Dense(210, activation = 'softmax')) model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy']) filepath = 'ner_2-{epoch:02d}-{loss:.5f}.hdf5' checkpoint = ModelCheckpoint(filepath, monitor = 'loss', verbose = 1, save_best_only = True, mode = 'min') callback_list = [checkpoint] model.fit(X, y , epochs = 20, batch_size = 1024, callbacks = callback_list)
X: 输入向量的形状为 (204564, 630, 1)
y: 目标向量的形状为 (204564, 210, 1)
也就是说,对于每630个输入,需要预测210个输出,但代码在编译时抛出以下错误
ValueError Traceback (most recent call last)<ipython-input-57-05a6affb6217> in <module>() 50 callback_list = [checkpoint] 51 ---> 52 model.fit(X, y , epochs = 20, batch_size = 1024, callbacks = callback_list) 53 print('successful')ValueError: Error when checking model input: expected embedding_8_input to have 2 dimensions, but got array with shape (204564, 630, 1)
请有人解释一下为什么会发生这个错误以及如何解决
回答:
消息显示:
你的第一层期望输入具有2个维度:(批量大小, 其他维度)。但你的输入有3个维度(批量大小=204564,其他维度=630, 1)。
嗯… 从你的输入中去掉这个1,或者在模型内重塑它:
解决方案1 – 从输入中去掉它:
X = X.reshape((204564,630))
解决方案2 – 添加一个重塑层:
model = Sequential()model.add(Reshape((630,),input_shape=(630,1)))model.add(Embedding.....)