一、笑脸数据集(genki4k)正负样本的划分、模型训练和测试的过程(至少包括SVM、CNN),输出模型训练精度和测试精度(F1-score和ROC)
1.训练数据
1) 导入Keras
import keras
keras.__version__
'2.3.1'
2) 读取数据集,训练
import os, shutil
# The path to the directory where the original
# dataset was uncompressed
original_dataset_dir = 'smileface/genki4k'
# The directory where we will
# store our smaller dataset
base_dir = 'smileface/1'
os.mkdir(base_dir)
# Directories for our training,
# validation and test splits
train_dir = os.path.join(base_dir, 'train')
os.mkdir(train_dir)
validation_dir = os.path.join(base_dir, 'validation')
os.mkdir(validation_dir)
test_dir = os.path.join(base_dir, 'test')
os.mkdir(test_dir)
# Directory with our training smile pictures
train_smile_dir = os.path.join(train_dir, 'smiles')
os.mkdir(train_smile_dir)
# Directory with our training nosmile pictures
train_nosmile_dir = os.path.join(train_dir, 'no_smiles')
os.mkdir(train_nosmile_dir)
# Directory with our validation smile pictures
validation_smile_dir = os.path.join(validation_dir, 'smiles')
os.mkdir(validation_smile_dir)
# Directory with our validation nosmile pictures
validation_nosmile_dir = os.path.join(validation_dir, 'no_smiles')
os.mkdir(validation_nosmile_dir)
# Directory with our validation smile pictures
test_smile_dir = os.path.join(test_dir, 'smiles')
os.mkdir(test_smile_dir)
# Directory with our validation nosmile pictures
test_nosmile_dir = os.path.join(test_dir, 'no_smiles')
os.mkdir(test_nosmile_dir)
3)将笑脸数据存入对应文件夹
print('total training smile images:', len(os.listdir(train_smile_dir)))
print('total training nosmile images:', len(os.listdir(train_nosmile_dir)))
print('total validation smile images:', len(os.listdir(validation_smile_dir)))
print('total validation nosmile images:', len(os.listdir(validation_nosmile_dir)))
print('total test smile images:', len(os.listdir(test_smile_dir)))
print('total test nosmile images:', len(os.listdir(test_nosmile_dir)))
total training smile images: 2162
total training nosmile images: 1837
total validation smile images: 2162
total validation nosmile images: 1837
total test smile images: 2162
total test nosmile images: 1837
4) 构建小型卷积神经网络
from keras import layers
from keras import models
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu',
input_shape=(150, 150, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
了解征图的尺寸是如何随着每一层变化的
model.summary()
Model: "sequential_2"
_________________________________________________________________
Layer (type) Output Shape Param #
===============================================================