我是ML的新手,我正在尝试玩一些本教程: https://medium.com/@ferhat00/deep-learning-with-keras-classifying-cats-and-dogs-part-2-21b3b25bbe5c。无论如何,CNN似乎仅在训练后我没有将其保存在h5文件中的情况下才起作用。更精确地:
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import Dropout
from keras import optimizers
classifier = Sequential()
classifier.add(Conv2D(32, (3, 3), input_shape = (128, 128, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Conv2D(64, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Flatten())
classifier.add(Dense(units = 64, activation = 'relu'))
classifier.add(Dropout(0.5))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('PetImages/training_set',
target_size = (128, 128),
batch_size = 32,
class_mode = 'binary')
test_set = test_datagen.flow_from_directory('PetImages/test_set',
target_size = (128, 128),
batch_size = 32,
class_mode = 'binary')
history = classifier.fit_generator(training_set,
steps_per_epoch = 8000/32,
epochs = 30,
validation_data = test_set,
validation_steps = 2000/32, workers=12, max_q_size=100)
///////////////////////////////////////
classifier.save("cnnPetsModel.h5")
print("saved model to disk")
///////////////////////////////////////
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np
img_path = 'PetImages/test_set/Dog/5000.jpg'
img = image.load_img(img_path, target_size=(128, 128))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = classifier.predict(x)
training_set.class_indices
print(preds)
if preds[0][0] == 1:
prediction = 'dog'
else:
prediction = 'cat'
print(prediction)
img_path = 'PetImages/test_set/Cat/5000.jpg'
img = image.load_img(img_path, target_size=(128, 128))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = classifier.predict(x)
training_set.class_indices
print(preds)
if preds[0][0] == 1:
prediction = 'dog'
else:
prediction = 'cat'
print(prediction)
如果删除“ ////////”之间的代码,则可以正确预测这两个图像,但是在保存模型的情况下,它们始终变为“ cat”。为什么会这样?我只在文件中保存参数,结构等。 预先感谢!