python - Keras 图像分类损失

标签 python tensorflow keras conv-neural-network image-recognition

我正在尝试制作一个可以识别口袋妖怪的简单 CNN 模型。第一次尝试时,我自己创建了一个非常小的数据集,由 10 个不同 Pokemon 的 100 张图片组成。 在 Python 中使用这段代码,看起来运行良好。

import tensorflow as tf
import numpy as np

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(32, (3,3), input_shape=(200,200,3), activation='relu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(32, (3,3), activation='relu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(units=400, activation='relu'))
model.add(tf.keras.layers.Dense(units=10, activation='sigmoid'))

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

train = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)
test = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)

training_set= train.flow_from_directory('datasets/starter/train', target_size=(200,200), class_mode='categorical')
val_set= test.flow_from_directory('datasets/starter/test', target_size=(200,200), class_mode='categorical')

history=model.fit_generator(training_set, steps_per_epoch=32, epochs=3, validation_data=val_set, validation_steps=32)

test_image = tf.keras.preprocessing.image.load_img('datasets/starter/val/attempt.png', target_size=(200, 200))
test_image = tf.keras.preprocessing.image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis=0)
result = model.predict(test_image)
print(training_set.class_indices)
print(result)

test_image2 = tf.keras.preprocessing.image.load_img('datasets/starter/val/attempt2.png', target_size=(200, 200))
test_image2 = tf.keras.preprocessing.image.img_to_array(test_image2)
test_image2 = np.expand_dims(test_image2, axis=0)
result2 = model.predict(test_image2)
print(training_set.class_indices)
print(result2)

最后一个epoch的训练精度固定为1。 当我尝试预测示例图像时: attempts.png是一张Charmander图片,它的标签是1,所以我得到这个向量:[[0。 1.0.0....0.]] attempts2.png是一张Torchic图片,它的标签是7,所以我得到:[[0。 0. ... 1.0.0.]]

但我注意到“model.compile”中的损失应该是“categorical_crossentropy”而不是“binary_crossentropy”。使用分类程序,我的程序将不再工作。 有人可以帮我理解吗?

最佳答案

您应该尝试使用 Softmax 作为最后一个激活,并使用分类交叉熵作为损失函数

关于python - Keras 图像分类损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58333926/

相关文章:

python - Kivy:如何更改 TabbedPanel 的边框?

machine-learning - TensorFlow - 无效参数 : Reshape:0 is both fed and fetched

python - Keras 文档 : Multi-input and multi-output models Not able to follow

python - TensorFlow 2.0 C++ - 加载预训练模型

python字典更新方法来扩展字典

python - 如何从文件中删除重复的行?

python - Argv - 字符串到整数

python - 使用 tfx 运行多个训练器时 Kubeflow Pipeline RuntimeError

machine-learning - 在深度学习方法中结合临床和图像数据的最佳方法是什么?

machine-learning - 使用keras训练多类nn时,loss无法进一步往下走,可能是什么原因