簡體   English   中英

使用加載的CNN進行預測時出錯

[英]Error while making predictions with loaded CNN

我已經訓練了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}}]]

所以問題在於這條線:

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層的默認情況,默認情況下, CNNMaxPool2Ddata_format='channels_last' 由於我沒有在MaxPooling2D圖層的參數中指出這一點,因此它向我顯示了該錯誤。 有關詳細信息,請查看文檔:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM