基于VGG16特征提取的图像分类模型训练

本项目使用VGG16预训练模型提取图像特征,并在此基础上构建分类模型,实现对图像的分类。代码涵盖了数据预处理、特征提取、模型训练和评估等环节,并使用matplotlib绘制了训练过程中的准确率和损失曲线。

1. 导入库

import os
import matplotlib.pyplot as plt
import numpy as np
from keras.applications import VGG16
from keras.preprocessing.image import ImageDataGenerator

2. 设置数据路径

data_dir = 'ss'+os.sep+'image'
train_dir = os.path.join(data_dir, 'train')
test_dir = os.path.join(data_dir, 'test')

3. 加载VGG16模型

vgg_model = VGG16(weights='imagenet', include_top=False, input_shape=(150,150,3))
vgg_model.summary()

4. 数据增强

datagen = ImageDataGenerator(rescale=1./255)

5. 定义特征提取函数

# 定义提取特征函数
def extract_features(directory, sample_count):
    #VGG16最后池化层的输出特征初始化储存张量
    features = np.zeros(shape=(sample_count,4,4,512))
    labels = np.zeros(shape=(sample_count))
    #从数据样本文件夹按batch_size数加载图像
    generator = datagen.flow_from_directory(directory,
                                            target_size=(150,150),
                                            batch_size=batch_size,
                                            class_mode='binary')
    i = 0
    for inputs_batch, labels_batch in generator:
        features_batch = vgg_model.predict(inputs_batch)
        features[i*batch_size : (i+1) * batch_size] = features_batch
        labels[i*batch_size : (i+1) * batch_size] = labels_batch
        i += 1
        # 
        if i *batch_size >= sample_count:
            break
    return features, labels

6. 提取训练集和测试集特征

batch_size = 20
# 
train_features, train_labels = extract_features(train_dir, 2000)
#validation_features, validation_labels = extract_features(validation_dir, 1000)
test_features,test_labels = extract_features(test_dir, 1000)
# 
train_features = np.reshape(train_features, (2000, 4*4*512))
#validation_features = np.reshape(validation_features, (1000, 4*4*512))
test_features = np.reshape(test_features, (1000, 4*4*512))

7. 构建分类模型

from keras import models
from keras import layers
from keras import optimizers
# 
model = models.Sequential()
model.add(layers.Dense(256,activation='relu',input_dim=4*4*512))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(1,activation='sigmoid'))
model.compile(optimizer=optimizers.Adam(lr=2e-5),
              loss='binary_crossentropy',
              metrics=['acc'])

8. 模型训练

history = model.fit(train_features,train_labels,
                    epochs=30,
                    batch_size=batch_size,
                    validation_data=(test_features,
                                     test_labels))

9. 绘制训练结果

acc = history.history['acc']
val_acc = history.history['val_acc']
epochs = range(1, len(acc) + 1)
plt.figure()
plt.plot(epochs,acc,'bo',label='训练集准确率')
plt.plot(epochs,val_acc,'b',label='验证集准确率')
plt.title('训练集与验证集准确率曲线')
plt.legend()
plt.show()

# 
acc = history.history['loss']
val_acc = history.history['val_loss']
epochs = range(1,len(acc) + 1)
plt.figure()
plt.plot(epochs,acc,'bo',label='训练集损失')
plt.plot(epochs,val_acc,'b',label='验证集损失')
plt.title('训练集与验证集损失曲线')
plt.legend()
plt.show()

10. 中文显示

如果需要在matplotlib图表中显示中文,可以添加以下行:

#在代码中添加以下行
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False

这会将字体设置为中文字体“SimHei”,并且禁用减号“-”的unicode。

总结

本项目展示了如何使用VGG16预训练模型提取图像特征,并构建分类模型进行图像分类。代码简洁易懂,可以作为入门学习的参考。

基于VGG16特征提取的图像分类模型训练

原文地址: https://www.cveoy.top/t/topic/n9AZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录