Я пытаюсь построить модель классификации изображений с 2 классами с (1) или без (0).Я могу построить модель и получить точность 1. Это слишком хорошо, чтобы быть правдой (что является проблемой), но когда я использую предикат_генератор, поскольку у меня есть изображения в папках, он возвращает только 1 класс 0 (без класса).Кажется, есть проблема, но я не могу решить ее, я просмотрел ряд статей, но все еще не могу решить эту проблему.
image_shape = (220, 525, 3) #height, width, channels
img_width = 96
img_height = 96
channels = 3
epochs = 10
no_train_images = 11957 #!ls ../data/train/* | wc -l
no_test_images = 652 #!ls ../data/test/* | wc -l
no_valid_images = 6156 #!ls ../data/test/* | wc -l
train_dir = '../data/train/'
test_dir = '../data/test/'
valid_dir = '../data/valid/'
test folder structure is the following:
test/test_folder/images_from_both_classes.jpg
#!ls ../data/train/without/ | wc -l 5606 #theres no class inbalance
#!ls ../data/train/with/ | wc -l 6351
#!ls ../data/valid/without/ | wc -l 2899
#!ls ../data/valid/with/ | wc -l 3257
classification_model = Sequential()
# First layer with 2D convolution (32 filters, (3, 3) kernel size 3x3, input_shape=(img_width, img_height, channels))
classification_model.add(Conv2D(32, (3, 3), input_shape=input_shape))
# Activation Function = ReLu increases the non-linearity
classification_model.add(Activation('relu'))
# Max-Pooling layer with the size of the grid 2x2
classification_model.add(MaxPooling2D(pool_size=(2, 2)))
# Randomly disconnets some nodes between this layer and the next
classification_model.add(Dropout(0.2))
classification_model.add(Conv2D(32, (3, 3)))
classification_model.add(Activation('relu'))
classification_model.add(MaxPooling2D(pool_size=(2, 2)))
classification_model.add(Dropout(0.2))
classification_model.add(Conv2D(64, (3, 3)))
classification_model.add(Activation('relu'))
classification_model.add(MaxPooling2D(pool_size=(2, 2)))
classification_model.add(Dropout(0.25))
classification_model.add(Conv2D(64, (3, 3)))
classification_model.add(Activation('relu'))
classification_model.add(MaxPooling2D(pool_size=(2, 2)))
classification_model.add(Dropout(0.3))
classification_model.add(Flatten())
classification_model.add(Dense(64))
classification_model.add(Activation('relu'))
classification_model.add(Dropout(0.5))
classification_model.add(Dense(1))
classification_model.add(Activation('sigmoid'))
# Using binary_crossentropy as we only have 2 classes
classification_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
batch_size = 32
# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
rescale=1. / 255,
zoom_range=0.2)
# this is the augmentation configuration we will use for testing:
# only rescaling
valid_datagen = ImageDataGenerator(rescale=1. / 255)
test_datagen = ImageDataGenerator()
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size = (img_width, img_height),
batch_size = batch_size,
class_mode = 'binary',
shuffle = True)
valid_generator = valid_datagen.flow_from_directory(
valid_dir,
target_size = (img_width, img_height),
batch_size = batch_size,
class_mode = 'binary',
shuffle = False)
test_generator = test_datagen.flow_from_directory(
test_dir,
target_size = (img_width, img_height),
batch_size = 1,
class_mode = None,
shuffle = False)
mpd = classification_model.fit_generator(
train_generator,
steps_per_epoch = no_train_images // batch_size, # number of images per epoch
epochs = epochs, # number of iterations over the entire data
validation_data = valid_generator,
validation_steps = no_valid_images // batch_size)
Epoch 1/10 373/373 [==============================] - 119 с 320 мс / шаг - потеря: 0,5214 - соотв: 0,7357 - val_loss: 0,2720 - val_acc: 0,8758
Эпоха 2/10 373/373 [=============================] - 120 с 322 мс/ шаг - потери: 0,2485 - в соответствии с: 0,8935 - потери по величине: 0,0568 - значения по умолчанию: 0,9829
Эпоха 3/10 373/373 [==============================] - 130 с 350 мс / шаг - потеря: 0,1427 - акк: 0,9435 - val_loss: 0,0410 - val_acc: 0,9796
Эпоха 4/10 373/373 [==============================] - 127 с 341 мс / шаг - потеря: 0,1053 - в соответствии: 0,9623 - val_loss: 0,0197 - val_acc: 0,9971
Epoch 5/10 373/373 [===================================] - 126 с 337мс / шаг- потери: 0,0817 - счета: 0,9682 - потери по величине: 0,0136 - потери по величине: 0,9948
Эпоха 6/10 373/373 [==============================] - 123s 329ms / step - потеря: 0.0665 - acc: 0.9754 - val_loss: 0.0116- val_acc: 0,9985
Epoch 7/10 373/373 [=============================] -140 с 376 мс / шаг - потеря: 0,0518 - в соответствии с: 0,9817 - потеря по величине: 0,0035 - значение по умолчанию: 0,9997
Эпоха 8/10 373/373 [==============================] - 144 с 386 мс / шаг - потеря: 0,0539 - с: 0,9832 - val_loss: 8,9459e-04 - val_acc: 1,0000
эпоха 9/10 373/ 373 [==============================] - 122 с 327 мс / шаг - потеря: 0,0434 - согласно: 0,9850 - val_loss:0.0023 - val_acc: 0.9997
Epoch 10/10 373/373 [=============================]- 125 с 336 мс / шаг - потеря: 0,0513 - в соответствии с: 0,9844 - значение_расхода: 0,0014 - значение_оценки: 1,0000
valid_generator.batch_size=1
score = classification_model.evaluate_generator(valid_generator,
no_test_images/batch_size, pickle_safe=False)
test_generator.reset()
scores=classification_model.predict_generator(test_generator, len(test_generator))
print("Loss: ", score[0], "Accuracy: ", score[1])
predicted_class_indices=np.argmax(scores,axis=1)
print(predicted_class_indices)
labels = (train_generator.class_indices)
labelss = dict((v,k) for k,v in labels.items())
predictions = [labelss[k] for k in predicted_class_indices]
filenames=test_generator.filenames
results=pd.DataFrame({"Filename":filenames,
"Predictions":predictions})
print(results)
потеря: 5,404246180551993e-06 Точность: 1,0
печать (прогнозируемые_классы_индексов) -ВСЕ 0
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
Filename Predictions
0 test_folder/video_3_frame10.jpg without
1 test_folder/video_3_frame1001.jpg without
2 test_folder/video_3_frame1006.jpg without
3 test_folder/video_3_frame1008.jpg without
4 test_folder/video_3_frame1009.jpg without
5 test_folder/video_3_frame1010.jpg without
6 test_folder/video_3_frame1013.jpg without
7 test_folder/video_3_frame1014.jpg without
8 test_folder/video_3_frame1022.jpg without
9 test_folder/video_3_frame1023.jpg without
10 test_folder/video_3_frame103.jpg without
11 test_folder/video_3_frame1036.jpg without
12 test_folder/video_3_frame1039.jpg without
13 test_folder/video_3_frame104.jpg without
14 test_folder/video_3_frame1042.jpg without
15 test_folder/video_3_frame1043.jpg without
16 test_folder/video_3_frame1048.jpg without
17 test_folder/video_3_frame105.jpg without
18 test_folder/video_3_frame1051.jpg without
19 test_folder/video_3_frame1052.jpg without
20 test_folder/video_3_frame1054.jpg without
21 test_folder/video_3_frame1055.jpg without
22 test_folder/video_3_frame1057.jpg without
23 test_folder/video_3_frame1059.jpg without
24 test_folder/video_3_frame1060.jpg without
... только некоторые выходы, но все 650+ не имеют класса.
Это вывод, и, как вы можете видеть, все прогнозируемые значения равны 0 для класса без.
Это моя первая попытка использования Keras и CNN, поэтому любая помощь будет очень признательна.
ОБНОВЛЕНИЕ
Я решил это.В настоящее время я работаю над точностью, но основная проблема теперь решена.
Это линия, которая вызвала проблемы.
predicted_class_indices=np.argmax(scores,axis=1)
argmax будет возвращать позицию индекса результата, но, поскольку я использовал двоичные классы, и в моем последнем слое у меня была 1 плотность.Он будет возвращать только одно значение, поэтому он всегда будет возвращать первый класс (0 в качестве позиции индекса).Поскольку сеть настроена только на возвращение одного класса.
Изменение следующего исправило мою проблему.
- Изменил class_mode на «категорический» для генератора поезда и теста
- Изменен последний плотный слой с 1 на 2, так что это будет возвращать баллы / вероятности для обоих классов.Поэтому, когда вы используете argmax, он вернет индексную позицию верхней оценки, указывающую, какой класс он предсказал.