我一直在使用Keras网络来对图像进行分类,判断它们是否包含交通灯,但到目前为止我还没有成功。我有一个包含11000多张图像的数据集,第一次测试我使用了240张图像(实际上是每个图像的灰度像素值的文本文件)。输出只有一个 – 0或1,表示图像是否包含交通灯。
然而,当我运行测试时,它只预测了一个类别。由于240张图像中有53张包含交通灯,它达到了大约79%的准确率,因为它一直预测0。我读到这可能是由于数据不平衡造成的,所以我缩减到了只有4张图像 – 2张有交通灯,2张没有。
即使在这种测试中,经过5个epoch后,它仍然停留在50%的准确率;它只是在预测一个类别!类似的问题已经得到了解答,但我还没有找到对我有用的解决方案:(
这是我使用的代码:
from keras.datasets import mnistfrom keras import modelsfrom keras import layersfrom keras.utils import to_categoricalimport numpy as npimport ostrain_images = []train_labels = []#以下只是管理任务 - 从文本文件中提取灰度像素值#并将它们添加到输入数组中。同样处理标签,这些标签#是从文本文件中提取并添加到输出数组中的。对性能不重要。 for fileName in os.listdir('pixels1/'): newRead = open(os.path.join('pixels1/', fileName)) currentList = [] for pixel in newRead: rePixel = int(pixel.replace('\n', ''))/255 currentList.append(rePixel) train_images.append(currentList) for fileName in os.listdir('labels1/'): newRead = open(os.path.join('labels1/', fileName)) line = newRead.readline() train_labels.append(int(line))train_images = np.array(train_images)train_labels = np.array(train_labels)train_images = train_images.reshape((4,13689))#modelmodel = models.Sequential()model.add(layers.Dense(13689, input_dim=13689, activation='relu'))model.add(layers.Dense(13689, activation='relu'))model.add(layers.Dense(1, activation='softmax'))model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])model.fit(train_images, train_labels, epochs=5, batch_size=1)
我至少希望它能在最后识别出这些图像。我真的很想继续在我的11,000个样本上进行训练,但目前我连4个样本都无法让它正常工作。
回答:
粗略要点:
-
你似乎认为你的密集层的单元数应该等于你的数据维度(13869);事实并非如此。将它们都改为更小的数(在100-200范围内) – 它们甚至不必相等。考虑到你相对较少的数据样本(图像),这么大的模型是不推荐的。
-
由于你是在二元分类设置中,并且最后一层只有一个节点,你应该对这一(最后一)层使用
activation=sigmoid
,并使用loss='binary_crossentropy'
来编译你的模型。 -
在图像应用中,通常前几层是卷积层。