使用Keras进行图像预测 [英] Image prediction using Keras

查看:443
本文介绍了使用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

这是代码:

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进行简单的图像预测.这是我尝试过的:

So I get two files: first_try.h5 and model.json. Now I want to try to do a simple image prediction using a sample dog.jpg and a 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))

我得到以下输出:

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

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

无论如何,是什么让您认为这不是正确的输出?您对1个值执行argmax.自然地,它的索引为0.如果希望最后一层的最终输出删除argmax,那么您就有机会了.

Anyways, what makes you think that this is not the correct output? You do the argmax on 1 value. 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.

这篇关于使用Keras进行图像预测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆