我正在开发一种 AI,它可以分析图像并识别 5 个可能的对象。我在 python 中使用 tf.keras,它在之前的项目中运行良好,但对于这个项目,无论我训练多长时间,它都会给出随机结果(20% 的准确度和 5 种可能的输出)。
5 个可能的对象是: - 四足动物 - 人形 - 飞机 - 卡车 - 汽车
我之前尝试过使用完全连接的神经网络,使用完全相同的数据集,经过 10 分钟的训练,它的准确率约为 50%。我的目标是达到 90% 的准确率,这就是我尝试使用 CNN 的原因。 我还玩了一下 mnist 数据集,并使用 tf.keras 制作了一个识别手写数字的 cnn。我尝试使用相同的 keras 模型,但失败了。我尝试了不同的模型,但都未能给出非随机预测。
这是我的 keras 模型:
import tensorflow as tf
layers = tf.keras.layers
model = tf.keras.models.Sequential([
layers.Conv2D(16, (3, 3), input_shape=(80, 80, 1), activation='relu'),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(32, (3, 3), activation='relu'),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Dropout(0.2),
layers.Flatten(),
layers.Dense(512, activation=tf.nn.relu),
layers.Dense(5, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
我正在用这段代码训练它:
x, y = self.load_data(input("File containg train files: "), input("File containg labels files: ")) # function that takes a .mat file and return an array of shape (29160, 1, 80, 80)
x = x.reshape(total_data_number, 80, 80, 1)
x = x.astype('float32')
x /= 255.0
epoch = 15
model.fit(x, y, batch_size=50, epochs=epoch, verbose=1)
全连接模型是这个:
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(80, 80, 1)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(5, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
准确率应该远高于 20%,并且在我训练模型时应该会提高。
请您参考如下方法:
您的一些问题可能是因为您使用的是 sparse_categorical_crossentropy 而您的输出是一个 one_hot_encoded 向量。因此,您应该改用 categorical_crossentropy。 (基本解释here)
