【发布时间】:2019-02-04 10:00:30
【问题描述】:
所以,我是深度学习的新手,我开始使用 Keras 的 CNN 模型的猫和狗数据集。
在我的代码中,我无法将概率作为classifier.predict 或classifier.predict_proba 的输出。我只是得到[[0,1]] 或[[1,0]] 的输出。我尝试了几张图片。
但我正在寻找类似 @987654326@、[[0.89,0.11]] 的东西
我尝试将损失函数从 binary_crossentropy 更改为 categorical_crossentropy。
我尝试将输出层的激活函数从sigmoid 更改为softmax。
我还尝试将flow_from_directory 中的class_mode 从binary 更改为categorical。
我想我的数据类型可能有问题,因为输出数组的类型是 float32。但即使这是错误,我也不知道如何改变它。
我找不到哪里出错了。请澄清/帮助。谢谢。
为什么我需要概率?
在我的另一个项目中,我会将图像拆分为“n”个较小的部分。然后,我将分别对“n”个片段使用分类器,并找到概率最大的一个片段。为此,我不会使用猫和狗的数据集。它用于 bin-picking,该数据集也将二进制输出为“YES”或“NO”。也欢迎对此提出任何建议。谢谢。
Link 获取 Github 中的代码。
#Building the CNN
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
#Initialising the CNN
classifier = Sequential()
#Step 1 - Convolution
classifier.add(Convolution2D(filters=32,kernel_size=[3,3],input_shape=(64,64,3),activation='relu'))
#Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size=(2,2),strides=2))
#Adding another Convolutional Layer for better accuracy
#classifier.add(Convolution2D(filters=32,kernel_size=[3,3],activation='relu'))
#classifier.add(MaxPooling2D(pool_size=(2,2),strides=2))
#Step 3 - Flattening
classifier.add(Flatten())
#Step 4 - Fully Connected Layers
classifier.add(Dense(units= 64, activation='relu'))
classifier.add(Dense(units= 2, activation='softmax'))
#Compiling the CNN
classifier.compile(optimizer='adam',loss = 'categorical_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='categorical')
test_set = test_datagen.flow_from_directory('dataset/test_set',
target_size=(64,64),
batch_size=32,
class_mode='categorical')
classifier.fit_generator(training_set,
steps_per_epoch=250,
epochs=3, #Just for time being I've kept very few epochs.
validation_data=test_set,
validation_steps=62)
#Making new Predictions
import numpy as np
from keras.preprocessing import image
test_image_luna=image.load_img('dataset/single/SkilletLuna.JPG',target_size=(64,64))
test_image2=image.img_to_array(test_image_luna)
test_image2=np.expand_dims(test_image2,axis=0)
luna=classifier.predict_proba(test_image2)
In [11]: luna
...:
Out[11]: array([[0., 1.]], dtype=float32)
【问题讨论】:
-
您检查过预测的准确性吗? NN 至少学到了什么吗?
-
是的,它确实学会了。它在 1 个 epoch 内有 50% 的准确率。 25 个 epoch 的准确率达到 80%。它分类没有问题,唯一的事情是它应该给我一些至少一些图像的十进制值(当我使用classifer.predict时)并且它没有,这让我很困扰。 @markuscosinus
标签: python tensorflow keras neural-network conv-neural-network