Keras 多分类中的多个预测?
More than one prediction in multi-classification in Keras?
我正在学习如何使用 Keras 设计卷积神经网络。我开发了一个使用 VGG16 作为基础的简单模型。我在数据集中有大约 6 classes 个图像。这是我的模型的代码和描述。
model = models.Sequential()
conv_base = VGG16(weights='imagenet' ,include_top=False, input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))
conv_base.trainable = False
model.add(conv_base)
model.add(layers.Flatten())
model.add(layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.001)))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(6, activation='sigmoid'))
编译和拟合模型的代码如下:
model.compile(loss='categorical_crossentropy',
optimizer=optimizers.RMSprop(lr=1e-4),
metrics=['acc'])
model.summary()
callbacks = [
EarlyStopping(monitor='acc', patience=1, mode='auto'),
ModelCheckpoint(monitor='val_loss', save_best_only=True, filepath=model_file_path)
]
history = model.fit_generator(
train_generator,
steps_per_epoch=10,
epochs=EPOCHS,
validation_data=validation_generator,
callbacks = callbacks,
validation_steps=10)
这是预测新图像的代码
img = image.load_img(img_path, target_size=(IMAGE_SIZE, IMAGE_SIZE))
plt.figure(index)
imgplot = plt.imshow(img)
x = image.img_to_array(img)
x = x.reshape((1,) + x.shape)
prediction = model.predict(x)[0]
# print(prediction)
通常 model.predict() 方法会预测多个 class。
[0 1 1 0 0 0]
我有几个问题
- 多class class化模型预测多个输出是否正常?
- 如果预测了不止一个 class,如何在训练时间内衡量准确性?
- 如何修改神经网络以便只预测一个 class?
感谢任何帮助。非常感谢!
你做的不是多classclass化,而是多标签。这是由在输出层使用 sigmoid 激活引起的。要正确执行多 class class 化,请在输出处使用 softmax 激活,这将在 classes 上产生概率分布。
按照预期,采用最大概率 (argmax) 的 class 将产生单个 class 预测。
我正在学习如何使用 Keras 设计卷积神经网络。我开发了一个使用 VGG16 作为基础的简单模型。我在数据集中有大约 6 classes 个图像。这是我的模型的代码和描述。
model = models.Sequential()
conv_base = VGG16(weights='imagenet' ,include_top=False, input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))
conv_base.trainable = False
model.add(conv_base)
model.add(layers.Flatten())
model.add(layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.001)))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(6, activation='sigmoid'))
编译和拟合模型的代码如下:
model.compile(loss='categorical_crossentropy',
optimizer=optimizers.RMSprop(lr=1e-4),
metrics=['acc'])
model.summary()
callbacks = [
EarlyStopping(monitor='acc', patience=1, mode='auto'),
ModelCheckpoint(monitor='val_loss', save_best_only=True, filepath=model_file_path)
]
history = model.fit_generator(
train_generator,
steps_per_epoch=10,
epochs=EPOCHS,
validation_data=validation_generator,
callbacks = callbacks,
validation_steps=10)
这是预测新图像的代码
img = image.load_img(img_path, target_size=(IMAGE_SIZE, IMAGE_SIZE))
plt.figure(index)
imgplot = plt.imshow(img)
x = image.img_to_array(img)
x = x.reshape((1,) + x.shape)
prediction = model.predict(x)[0]
# print(prediction)
通常 model.predict() 方法会预测多个 class。
[0 1 1 0 0 0]
我有几个问题
- 多class class化模型预测多个输出是否正常?
- 如果预测了不止一个 class,如何在训练时间内衡量准确性?
- 如何修改神经网络以便只预测一个 class?
感谢任何帮助。非常感谢!
你做的不是多classclass化,而是多标签。这是由在输出层使用 sigmoid 激活引起的。要正确执行多 class class 化,请在输出处使用 softmax 激活,这将在 classes 上产生概率分布。 按照预期,采用最大概率 (argmax) 的 class 将产生单个 class 预测。