簡體   English   中英

使用Keras模型進行預測時出錯

[英]Error making prediction with Keras model

我正在嘗試使用預先訓練的Keras模型對樣本進行預測,但出現錯誤。 我已經詳細介紹了模型訓練腳本的各個部分,以顯示數據准備,矩陣形狀和模型規格。

矩陣形狀和數據准備:

from __future__ import print_function
#import numpy as np
np.random.seed(1337)  # for reproducibility

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras import backend as K

batchsize = 128
nb_classes = 3
nb_epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = (2, 2)
# convolution kernel size
kernel_size = (3, 3)

# the data, shuffled and split between train and test sets
#(X_train, y_train), (X_test, y_test) = mnist.load_data()

if K.image_dim_ordering() == 'th':
    X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
    X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)
    X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)

型號規格:

model = Sequential()

model.add(Convolution2D(nb_filters, [kernel_size[0], kernel_size[1]],
                        padding='valid',
                        input_shape=input_shape,
                        name='conv2d_1'))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, [kernel_size[0], kernel_size[1]], name='conv2d_2'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size, name='maxpool2d'))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(128, name='dense_1'))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes, name='dense_2'))
model.add(Activation('softmax'))

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

在完全獨立的程序中,重新加載了預訓練的模型,對輸入樣本矩陣進行了整形,以匹配模型期望的結果,並對數據應用相同的歸一化。 像這樣

預測方法:

from keras import backend as K
from keras.models import load_model

img_rows, img_cols = 28, 28

#Load the pre-trained classifier model
retrieved_model = load_model('classifier_cnn_saved_model_0.05_30min.hdf5')

#Function to callback
def get_prediction(sample):
    print('Received: ' + str(sample.shape))
    if K.image_dim_ordering() == 'th':
        sample = sample.reshape(sample.shape[0], 1, img_rows, img_cols)
    else:
        sample = sample.reshape(sample.shape[0], img_rows, img_cols, 1)

    print('Reshaped for backend: ' + K.image_dim_ordering() + ' ' + str(sample.shape))
    sample = sample.astype('float32')   
    sample /= 255 #normalize the sample data
    prediction = retrieved_model.predict(sample)
    print('pyAgent; ' + str(sample.shape) + ' prediction: ' + str(prediction))

當調用get_prediction時,將給出此輸出;

Received: (1, 784) <====== Yep, as expected.
Reshaped for backend: tf (1, 28, 28, 1) <====== What the model expects, I think. Based on how it was specified at training time.

但是嘗試進行預測時出現此錯誤;

Exception: ValueError: Tensor Tensor("activation_4/Softmax:0", shape=(?, 3), dtype=float32) is not an element of this graph. 

我很沮喪 誰能指出這里有什么問題以及如何糾正它? 非常感謝。

注意所有的訓練和預測都在使用Python 3和Keras 2.1.3和Tensorflow 1.5.0的Windows 10計算機上進行的

考慮到這個github問題就得出了答案。 在這種情況下, get_prediction()將由與加載模型的線程不同的線程調用。 進行以下更改可清除錯誤:

import tensorflow as tf #<======= add this
from keras import backend as K
from keras.models import load_model

img_rows, img_cols = 28, 28

#Load the pre-trained classifier model
retrieved_model = load_model('classifier_cnn_saved_model_0.05_30min.hdf5')
#https://www.tensorflow.org/api_docs/python/tf/Graph
graph = tf.get_default_graph() #<======= do this right after constructing or loading the model

#Function to callback
def get_prediction(sample):
    print('Received: ' + str(sample.shape))
    if K.image_dim_ordering() == 'th':
        sample = sample.reshape(sample.shape[0], 1, img_rows, img_cols)
    else:
        sample = sample.reshape(sample.shape[0], img_rows, img_cols, 1)

    print('Reshaped for backend: ' + K.image_dim_ordering() + ' ' + str(sample.shape))
    sample = sample.astype('float32')   
    sample /= 255 #normalize the sample data
    with graph.as_default(): #<======= with this, call predict
        prediction = retrieved_model.predict_classes(sample)
    print('pyAgent; ' + str(sample.shape) + ' prediction: ' + str(prediction))

暫無
暫無

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

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