我如何从Keras获得概率?
我为3个班级训练了CNN模型。当我在新的测试图像上使用经过训练的模型的predict()方法(使用Functional API)时,总是得到一个热编码输出,ei [0, 1, 0]
,而我想得到诸如[0.1, 0.95, 0.1]
之类的输出
我使用softmax
作为最后一次激活,因此所有概率之和总计为1。但是,我创建了一个虚拟模型,仅在一个时期内对其进行了训练,但仍然获得了一个热编码输出,而不是概率。
我在这里做错了吗,比如调用错误的方法?否则如何获取最后一层的输出,以便可以对输出进行规范化?
预测脚本的片段:
model = load_model('./model.h5')
model.compile(loss='categorical_crossentropy',
optimizer='adadelta',
metrics=['acc'])
img = image.load_img(path.name,
target_size=(128, 128),
color_mode='grayscale')
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
probability = model.predict(img)
print(probability)
培训脚本:
# Creates input shape for theano or tensorflow.
if K.image_data_format() == 'channels_first':
input_shape = (1, 128, 128)
else:
input_shape = (128, 128, 1)
visible = Input(shape=input_shape)
conv1_1 = Conv2D(filters=8,kernel_size=(5, 5),padding='same', strides = 1)(visible)
prelu1_1 = PReLU(alpha_initializer='zeros')(conv1_1)
pool1_1 = MaxPooling2D(pool_size=(2, 2),strides=2)(prelu1_1)
flat1 = Flatten()(pool1_1)
conv2_1 = Conv2D(filters=8,kernel_size=(5, 5),padding='same', strides = 1)(visible)
prelu2_1 = PReLU(alpha_initializer='zeros')(conv2_1)
pool2_1 = MaxPooling2D(pool_size=(2, 2),strides=2)(prelu2_1)
flat2 = Flatten()(pool2_1)
# Merge layers
merge = concatenate([flat1, flat2])
dense = Dense(64)(merge)
prelu3 = PReLU(alpha_initializer='zeros')(dense)
dropout3 = Dropout(rate=0.4)(prelu3)
dense4 = Dense(3)(dropout3)
output = Activation('softmax')(dense4)
model = Model(inputs=visible, outputs=output)
model.compile(loss='categorical_crossentropy',
optimizer='Adadelta',
metrics=['accuracy'])
train_datagen = ImageDataGenerator(
rescale=1. / 255,
shear_range=0.2,
width_shift_range=0.1,
height_shift_range=0.1,
rotation_range=5,
horizontal_flip=True)
test_datagen = ImageDataGenerator(
rescale=1. / 255, )
train_data_dir = r'D:\path\to\train'
validation_data_dir = r'D:\path\to\validation'
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(128, 128),
batch_size=32,
color_mode='grayscale',
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(128, 128),
batch_size=32,
color_mode='grayscale',
class_mode='categorical')
model_final = model.fit_generator(
train_generator,
steps_per_epoch=11000 // 32,
epochs=1,
validation_data=validation_generator,
validation_steps=3000 // 32)
# Save model
model.save('./model.h5')
Keras版本:2.1.6
注意:
model
建立在功能性API上,即(keras.models.Model()
)
答案 0 :(得分:1)
如果您不使用功能性API,则可以进行console.log
以获取概率。
model.predict_proba()
希望这会有所帮助。