使用keras .h5模型进行预测时出错?



我用图像数据集训练了一个CNN模型,并将模型保存为名称classifier.h5。现在,我需要加载这个模型来进行预测。我以以下方式实现了代码,但遇到了错误_maybe_load_initial_epoch_from_ckpt() takes 2 positional arguments but 3 were given。什么可能导致这个错误,如何解决它?

这是我的CNN模型。保存为classifier.h5

EPOCHS = 60
batch_size = 32
iter_per_epoch = len(x_train)//batch_size
val_per_epoch = len(x_test)//batch_size
print(len(x_train))
print(len(x_test))

classifier = Sequential()
classifier.add(Conv2D(32, 3, activation='relu',
padding='same', input_shape=(img_w, img_h, 3)))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D())
classifier.add(Conv2D(32, 3, activation='relu',
padding='same', kernel_initializer='he_uniform'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D())
classifier.add(Conv2D(64, 3, activation='relu',
padding='same', kernel_initializer='he_uniform'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D())
classifier.add(Conv2D(64, 3, activation='relu',
padding='same', kernel_initializer='he_uniform'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D())
classifier.add(Conv2D(128, 3, activation='relu',
padding='same', kernel_initializer='he_uniform'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D())
classifier.add(Conv2D(128, 3, activation='relu',
padding='same', kernel_initializer='he_uniform'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D())
classifier.add(Flatten())
classifier.add(Dropout(0.5))
classifier.add(Dense(128, activation='relu'))
classifier.add(Dense(4, activation='softmax'))
classifier.compile(loss='sparse_categorical_crossentropy',
optimizer='adam', metrics=['accuracy'])
classifier.summary()
train_datagen = ImageDataGenerator(
rotation_range=25,
zoom_range=0.1,
width_shift_range=0.1,
height_shift_range=0.1,
shear_range=0.2,
horizontal_flip=True
)
val_datagen = ImageDataGenerator()
train_gen = train_datagen.flow(x_train, y_train, batch_size=batch_size)
val_gen = val_datagen.flow(x_test, y_test, batch_size=batch_size)
m = classifier.fit_generator(
train_gen,
steps_per_epoch=iter_per_epoch,
epochs=EPOCHS,
validation_data=val_gen,
validation_steps=val_per_epoch,
verbose=1
)

现在在另一个脚本中,我试图加载这个模型,但遇到上述错误

from keras.models import load_model
from tensorflow import Graph
import tensorflow as tf
img_w, img_h = 256, 256
gpuoptions = tf.compat.v1.GPUOptions(allow_growth=True)
graph = Graph()
with graph.as_default():
tf_session = tf.compat.v1.Session(
config=tf.compat.v1.ConfigProto(gpu_options=gpuoptions))
with tf_session.as_default():
model = load_model('classifier.h5')
path = "./images/test/Leaf Blast/blast__0_2632.jpg"
img = cv2.imread(path)
test_image = cv2.resize(img, (int(img_w*1.5), int(img_h*1.5)))
test_image = preprocess(test_image)
test_image = edge_and_cut(test_image)
test_image = np.array(test_image)
test_image = np.expand_dims(test_image, axis=0)
img_class = model.predict(test_image)
print(img_class)

以下是我的完整错误跟踪:

Traceback (most recent call last):
File "error.py", line 171, in <module>
img_class = model.predict(test_image)
File "C:UsersnambaAppDataLocalProgramsPythonPython38libsite-packagestensorflowpythonkerasenginetraining_v1.py", line 983, in predict
return func.predict(
File "C:UsersnambaAppDataLocalProgramsPythonPython38libsite-packagestensorflowpythonkerasenginetraining_arrays.py", line 708, in predict
return predict_loop(
File "C:UsersnambaAppDataLocalProgramsPythonPython38libsite-packagestensorflowpythonkerasenginetraining_arrays.py", line 259, in model_iteration
initial_epoch = model._maybe_load_initial_epoch_from_ckpt(initial_epoch, mode)
TypeError: _maybe_load_initial_epoch_from_ckpt() takes 2 positional arguments but 3 were given

我不知道是什么导致了这个错误。但是,下面的更改已经解决了这个问题。我删除了图形部分并加载了我的模型。现在显示结果。

class_dict = {'Bacterial leaf blight': 0,
'Brown spot': 1,
'Leaf Blast': 2,
'Leaf smut': 3
}
class_names = list(class_dict.keys())
img_w, img_h = 256, 256
model = load_model('classifier.h5')
path = "./images/test/Leaf Blast/blast__0_2632.jpg"
img = cv2.imread(path)
test_image = cv2.resize(img, (int(img_w*1.5), int(img_h*1.5)))
test_image = preprocess(test_image)
test_image = edge_and_cut(test_image)
test_image = np.array(test_image)
test_image = np.expand_dims(test_image, axis=0)
img_class = model.predict(test_image)
img_class = img_class.flatten()
m = max(img_class)
for index, item in enumerate(img_class):
if item == m:
pred_class = class_names[index]
print(pred_class)

相关内容

  • 没有找到相关文章

最新更新