简体   繁体   English

使用Keras进行图像预测

[英]Image prediction using Keras

I am following this guide as a start to train a model using some cats and dogs images: 我遵循此指南作为开始使用一些猫和狗图像训练模型的开始:

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

This is the code: 这是代码:

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())

So I get two files: first_try.h5 and model.json. 所以我得到两个文件:first_try.h5和model.json。 Now I want to try to do a simple image prediction using a sample dog.jpg and a cat.jpg. 现在,我想尝试使用样本dog.jpg和cat.jpg进行简单的图像预测。 This is what I tried: 这是我尝试的:

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))

I get this output: 我得到以下输出:

Using Theano backend.
Loaded model from disk
0
0

Can someone guide me? 有人可以指导我吗? How to do a model.predict correctly? 如何正确进行模型预测?

I would suggest you use ( https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model ): 我建议您使用( 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')

Anyways, what makes you think that this is not the correct output? 无论如何,是什么让您认为这不是正确的输出? You do the argmax on 1 value. 您对1个值执行argmax。 This is naturally the index 0. If you want the final output of the last layer remove the argmax and then you get a probability. 自然地,它的索引为0。如果希望最后一层的最终输出除去argmax,则可以得到一个概率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM