使用Keras进行图像预测

时间:2017-05-04 06:24:29

标签: python deep-learning keras

我遵循本指南作为使用一些猫狗图像训练模型的开始:

https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html

这是代码:

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K


# dimensions of our images.
img_width, img_height = 150, 150

train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 2000
nb_validation_samples = 800
epochs = 1
batch_size = 16

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

# this is a generator that will read pictures found in
# subfolers of 'data/train', and indefinitely generate
# batches of augmented image data
train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

# this is a similar generator, for validation data
validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

model.save_weights('first_try.h5')
with open('model.json', 'w') as f:
    f.write(model.to_json())

所以我得到两个文件:first_try.h5和model.json。 现在我想尝试使用样本dog.jpg和cat.jpg进行简单的图像预测。这就是我试过的:

from keras.models import Sequential
from keras.layers import Dense
from keras.models import model_from_json
from PIL import Image
import cv2, numpy as np

# load json and create model
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("first_try.h5")
print("Loaded model from disk")

#attempt 1
img = cv2.resize(cv2.imread('cat.jpg'), (150, 150))
mean_pixel = [103.939, 116.779, 123.68]
img = img.astype(np.float32, copy=False)
for c in range(3):
    img[:, :, c] = img[:, :, c] - mean_pixel[c]
img = img.transpose((2,0,1))
img = np.expand_dims(img, axis=0)

out1 = loaded_model.predict(img)
print(np.argmax(out1))

#attempt 2
loaded_model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
img = Image.open('dog.jpg')
img = img.convert('RGB')
x = np.asarray(img, dtype='float32')
x = x.transpose(2, 0, 1)
x = np.expand_dims(x, axis=0)
out1 = loaded_model.predict(x)
print(np.argmax(out1))

我得到了这个输出:

Using Theano backend.
Loaded model from disk
0
0

有人可以指导我吗?如何正确地做一个model.predict?

1 个答案:

答案 0 :(得分:1)

我建议你使用(https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model):

from keras.models import load_model
model.save('model.hdf5')
model = load_model('model.hdf5')

无论如何,是什么让你认为这不是正确的输出?你在1值上做argmax。这自然是索引0.如果你想要最后一层的最终输出删除argmax然后你得到一个概率。