【问题标题】:Predict Method Gives Error for Created Model预测方法为创建的模型提供错误
【发布时间】:2022-01-21 03:54:02
【问题描述】:

我为 NLP 问题建立了一个模型,并尝试使用它进行预测。它对 LSTM 和 RNN 都给出了错误:

ValueError: in user code:

    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1621, in predict_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1611, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1604, in run_step  **
        outputs = model.predict_step(data)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1572, in predict_step
        return self(x, training=False)
    File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py", line 213, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" '

    ValueError: Exception encountered when calling layer "sequential_33" (type Sequential).
    
    Input 0 of layer "gru_8" is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 300)
    
    Call arguments received:
      • inputs=tf.Tensor(shape=(None,), dtype=int32)
      • training=False
      • mask=None

训练阶段成功,我不知道我做错了什么。我可以得到 model_weights 但无法做出预测。这是下面的代码。

model = Sequential()
model.add(layers.Embedding(vocab_size, embedding_dim, input_length=maxlen))
model.add(layers.GRU(64, return_sequences=True))
model.add(layers.GlobalMaxPool1D())
model.add(layers.Dropout(0.4))
model.add(layers.Dense(8, activation='relu'))
model.add(layers.Dropout(0.4))
model.add(layers.Dense(4, activation='relu'))
model.add(layers.Dropout(0.4))
model.add(layers.Dense(3,activation='softmax'))


model_path= "sentiment labelled sentences/generic sentiment models/w4/model{epoch:04d}.hdf5"
check=ModelCheckpoint(model_path, monitor='val_loss', verbose=0, save_best_only=False, save_weights_only=False, mode='auto',save_freq='epoch') #modeli her epoch sonunda kaydet
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.get_weights()
history = model.fit(X_train, y_train,
                    epochs=15,
                    validation_data=(X_test, y_test),
                    batch_size=150, callbacks=[check])

model.predict(X_test[0])

【问题讨论】:

  • 您需要添加示例数据。看起来您的输入数据形状有问题(即您缺少一些暗淡或其他东西) - X_train 可能是一个批处理,而 X_test 也不是一个选项

标签: python tensorflow keras deep-learning lstm


【解决方案1】:

回答我自己的问题,我在 predict 方法中指定了 batch_size,它现在可以工作了。

【讨论】:

    猜你喜欢
    • 2016-10-06
    • 2021-08-05
    • 2019-05-24
    • 2022-11-12
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2019-10-19
    相关资源
    最近更新 更多