基于VGG16的图像二分类模型训练与评估
基于VGG16的图像二分类模型训练与评估
本项目使用VGG16模型提取图像特征,并利用神经网络进行图像二分类,并绘制训练集与验证集的准确率和损失曲线。
环境准备
import os
import matplotlib.pyplot as plt
import numpy as np
from keras.applications import VGG16
from keras.preprocessing.image import ImageDataGenerator
数据准备
data_dir = 'ss'+os.sep+'image'
train_dir = os.path.join(data_dir, 'train')
test_dir = os.path.join(data_dir, 'test')
模型构建
vgg_model = VGG16(weights='imagenet', include_top=False, input_shape=(150,150,3))
vgg_model.summary()
数据预处理
datagen = ImageDataGenerator(rescale=1./255)
特征提取函数
def extract_features(directory, sample_count):
features = np.zeros(shape=(sample_count,4,4,512))
labels = np.zeros(shape=(sample_count))
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
提取特征
batch_size = 20
train_features, train_labels = extract_features(train_dir, 2000)
test_features,test_labels = extract_features(test_dir, 1000)
特征重塑
train_features = np.reshape(train_features, (2000, 4*4*512))
test_features = np.reshape(test_features, (1000, 4*4*512))
模型训练
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'])
history = model.fit(train_features,train_labels,
epochs=30,
batch_size=batch_size,
validation_data=(test_features,
test_labels))
绘制训练曲线
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()
总结
本项目利用VGG16模型提取图像特征,并使用神经网络进行图像二分类。通过训练和评估,我们可以观察到模型的准确率和损失的变化趋势,并根据结果进行模型优化。
原文地址: https://www.cveoy.top/t/topic/n9Ax 著作权归作者所有。请勿转载和采集!