前言:
该项目使用了CNN模型、Dense Network模型,项目旨在通过深度学习技术,卷积神经网络。对两百张图片自动分类图片中的衣物为“衣服”或“裤子”,并提供了从数据预处理、模型构建、训练、评估到预测结果应用的完整工作流程。
深度学习技术是什么:
深度学习技术是一种人工智能(AI)的分支,它属于机器学习领域,其灵感来源于生物大脑中神经网络的工作机制。这项技术使计算机能够通过学习从原始数据中自动提取特征,并利用这些特征来进行预测、决策或其他复杂任务,深度学习技术通过模拟人类大脑的多层次抽象处理机制,实现了对复杂数据模式的高效学习和理解,是推动当前人工智能快速发展的重要力量。
卷积神经网络是什么:
卷积神经网络(Convolutional Neural Networks, CNN)是一种特殊类型的神经网络,专为处理具有网格结构的数据(如图像和语音)而设计。CNN的核心优势在于它能够自动学习和提取输入数据中的空间特征,无需人工设计特征,这使得它在计算机视觉、自然语言处理、音频处理等领域取得了显著成就。CNN特别适合处理图像识别、物体检测、图像分类、语义分割等任务,在诸多AI应用中发挥着至关重要的作用。
完整代码:
#导入所需的库
import glob
import numpy as np
import pandas as pd
from PIL import Image
import warnings
#忽略掉警告信息
warnings.filterwarnings('ignore')
# 文件路径
test= "1t\*"
tain= "t2\*"
# 收集所有图片文件路径
clothe= [file for file in glob.iglob(test)]
pant= [file for file in glob.iglob(tain)]
clothes= np.zeros(len(clothe))# 初始化标签 创建全为0的NumPy数组
pants= np.ones(len(pant))#全为1的NumPy数组
# 使用字典创建DataFrame
data_dict = {
'filepath': clothe+pant,
'label': np.concatenate((clothes,pants))
}
# 通过字典构造DataFrame
df_photos = pd.DataFrame(data_dict)
df_photos
from sklearn.model_selection import train_test_split
df_train, df_test = train_test_split(df_photos, test_size=0.2, random_state=1)#其中测试集占总数据的20%,random_state=1确保每次运行结果一致
df_train.reset_index(drop=True, inplace=True)# reset_index方法去除原索引,并重新设置索引,避免后续处理中的混淆
df_test.reset_index(drop=True, inplace=True)
# 图像预处理函数
def process_image(filepath):
return np.asarray(Image.open(filepath).resize((128, 128)).convert("L")) / 255.0 #将像素值归一化到[0,1]区间内,通过除以255实现
# 加载并预处理训练和测试图像
train_images = np.array([process_image(path) for path in df_train['filepath']])
test_images = np.array([process_image(path) for path in df_test['filepath']])
train_labels = df_train['label'].values
test_labels = df_test['label'].values
from keras.layers import Dense #用于全连接层
from tensorflow.keras.models import Sequential #Sequential模型 创建神经网络模型
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten
from tensorflow.keras.preprocessing.image import ImageDataGenerator
#Sequential是Keras提供创建线性堆叠模型的类,适合于那些各层之间是简单的串联
model_enhanced = Sequential([
Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(128, 128, 1)),#激活函数为ReLU
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.25),
Conv2D(64, kernel_size=(3, 3), activation='relu'),
MaxPooling2D(pool_size=(2, 2)),#最大池化操作 降低空间维度,减少计算量
Dropout(0.25),#防止过拟合。它随机关闭一部分神经元,减少神经元间的相互依赖
Flatten(),
Dense(256, activation='relu'),
Dropout(0.5),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(2, activation='softmax')
])
# 编译模型
from tensorflow import keras#Adam优化器
opt = keras.optimizers.Adam(learning_rate=0.001)#寻找更精细的模型参数调整
model_enhanced.compile(optimizer=opt,
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])#accuracy作为评估指标,用于监控模型在训练和验证过程中的分类准确率
# 使用 ImageDataGenerator 进行数据增强
datagen = ImageDataGenerator(
rotation_range=10,
zoom_range=0.1,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True,
validation_split=0.2 # 保留20%的数据用于验证
)
history = model_enhanced.fit(train_images, train_labels, epochs=20, validation_split=0.2)
#将其转换为灰度图像的NumPy数组
from PIL import Image
def process_images(image_path):
# 打开图像文件
with Image.open(image_path) as img:
# 转换为灰度图像
img_gray = img.convert('L')
# 将PIL图像转换为numpy数组,以便于与其他库(如matplotlib)兼容
img_gray_array = np.array(img_gray)
return img_gray_array
#简单直观地展示经过预处理后的灰度图像
from matplotlib import pyplot as plt
img = process_images(clothe[22])
# 显示图片
fig = plt.figure(figsize=(4,4))
ax = fig.add_subplot(111)
ax.imshow(img, cmap="gray")
ax.set_xticks([])
ax.set_yticks([])
plt.show()
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
# 设置中文字体
plt.rcParams['font.sans-serif']=['SimHei'] # 用黑体显示中文
plt.rcParams['axes.unicode_minus']=False # 正常显示负号
# 训练集中绘制16张图片
fig = plt.figure(figsize=(10, 10))
for i in range(16):
plt.subplot(4, 4, i+1)
img = process_image(df_train["filepath"].iloc[i])
plt.imshow(img, cmap="gray")
plt.grid(False)
plt.xticks([])
plt.yticks([])
if df_train["label"].iloc[i] == 0:
plt.title("衣服", size=10)
else:
plt.title("裤子", size=10)
plt.show()
# 绘制准确率图表
fig = plt.figure(figsize=(15,5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax1.plot(history.history['accuracy'])
ax1.plot(history.history['val_accuracy'])
ax1.set_title('Model Accuracy')
ax1.set_ylabel('Accuracy')
a