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

深度学习

  • 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()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/79300.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

蓝桥杯电子赛_继电器和蜂鸣器

目录 一 前言 二 继电器和蜂鸣器实物 三 分析部分 (1)bsp_init.c (2)蜂鸣器和继电器原理图 (3)ULN2003 (4)他们俩所连接的锁存器 四 代码 在这里要特别说一点!&…

仿腾讯会议——主界面设计创建房间加入房间客户端实现

1、实现腾讯会议主界面 2、添加Qt类WeChatDialog 3、定义创建会议和加入会议的函数 4、实现显示名字、头像的函数 调用函数 5、在中间者类中绑定函数 6、实现创建房间的槽函数 7、实现加入房间的槽函数 8、设置界面标题 9、服务器定义创建和进入房间函数 10、服务器实现创建房间…

网络编程初识

注:此博文为本人学习过程中的笔记 1.socket api 这是操作系统提供的一组api,由传输层向应用层提供。 2.传输层的两个核心协议 传输层的两个核心协议分别是TCP协议和UDP协议,它们的差别非常大,编写代码的风格也不同&#xff0c…

【质量管理】现代TRIZ问题识别中的功能分析——功能模型

功能模型的定义 功能模型是对工程系统进行功能分析的一个阶段,目的是建立工程系统的功能模型。功能模型描述了工程系统和超系统组件的功能,包括有用功能、性能水平和成本等。 在文章【质量管理】现代TRIZ中问题识别中的功能分析——相互接触分析-CSDN博客…

广告事件聚合系统设计

需求背景 广告事件需要进行统计,计费,分析等。所以我们需要由数据接入,数据处理,数据存储,数据查询等多个服务模块去支持我们的广告系统 规模上 10000 0000个点击(10000 00000 / 100k 1wQPS) …

C语言中,sizeof关键字(详细介绍)

目录 ‌1. 基本用法‌(1) ‌基本数据类型‌(2) ‌变量‌(3) ‌数组‌(4) ‌指针‌ ‌2. 特殊用法‌(1) ‌结构体与内存对齐‌(2) ‌动态内存分配‌(3) ‌表达式‌ ‌3. 注意事项‌‌1)sizeof 与 strlen 的区别‌:‌2)变长数组(VLA…

ADK 第三篇 Agents (LlmAgent)

Agents 在智能体开发套件(ADK)中,智能体(Agent)是一个独立的执行单元,旨在自主行动以实现特定目标。智能体能够执行任务、与用户交互、使用外部工具,并与其他智能体协同工作。 在ADK中&#x…

【深度学习】典型的 CNN 网络

目录 一、LeNet-5 (1)LeNet-5 网络概览 (2)网络结构详解 (3)关键组件与数学原理 3.1 局部感受野与卷积运算 3.2 权重共享 3.3 子采样(Pooling) 3.4 激活函数 (4…

4.8/Q1,中山大学用NHANES:膳食烟酸摄入量与非酒精性脂肪肝之间的关联

文章题目:Association between Dietary Niacin Intake and Nonalcoholic Fatty Liver Disease: NHANES 2003-2018 DOI:10.3390/nu15194128 中文标题:膳食烟酸摄入量与非酒精性脂肪肝之间的关联:NHANES 2003-2018 发表杂志&#xf…

高效管理远程服务器Termius for Mac 保姆级教程

以下是 Termius for Mac 保姆级教程,涵盖安装配置、核心功能、实战案例及常见问题解决方案,助你高效管理远程服务器(如Vultr、AWS等)。 一、Termius 基础介绍 1. Termius 是什么? 跨平台SSH客户端:支持Ma…

理解数学概念——支集(支持)(support)

1. 支集(support)的定义 在数学中,一个实函数 f 的支集(support)是函数的不被映射到 0 的元素域(即定义域)的子集。若 f 的(定义)域(domain)是一个拓扑空间(即符合拓扑的集合),则 f 的支集则定义为包含( f 的元素域中)不被映射到0的所有点之最小闭集…

Vue 3 Element Plus 浏览器使用例子

Element Plus 是一个基于 Vue 3 的流行开源 UI 库,提供了一系列的组件,帮助开发者快速构建现代化的用户界面。它的设计简洁、现代,包含了许多可定制的组件,如按钮、表格、表单、对话框等,适合用于开发各种 Web 应用。 …

SSR vs SSG:前端渲染模式终极对决(附 Next.js/Nuxt.js 实战案例)

一、引言:前端渲染模式的进化之路 随着互联网的发展,用户对于网页的加载速度和交互体验要求越来越高。前端渲染技术作为影响网页性能的关键因素,也在不断地发展和演进。从最初的客户端渲染(CSR),到后来的服…

算法笔记.分解质因数

代码实现&#xff1a; #include<iostream> using namespace std; void breakdown(int x) {int t x;for(int i 2;i < x/i;i){if(t%i 0){int counts 0;while(t % i 0){t/i;counts;}cout << i <<" "<< counts<<endl;}}if(t >…

CUDA Error: the provided PTX was compiled with an unsupported toolchain

CUDA程序编译时生成的PTX代码与系统上的CUDA驱动版本不兼容 CUDA 编译器版本&#xff1a; CUDA 12.6 (nvcc 编译器版本) CUDA 驱动版本&#xff1a; CUDA 12.3 (nvidia-smi 驱动版本) 解决方法&#xff1a; 驱动版本下载参考&#xff1a;Your connected workspace for wiki…

计算机组成原理实验(7) 堆指令部件模块实验

实验七 堆指令部件模块实验 一、实验目的 1、掌握指令部件的组成方式。 2、熟悉指令寄存器的打入操作&#xff0c;PC计数器的设置和加1操作&#xff0c;理解跳转指令的实现过程。 二、实验要求 按照实验步骤完成实验项目&#xff0c;掌握数据打入指令寄存器IR1、PC计数器的…

2022 年 6 月大学英语四级考试真题(第 2 套)——阅读版——仔细阅读题

&#x1f3e0;个人主页&#xff1a;fo安方的博客✨ &#x1f482;个人简历&#xff1a;大家好&#xff0c;我是fo安方&#xff0c;目前中南大学MBA在读&#xff0c;也考取过HCIE Cloud Computing、CCIE Security、PMP、CISP、RHCE、CCNP RS、PEST 3等证书。&#x1f433; &…

磁盘文件系统

磁盘文件系统 一、磁盘结构1.1 认识一下基础的硬件设备以及真实的机房环境1.2 磁盘物理结构与存储结构1、磁盘物理结构2、磁盘的存储结构3、CHS地址定位4、磁盘的逻辑结构&#xff08;LBA&#xff09;5 磁盘真实过程5 CHS && LBA地址 二、理解分区、格式化1 引⼊"…

基于LangChain 实现 Advanced RAG-后检索优化(下)-上下文压缩与过滤

摘要 Advanced RAG 的后检索优化&#xff0c;是指在检索环节完成后、最终响应生成前&#xff0c;通过一系列策略与技术对检索结果进行深度处理&#xff0c;旨在显著提升生成内容的相关性与质量。在这些优化手段中&#xff0c;上文压缩与过滤技术是提升检索结果质量的重要手段。…

为什么 Vite 速度比 Webpack 快?

一、webpack会先进行编译&#xff0c;再运行&#xff0c;vite会直接启动&#xff0c;再按需编译文件。 首先看两张图&#xff0c;可以清晰的看到&#xff0c;上面的图是webpack编译过的&#xff0c;而下面的图是vite直接使用工程内文件。 二、区别于Webpack先打包的方式&am…