【问题标题】:What does the prediction say? CNN Keras预言说什么? CNN 凯拉斯
【发布时间】:2017-10-09 17:14:38
【问题描述】:

我创建了一个CNN 模型来尝试预测图像是狗还是猫,但在输出上我不知道它预测了什么。见下文:

import pandas as pd
from keras.models import Sequential
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Dense, Flatten, Conv2D, Dropout, MaxPooling2D
from scipy import misc
import numpy as np

def build_classifier():
    # Model based on 'https://www.researchgate.net/profile/Le_Lu/publication/277335071/figure/fig8/AS:294249976352779@1447166069905/Figure-8-The-proposed-CNN-model-architecture-is-composed-of-five-convolutional-layers.png'
    #It's smarter to add layer without creating variables because of the processing, but as a small dataset it doesn't matter a lot.
    classifier = Sequential()

    conv1 = Conv2D(filters=64, kernel_size=(2,2), activation='relu', input_shape=(64,64,3))
    conv2 = Conv2D(filters=192, kernel_size=(2,2), activation='relu')
    conv3 = Conv2D(filters=384, kernel_size=(2,2), activation='relu')
    conv4 = Conv2D(filters=256, kernel_size=(2,2), activation='relu')
    conv5 = Conv2D(filters=256, kernel_size=(2,2), activation='relu')
    pooling1 = MaxPooling2D(pool_size=(2,2))
    pooling2 = MaxPooling2D(pool_size=(2,2))
    pooling3 = MaxPooling2D(pool_size=(2,2))
    fcl1 = Dense(1024, activation='relu')
    fcl2 = Dense(1024, activation='relu')
    fcl3 = Dense(2, activation='softmax')
    dropout1= Dropout(0.5)
    dropout2 = Dropout(0.5)
    flatten = Flatten()

    layers = [conv1, pooling1, conv2, pooling2, conv3, conv4, conv5,
             pooling3, flatten, fcl1, dropout1, fcl2, dropout2, fcl3]

    for l in layers:
        classifier.add(l)

    return classifier

model = build_classifier()
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
        'dataset/training_set',
        target_size=(64, 64),
        batch_size=32,
        class_mode='categorical')

validation_generator = test_datagen.flow_from_directory(
        'dataset/test_set',
        target_size=(64, 64),
        batch_size=32,
        class_mode='categorical')


model.fit_generator(
        train_generator,
        steps_per_epoch=200,
        epochs=32,
        validation_data=validation_generator,
        validation_steps=100)

model.save('model.h5')
model.save_weights('model_weights.h5')

我在另一个文件中打开了我保存的模型:

from keras.models import load_model
from scipy import misc
import numpy as np

def single_pred(filepath, model):
    classifier = load_model(model)
    img = misc.imread(filepath)
    img = misc.imresize(img, (64,64,3))
    img = np.expand_dims(img, 0)
    print(classifier.predict(img))

if __name__ == '__main__':
    single_pred('/home/leonardo/Desktop/Help/dataset/single_prediction/cat_or_dog_2.jpg', 'model.h5')

作为输出我得到这个:

Using TensorFlow backend.
2017-10-09 14:06:25.520018: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-10-09 14:06:25.520054: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
[[ 0.  1.]]

但是我怎么知道预测是狗还是猫?有了这个结果,我仍然不知道图像是狗还是猫。

【问题讨论】:

  • 确实有人需要阅读一些基础教程。忽略这一点在未来不会有太大的乐趣。 提示:看看你的最后一层fcl3 = Dense(2, activation='softmax'),你的输入形状和你的损失!
  • 输入形状有什么问题?
  • 我没有说有什么问题。我暗示了关于解释输出的 3 件最重要的事情。
  • fcl3 = Dense(2,activation='softmax'),表示您正在进行两类分类,并且 [0 1] 输出表明它预测了第二类 (1),无论它是什么
  • 好的,谢谢

标签: python computer-vision keras artificial-intelligence


【解决方案1】:

除非您指定标签,否则您的生成器会自动为您创建分类标签。您可以使用train_generator.class_indices 检查那些 类标签的顺序是字母数字,所以cats=0 dogs=1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-06
    • 2020-03-02
    • 2021-07-19
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多