【问题标题】:Error while making predictions with loaded CNN使用加载的 CNN 进行预测时出错
【发布时间】:2019-10-29 01:57:39
【问题描述】:

我已经训练了一个用于信号分类的 CNN 模型:

with tf.device('/cpu:0'):
    model = Sequential()

    model.add(Convolution2D(filters=10, kernel_size=(3, 3), activation='relu',
                        input_shape=(1, SEQ_LEN, FEATURES), data_format='channels_first'))
    model.add(Dropout(0.3))
    model.add(Convolution2D(filters=10, kernel_size=(3, 3), activation='relu'))
    model.add(Dropout(0.3))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Flatten())
    model.add(Dense(100, activation='relu'))
    model.add(Dense(2, activation='softmax'))

    model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
    tensorboard = TensorBoard(log_dir='logs/{}'.format(NAME))

    filepath = NAME + "_{epoch:02d}-{val_acc:.3f}"

    history = model.fit(
        train_x, train_y,
        batch_size=BATCH_SIZE,
        epochs=EPOCHS,
        validation_data=(validation_x, validation_y),
        callbacks=[tensorboard])

scores = model.evaluate(test_x, test_y)
print('Test loss: {} \nTest accuracy: {}'.format(scores[0], scores[1]))

# Save entire model to a HDF5 file
np.save('manually_saved_models/{}_test_x'.format(NAME), test_x)
np.save('manually_saved_models/{}_test_y'.format(NAME), test_y)
model.save('manually_saved_models/{}_acc{}.h5'.format(NAME, round(scores[1], 3)))

训练后,我可以对 test_x 值进行预测,但是当我尝试之后使用以下方法加载此模型时:

model = tf.keras.models.load_model('....h5')
test_x = np.load('....npy')
test_y = np.load('....npy')

我无法做出任何预测,并且收到以下错误消息:

2019-06-14 16:03:54.558556: E tensorflow/core/common_runtime/executor.cc:624] Executor failed to create kernel. Invalid argument: Default MaxPoolingOp only supports NHWC on device type CPU
     [[{{node max_pooling2d_1/MaxPool}}]]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Users\1\PycharmProjects\Test2\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1011, in evaluate
    steps=steps)
  File "C:\Users\1\PycharmProjects\Test2\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py", line 329, in model_iteration
    batch_outs = f(ins_batch)
  File "C:\Users\1\PycharmProjects\Test2\lib\site-packages\tensorflow\python\keras\backend.py", line 3073, in __call__
    self._make_callable(feed_arrays, feed_symbols, symbol_vals, session)
  File "C:\Users\1\PycharmProjects\Test2\lib\site-packages\tensorflow\python\keras\backend.py", line 3019, in _make_callable
    callable_fn = session._make_callable_from_options(callable_opts)
  File "C:\Users\1\PycharmProjects\Test2\lib\site-packages\tensorflow\python\client\session.py", line 1471, in _make_callable_from_options
    return BaseSession._Callable(self, callable_options)
  File "C:\Users\1\PycharmProjects\Test2\lib\site-packages\tensorflow\python\client\session.py", line 1425, in __init__
    session._session, options_ptr, status)
  File "C:\Users\1\PycharmProjects\Test2\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 528, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Default MaxPoolingOp only supports NHWC on device type CPU
     [[{{node max_pooling2d_1/MaxPool}}]]

【问题讨论】:

  • 你能把第一个例子的导入包括进来吗?
  • @MatiasValdenegro 感谢您的评论,我发现了问题,将其发布为答案。

标签: python python-3.x tensorflow machine-learning keras


【解决方案1】:

所以问题出在这一行:

model.add(Convolution2D(filters=10, kernel_size=(3, 3), activation='relu',
                    input_shape=(1, SEQ_LEN, FEATURES), data_format='channels_first'))

我指出data_format='channels_first'不是CNN层的默认情况,默认情况下CNN和MaxPool2D都与data_format='channels_last'一起使用。由于我没有在MaxPooling2D 层的参数中指出这一点,因此它向我显示了该错误。有关更多详细信息,请查看文档:

https://keras.io/layers/convolutional/

https://keras.io/layers/pooling/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多