【发布时间】:2018-06-21 09:01:55
【问题描述】:
我正在尝试从 keras 模型中获取每个类别的概率。请在下面找到示例 keras 模型:
width = 80
height = 80
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=( width, height, 3)))
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()) # this converts our 3D feature maps to 1D feature vectors
model.add(Dense(64))
model.add(Activation('relu'))
#model.add(Dropout(0.5))
model.add(Dense(2))
model.add(Activation('softmax'))
model.compile(loss='sparse_categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
但是,在训练模型之后,我加载了要预测的图像:
img = image.load_img('Test2.jpg', target_size=(80, 80))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict_proba(images, batch_size=1)
print(classes)
[[ 0. 1.]]
我仍然得到类标签,而不是概率。任何提示我做错了什么?
编辑 这就是模型的训练方式:
train_datagen = ImageDataGenerator(
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
train_generator = train_datagen.flow_from_directory(
'.\\train', # this is the target directory
target_size=(width, height), # all images will be resized to 150x150
batch_size=batch_size,
class_mode='binary',
shuffle=True) # since we use binary_crossentropy loss, we need binary labels
# this is a similar generator, for validation data
validation_generator = test_datagen.flow_from_directory(
'.\\validate',
target_size=(width, height),
batch_size=batch_size,
class_mode='binary',
shuffle=True)
model.fit_generator(
train_generator,
steps_per_epoch=4000,
epochs=2,
validation_data=validation_generator,
validation_steps=1600)
【问题讨论】:
-
您是否标准化了您的训练数据?您是否相应地对输入图像进行了标准化?
-
0 和 1 也是有效概率。
-
大家好,感谢您的及时反应。我用训练模型/加载样本的代码更新了问题。我认为我没有在任何地方进行标准化,还是我错了? (keras新手)。在我看来,任何一个课程的概率都那么高,对吗?但是会尝试不同的样本并让您知道。
标签: python deep-learning keras