CNN Keras не принимает 1 канал для черно-белых изображений - PullRequest
0 голосов
/ 16 февраля 2020

Я преобразовал свои изображения в черно-белые с использованием приведенного ниже кода

image_file = Image.open('colored.png') # open colour image
    image_file = image_file.convert('1') # convert image to black and white
    image_file.save('black_white.png')

Когда я передаю полученные изображения в свою сеть CNN в Керасе, это дает мне следующее

ValueError: Ошибка при проверке ввода: ожидалось, что conv2d_1_input будет иметь форму (200, 200, 1), но получил массив с формой (200, 200, 3)

Ниже приведен мой код Keras CNN, я что-то упустил?

from keras.models import Sequential
from keras.layers import Conv2D,Activation,MaxPooling2D,Dense,Flatten,Dropout
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from IPython.display import display
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.metrics import classification_report, confusion_matrix
import keras
from keras.layers import BatchNormalization
from keras.optimizers import Adam


classifier = Sequential()
classifier.add(Conv2D(32,(3,3),input_shape=(200,200,1)))
classifier.add(Activation('relu'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Conv2D(32,(3,3)))
classifier.add(Activation('relu'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Conv2D(64,(3,3)))
classifier.add(Activation('relu'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Flatten())
classifier.add(Dense(128))
classifier.add(Activation('relu'))
classifier.add(Dropout(0.5))
classifier.add(Dense(8))
classifier.add(Activation('softmax'))
classifier.summary()
classifier.compile(optimizer ='adam',
                   loss ='categorical_crossentropy',
                   metrics =['accuracy'])
train_datagen = ImageDataGenerator(rescale =1./255,
                                   shear_range =0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip =True)
test_datagen = ImageDataGenerator(rescale = 1./255)

batchsize=10
training_set = train_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Train_grey/',
                                                target_size=(200,200),
                                                batch_size= batchsize,
                                                class_mode='categorical')

test_set = test_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Test_grey/',
                                           target_size = (200,200),
                                           batch_size = batchsize,
                       shuffle=False,
                                           class_mode ='categorical')
history=classifier.fit_generator(training_set,
                        steps_per_epoch = 3067 // batchsize,
                        epochs = 30,
                        validation_data =test_set,
                        validation_steps = 769 // batchsize)


Y_pred = classifier.predict_generator(test_set, steps= 769 // batchsize + 1)
y_pred = np.argmax(Y_pred, axis=1)
print('Confusion Matrix')
print(confusion_matrix(test_set.classes, y_pred))
print('Classification Report')
target_names = test_set.classes
class_labels = list(test_set.class_indices.keys()) 
target_names = ['coinhive','emotent','fareit', 'flystudio', 'gafgyt','gamarue', 'mirai','razy'] 
report = classification_report(test_set.classes, y_pred, target_names=class_labels)
print(report) 

# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

1 Ответ

1 голос
/ 16 февраля 2020

В вашем вызове flow_from_directory() отсутствует параметр "color_mode"; даже если вы вручную конвертируете фотографии в оттенки серого в указанной выше функции, за занавесками flow_from_directory() загружает их и конвертирует их обратно в RGB из-за значения по умолчанию 'color_mode=rgb'.

Используйте его следующим образом:

 train_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Train_grey/',
                                                target_size=(200,200),
                                                color_mode='grayscale',
                                                batch_size= batchsize,
                                                class_mode='categorical')
...