Python 3.x CNN模型交叉验证的实现

Python 3.x CNN模型交叉验证的实现,python-3.x,tensorflow,scikit-learn,cnn,Python 3.x,Tensorflow,Scikit Learn,Cnn,我已经建立了我的CNN模型,对8类图像进行分类。训练和测试步骤是通过随机分割80%的训练图像和20%的测试图像来完成的,其中计算了锐度和F测量结果 我注意到,与我的测试结果相比,我的训练精度结果稍低(我认为训练精度应该更高)。在进行了大量搜索之后,我发现了两个原因: 1-使用落差(0.5),这会影响训练精度结果 2-测试数据集易于分类 我计划通过10-k交叉验证来评估我的CNN分类器。然而,由于我在这方面还是新手,所以我找到的大多数答案都是针对.csv文件的,在那里我有图像文件 如何编写代码以获

我已经建立了我的CNN模型,对8类图像进行分类。训练和测试步骤是通过随机分割80%的训练图像和20%的测试图像来完成的,其中计算了锐度和F测量结果

我注意到,与我的测试结果相比,我的训练精度结果稍低(我认为训练精度应该更高)。在进行了大量搜索之后,我发现了两个原因:

1-使用落差(0.5),这会影响训练精度结果

2-测试数据集易于分类

我计划通过10-k交叉验证来评估我的CNN分类器。然而,由于我在这方面还是新手,所以我找到的大多数答案都是针对.csv文件的,在那里我有图像文件

如何编写代码以获得交叉验证

我可以得到交叉验证的混淆矩阵吗

我的代码:

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,3)))
classifier.add(Activation('relu'))
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 =keras.optimizers.Adam(lr=0.001),
                   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/',
                                                target_size=(200,200),
                                                batch_size= batchsize,
                                                class_mode='categorical')

test_set = test_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Test/',
                                           target_size = (200,200),
                                           batch_size = batchsize,
                       shuffle=False,
                                           class_mode ='categorical')
history=classifier.fit_generator(training_set,
                        steps_per_epoch = 3067 // batchsize,
                        epochs = 50,
                        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()

在k-fold交叉验证中,原始样本被随机划分为k个大小相等的子样本。在k个子样本中,保留一个子样本作为模型测试的验证数据,剩余的k个子样本作为模型测试的验证数据− 1个子样本用作培训数据。

例如,就像您想要进行10倍交叉验证一样,您将

  • 将数据分成十个随机、相等的部分

  • 用九个数据子集训练十个单独的模型

  • 对每个模型的不同数据子集进行验证
  • 分别查找每个模型的混淆矩阵
  • 培训和测试的代码将保持不变,只是数据输入可以通过自定义生成器或使用SKLearn获取