关于python的Keras预测

关于python的Keras预测,python,tensorflow,keras,Python,Tensorflow,Keras,我的CNN有以下代码: 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 # dime

我的CNN有以下代码:

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 = 64, 64

train_data_dir = "path_trainning"
validation_data_dir = "path_validation"
nb_train_samples = 2000
nb_validation_samples = 800
epochs = 10
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)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

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('my_cnn.h5')
这是我预测的代码:

for file in os.listdir(targets_path):
    filef = '\\' + file
    test_image = image.load_img(targets_path + filef, target_size=(64, 64))
    test_image = image.img_to_array(test_image)
    test_image = np.expand_dims(test_image, axis=0)
    result = model.predict(test_image)
    print("\nOriginal: " + file)
    print("Prediction: " + str(result[0][0]))
    if result[0][0] == 1:
        prediction = 'dog'
    else:
        prediction = 'cat'
    print(prediction)
我的问题是:

有了这个代码作为“预测”部分,我意识到除非CNN有一个1,否则它不会是一只狗。我得到的结果是0.99999是一只猫,但有了这个值,它更接近于一只狗

我想我没有完全理解它


有人能解释一下吗?

这是因为输出层是一个带有sigmoid激活的节点,它返回的值介于0和1之间。因此,结果永远不会是1(或0),因此代码将始终返回“cat”。

这是因为输出层是带有sigmoid激活的节点,该节点返回的值介于0和1之间。因此,结果永远不会是1(或0),因此代码将始终返回“cat”。

这可能是您的CNN的问题

您正在隐藏层中使用ReLU激活。它们的输出范围从0到无穷大。当这些值通过最终的输出激活时,在您的情况下是sigmoid。如果我将更大的值(如25)传递给sigmoid,则输出将接近1。同样的情况也会发生在非常小的值上,这将导致阈值接近0

如果在隐藏层中使用ReLU,则应在输出层使用softmax函数。Softmax将logits转换为类概率


而且,对于softmax,您将使用分类类而不是二进制类。您将有2个类,因此有2个输出节点。

这可能是您的CNN的问题

您正在隐藏层中使用ReLU激活。它们的输出范围从0到无穷大。当这些值通过最终的输出激活时,在您的情况下是sigmoid。如果我将更大的值(如25)传递给sigmoid,则输出将接近1。同样的情况也会发生在非常小的值上,这将导致阈值接近0

如果在隐藏层中使用ReLU,则应在输出层使用softmax函数。Softmax将logits转换为类概率


而且,对于softmax,您将使用分类类而不是二进制类。您将有2个类,因此有2个输出节点。

OK,我编辑了这篇文章。但是,我也养了一些狗。有时它返回1.0记住,您的输出是每个类的“概率”,因此,如果您指定标签1=cat,那么测试图像的概率>0.5将导致,您应该将其预测为cat。这是我不理解的。我,作为一个程序员,如果一个图像有>0.5p的狗的感觉,我会说它是一只狗。但是在我发布的代码中,只有当它等于1时,我才有一只狗。所以如果结果[0][0]>0.5或者什么的话,我应该改变它并把它放到
上吗?好的,我编辑了这篇文章。但是,我也养了一些狗。有时它返回1.0记住,您的输出是每个类的“概率”,因此,如果您指定标签1=cat,那么测试图像的概率>0.5将导致,您应该将其预测为cat。这是我不理解的。我,作为一个程序员,如果一个图像有>0.5p的狗的感觉,我会说它是一只狗。但是在我发布的代码中,只有当它等于1时,我才有一只狗。所以如果结果[0][0]>0.5
或其他内容,我是否应该更改该值并放入
值错误:检查目标时出错:预期激活_5具有形状(1),但获得了具有形状(2)的数组。我将
class_模式
更改为category,并得到了errorValueError:Error当检查目标时:预期激活_5具有形状(1),但得到了具有形状(2,)的数组。我将
class\u模式
更改为categorical,并得到了那个错误