首页 文章

如何在Keras中使用创建的CNN模型和新数据

提问于
浏览
2

我只是按照一个教程,用CNras和Keras(Tensorflow后端)对猫和狗的10k图像进行分类 .

一切似乎都没问题,我在测试和训练集上都获得了很好的准确性:

....    
    Epoch 24/25
    250/250 [==============================] - 26s 104ms/step - loss: 0.2938 - acc: 0.8745 - val_loss: 0.4235 - val_acc: 0.8270
    Epoch 25/25
    250/250 [==============================] - 25s 99ms/step - loss: 0.2901 - acc: 0.8719 - val_loss: 0.4324 - val_acc: 0.8270

But how do I use this model to predict the class of a new image?

我的代码创建并适合分类器:

# Importing the Keras libraries and packages
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
import PIL
#these 2 lines are for timer
import cv2
from timeit import default_timer as timer
start = timer()
# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), activation="relu", input_shape=(64, 64, 3)))
# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation="relu"))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units=128, activation="relu"))
classifier.add(Dense(units=1, activation="sigmoid"))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Part 2 - Fitting the CNN to the images
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('dataset/training_set',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'binary')
test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size = (64, 64),
                                            batch_size = 32,
                                            class_mode = 'binary')
classifier.fit_generator(training_set,
                         steps_per_epoch = 250,
                         epochs = 25,
                         validation_data = test_set,
                         validation_steps = 63)
# elapsed time
end = timer()
print(end - start)
# end of work message
import os
os.system('say "your program has finished"')

数据集:here

2 回答

  • 3

    这应该工作 . 我喜欢使用 skimage ,但这取决于你 .

    import skimage.io as io
    import skimage.transform as tr
    
    img = io.imread('img.jpg')         # Reads the image
    img = tr.resize(img, (64, 64, 3))  # Resizes the image
    img = img[np.newaxis, ...]         # Adds a new dim to simulate a batch
    pred = classifier.predict(img)     # Predicts a value between 0 and 1
    
    if pred > 0.5:
        print('Class 1')
    else:
        print('Class 2')
    
  • 1

    您还可以为要预测的数据创建另一个 ImageDataGenerator() . 请注意,您计划预测的此数据在技术上称为测试集,而您称为测试集的数据实际上是验证集 .

    在任何情况下,在为测试集创建 ImageDataGenerator() 之后,您可以以与调用 classifier.fit_generator() 的方式类似的方式调用 classifier.predict_generator() . 我展示了如何做到这一点的一个例子here .

相关问题