当前位置: 首页 > news >正文

人工智能-深度学习之卷积神经网络

深度学习

  • mlp弊端
  • 卷积神经网络
    • 图像卷积运算
    • 卷积神经网络的核心
    • 池化层实现维度缩减
    • 卷积神经网络
    • 卷积神经网络两大特点
    • 卷积运算导致的两个问题:
    • 图像填充(padding)
    • 结构组合问题
    • 经典CNN模型
      • LeNet-5模型
      • AlexNet模型
      • VGG-16模型
    • 经典的CNN模型用于新场景
  • 实战
    • 实战(1):建立CNN实现猫狗识别
    • 实战(2):基于VGG16、结合mlp实现猫狗识别


mlp弊端

mlp模型的弊端:图片大时,参数也很多。
办法:提取出图像中的关键信息,再建立mlp模型进行训练。
在这里插入图片描述

卷积神经网络

图像卷积运算

对图像矩阵与滤波器矩阵进行对应相乘再求和运算,转化得到新的矩阵。
作用:快速定位图像中某些边缘特征
英文:convolution(卷积神经网络:CNN)
在这里插入图片描述
在这里插入图片描述
将图片与轮廓滤波器进行卷积运算,可快速定位固定轮廓特征的位置
在这里插入图片描述

卷积神经网络的核心

计算机根据样本图片,自动寻找合适的轮廓过滤器,对新图片进行轮廓匹配
自动求解W,寻找合适的过滤器。一个过滤器不够,需要寻找很多过滤器。
在这里插入图片描述
RGB图像的卷积:对R/G/B三个通道分别求卷积再相加。(如图,为两个过滤器)
在这里插入图片描述

池化层实现维度缩减

池化:按照一个固定规则对图像矩阵进行处理,将其转换为更地维度的矩阵
Srtide为窗口滑动步长,用于池化、卷积的计算中。
保留核心信息的情况下,实现维度缩减。
最大法池化(Max-pooling):
在这里插入图片描述
平均法池化(Avg-pooling):
在这里插入图片描述

卷积神经网络

把卷积、池化、mlp先后连接在一起,组成卷积神经网络
在这里插入图片描述

卷积神经网络两大特点

1、参数共享(parameter sharing):同一个特征过滤器可用于整张图片
2、稀疏连接(sparsity of connections):生成的特征图片每个节点只与原图片中特定节点连接
在这里插入图片描述

卷积运算导致的两个问题:

1、图像被压缩,信息丢失
2、边缘信息使用少,容易被忽略
在这里插入图片描述

图像填充(padding)

通过在图像各边添加像素,使其在进行卷积运算后维持原图大小
在这里插入图片描述
通过padding增加像素的数量,由过滤器尺寸与stride决定

结构组合问题

在这里插入图片描述

经典CNN模型

1、参考经典CNN结构搭建新模型
2、使用经典CNN模型结构对图像预处理,再建立MLP模型
经典CNN模型:
1、LeNet-5
2、AlexNet
3、VGG

LeNet-5模型

在这里插入图片描述

解析:第一次(32-5)/1+1=28,第二次(28-2)/2+1=14,第三次(14-5)/1+1=10,第四次(10-2)/2+1=5.
输入图像:32x32灰度图,一个通道(channel)
训练参数:约60000个
特点:
1、随着网络越深,图像的高度和宽度在缩小,通道数在增加
2、卷积和池化先后成对使用

AlexNet模型

在这里插入图片描述
输入图像:227x227x3 RGB图,3个通道
训练参数:约60000000个
特点:
1、适用于识别较为复杂的彩色图,可识别1000种类别
2、结构比LeNet更为复杂,使用Relu作为激活函数
结果:
学术界开始相信深度学习技术,在计算机视觉应用中可以得到很不错的效果

VGG-16模型

在这里插入图片描述
输入图像:227x227x3 RGB图,3个通道
训练参数:约138000000个
特点:
1、所有卷积层filter宽和高都是3,步长为1,padding都使用same convolution;
2、所有池化层的filter宽和高都是2,步长为2;
3、相比alexnet,有更多的filter用于提取轮廓信息,具有更高精准性;

经典的CNN模型用于新场景

1、使用经典的CNN模型结构对图像预处理,再建立MLP模型;
2、参考经典的CNN结构搭建新模型

1、加载经典的CNN模型,剥除其FC层,对图像进行预处理
2、把预处理完成的数据作为输入,分类结果为输出,建立一个mlp模型
3、模型训练
在这里插入图片描述

在这里插入图片描述

实战

实战(1):建立CNN实现猫狗识别

任务:基于dataset/training_set数据,根据提供的结构,建立CNN模型
1、识别图片中的猫/狗、计算dataset/test_set测试数据预测准确率
2、从网站下载猫/狗图片,对其进行预测
在这里插入图片描述

#load the data
from keras.preprocessing.image import ImageDataGenrator
train_datagen = ImageDataGenerator(rescale=1./255)
training_set = train_datagen.flow_from_directory('./dataset/training_set',target_size=(50,50),batch_size=32,class_mode='binary')#set up the cnn model
from keras.models import Sequential
form keras.layers import Conv2D, MaxPool2D, Flatten, Dense
model = Sequential()
#卷积层
model.add(Conv2D(32,(3,3),input_shape=(50,50,3),activation='relu'))
#池化层
model.add(MaxPool2D(pool_size=(2,2)))
#卷积层
model.add(Conv2D(32,(3,3),activation='relu'))
#池化层
model.add(MaxPool2D(pool_size=(2,2)))
#flattening layer
model.add(Flatten())
#FC layer
model.add(Dense(units=128,activation='relu'))
model.add(Dense(units=1,activation='sigmoid'))#configure the model
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
model.summary()#train the model
model.fit_generator(training_set,epochs=25)
#accuracy on the training data
accuracy_train = model.evaluate_generator(training_set)
print(accuracy_train)
#accuracy on the test data
test_set = train_datagen.flow_from_directory('./dataset/test_set',target_size=(50,50),batch_size=32,class_mode='binary')
accuracy_test = model.evaluate_generator(test_set)
print(accuracy_test)#load single image
from keras.preprocessing.image import load_img, img_to_array
pic_dog = 'dog.jpg'
pic_dog = load_img(pic_dog,target_size=(50,50))
pic_dog = img_to_array(pic_dog)
pic_dog = pic_dog/255
pic_dog = pic_dog.reshape(1,50,50,3)
result = model.predict_classes(pic_dog)
print(result)pic_cat = 'cat.jpg'
pic_cat = load_img(pic_cat,target_size=(50,50))
pic_cat = img_to_array(pic_cat)
pic_cat = pic_cat/255
pic_cat = pic_cat.reshape(1,50,50,3)
result = model.predict_classes(pic_cat)
print(result)
#补充说明,以下方法可以查看输出的数字是什么标签,如'cat':0,'dogs':1
training_set.class_indices
#make prediction on multiple images
import matplotlib as mlp
font2 = {'family':'SomHei','weight':'normal','size': 20,}
mlp.rcParams['font.family'] = 'SimHei'
mlp.rcParams['axes.unicode_minus'] = False
from matplotlib import pyplot as plt
from matplotlib.image import imread
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.models import load_model
a = [i for range(1,10)]
fig = plt.figure(figsize=(10,10))
for i in a:img_name = str(i)+'.jpg'img_ori = load_img(img_name,target_size=(50,50))img = img_to_array(img_ori)img = img.astype('float32')/255img = img.reshape(1,50,50,3)result = model.predict_classes(img)img_ori = load_img(img_name, target_size=(250,250))plt.subplot(3,3,i)plt.imshow(img_ori)plt.title('预测为:狗狗' if result[0][0] == 1 else '预测为:猫咪')
plt.show()

实战(2):基于VGG16、结合mlp实现猫狗识别

任务:使用VGG16的结构提取图像特征,再根据特征建立mlp模型,实现猫狗图像识别。训练/测试数据:dataset\data_vgg
1、对数据进行分离、计算测试数据预测准确率
2、从网站下载猫/狗图片,对其进行预测
备注:mlp模型只有一个隐藏层(10个神经元)

#load the data 
from keras.preprocessing.image import load_img,img_to_array
img_path = '1.jpg'
img = load_img(img_path,target_size=(224,224))
img = img_to_array(img)
type(img)from karas.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
import numpy as nn
model_vgg = VGG16(weights='imagenet',include_top=False)
x = np.expand_dims(img,axis=0)
x = preprocess_input(x)
print(x.shape)#特征提取
features = model_vgg.predict(x)
print(features.shape)
#flatten
features = features.reshape(1,7*7*512)
print(features.shape)
#visualize the data
%matplotlib inline
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(5,5))
img = load_img(img_path,target_size=(224,224))
plt.imshow(img)
#此处为批量处理
#load image and preprocess it with vgg16 structure
from keras.preprocessing.image import img_to_array,load_img
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
import numpy as npmodel_vgg = VGG16(weight='imagent',include_top=False)
#define a method to load and preprocess the image
def modelProcess(img_path,model):img = load_img(img_path, target_size=(224,224))img = img_to_array(img)x = np.expand_dims(img,axis=0)x = preprocess_input(x)x_vgg = model.predict(x)x_vgg = x_vgg.reshape(1,25088)return x_vgg#list file names of the training datasets
import os
folder = "dataset/data_vgg/cats"
dirs = os.listdir(folder)
#generate path for the images
img_path = []
for i in dirs:if os.path.splitext(i)[1] == ".jpg":img_path.append(i)
img_path = [folder+"//"+i for i in img_path]#preprocess multiple images
features1 = np.zeros([len(img_path),25088])
for i in range(len(img_path)):feature_i = modelProcess(img_path[i],model_vgg)print('preprocessed:',img_path[i])features1[i] = feature_ifolder = "dataset/data_vgg/dogs" 
dirs = os.listdir(folder)
#generate path for the images
img_path = []
for i in dirs:if os.path.splitext(i)[1] == ".jpg":img_path.append(i)
img_path = [folder+"//"+i for i in img_path]
#preprocess multiple images
features2 = np.zeros([len(img_path),25088])
for i in range(len(img_path)):feature_i = modelProcess(img_path[i],model_vgg)print('preprocessed:',img_path[i])features2[i] = feature_i#label the results
print(features1.shape,features2.shape)
y1 = np.zeros(300)
y2 = np.ones(300)#generate the training data
X = np.concatenate((features1,features2),axis=0)
y = np.concatenate((y1,y2),axis=0)
y = y.reshape(-1,1)
print(X.shape,y.shape)#split the training and test data
from sklearn.model_selection import train_test_split
X_train,y_trian,X_test,y_test = train_test_split(X,y,test_size=0.3,random_state=50)
pirnt(X_train.shape,X_test.shape,X/shape)#set up the mlp model
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(units=10,activation='relu',input_dim=25088))
model.add(Dense(units=1,activation='sigmoid'))
model.summary()
#configure the model
model.compile(optimizer='adam',loss='binary_crossentropy',metric=['accuracy'])
#train the model
model.fit(X_train,y_train,epochs=50)from sklearn.metrics import accuracy_score
y_train_predict = model.predict_classes(X_train)
accuracy_train = accuracy_score(y_train,y_train_predict)
print(accuracy_train)#测试准确率
y_test_predict = model.predict_classes(X_test)
accuracy_test = accuracy_score(y_test,y_test_predict)
print(accuracy_test)# coding:utf-8 批量处理图片
import matplotlib as mlp
font2 = { 'family' : 'SimHei','weight' : 'normal','size'   : 20,
}
mlp.rcParams['font.family'] = 'SimHei'
mlp.rcParams['axes.unicode_minus'] = False
from matplotlib import pyplot as plt
from matplotlib.image import imread
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.models import load_model
#from cv2 import load_img
a = [i for i in range(1,10)]
fig = plt.figure(figsize=(10,10))
for i in a:img_name = str(i)+'.jpg'img_path = img_nameimg = load_img(img_path, target_size=(224, 224))img = img_to_array(img)x = np.expand_dims(img,axis=0)x = preprocess_input(x)x_vgg = model_vgg.predict(x)x_vgg = x_vgg.reshape(4,25088)result = model.predict_classes(x_vgg)img_ori = load_img(img_name, target_size=(250, 250))plt.subplot(3,3,i)plt.imshow(img_ori)plt.title('预测为:狗狗' if result[0][0] == 1 else '预测为:猫咪')
plt.show()

相关文章:

  • 如何在Cursor中使用MCP服务
  • 使用Python和Pandas实现的Amazon Redshift权限检查与SQL生成用于IT审计
  • Java SE(6)——类和对象
  • 贪心算法精解(Java实现):从理论到实战
  • python-MySQL鏈接
  • JavaScript延迟加载
  • 【深度学习-Day 2】图解线性代数:从标量到张量,理解深度学习的数据表示与运算
  • OpenStack Yoga版安装笔记(25)Nova Cell理解
  • 【ESP32】st7735s + LVGL使用-------图片显示
  • 【五一培训】Day1
  • MySQL基础关键_003_DQL(二)
  • WEB UI自动化测试之Selenium框架学习
  • 【HarmonyOS】作业三 UI
  • 【信息系统项目管理师-论文真题】2024上半年(第二批)论文详解(包括解题思路和写作要点)
  • 【云备份】服务端工具类实现
  • Unity动态列表+UniTask异步数据请求
  • 嵌入式AI还是一片蓝海
  • MySQL 服务搭建
  • 范式演进:从ETL到ELT及未来展望
  • 多智能体空域协同中的伦理博弈与系统调停
  • 2024年境内酒店住宿行业指标同比下滑:酒店行业传统增长模式面临挑战
  • 格桑花盛放上海,萨迦艺术团襄阳公园跳起藏族舞
  • 保险经纪公司元保在纳斯达克挂牌上市,去年净赚4.36亿元
  • 两部门预拨4000万元支持山西、广西、陕西做好抗旱救灾工作
  • 强制性国家标准《危险化学品企业安全生产标准化通用规范》发布
  • 外交部:中美双方并未就关税问题进行磋商或谈判