卷积神经网络、比较MLPS和CNNS、滤波器、CNN各层的作用、在Pytorch可视化CNN

卷积神经网络、比较MLPS和CNNS、滤波器、CNN各层的作用、在Pytorch可视化CNN本文深入探讨了卷积神经网络 CNN 的基础知识 包括与多层感知器 MLP 的比较 计算机如何解析图像 以及构建和可视化 CNN 层

大家好,欢迎来到IT知识分享网。

1.33.卷积神经网络

卷积神经网络(CNN)是一种人工神经网络结构,因为利用卷积神经网络在图像语音识别方面能够给出更优预测结果,这一技术也被广泛的传播可应用。卷积神经网络最常被应用的方面是计算的图像识别,不过因为不断的创新,也被应用在视频分析,自然语言处理,药物发现,等等。

应用案例:
智能手机可以识别相机中的面部。
使用Google图片搜索特定照片的能力。
从条形码或书籍中扫描文本。


1.33.1.卷积 和 神经网络

什么是卷积神经网络?我们可以把这个词拆开成为“卷积”和“神经网络”。

卷积也就是说神经网络不再是对每个像素的输入信息做处理了,而是图片上每一小块像素区域进行处理,这种做法加强了图片信息的连续性。使得神经网络能看到图形,而非一个点。这种做法同时也加深了神经网络对图像的理解。每次收集的时候都只是收集一小块像素区域,然后把收集来的信息进行整理,这时候整理出来的信息有了一些实际上的呈现。然后以同样的步骤,用类似的批量过滤器扫过产生的这些边缘信息,神经网络从这些边缘信息里面总结出更高层的信息结构。经过几次过滤,最后我们把这些信息套入几层普通的全连接神经层进行分类,这样就能得到输入的图片能被分为哪一类的结果了。

神经网络的基本模型由组织在不同层中的神经元组成。每个神经网络都有一个输入层和一个输出层,并根据问题的复杂性增加了许多隐藏层。一旦数据通过这些层,神经元就会学习并识别模式。神经网络的这种表示称为模型。训练完模型后,我们要求网络根据测试数据进行预测。

卷积神经网络(CNN)是一种特殊类型的神经网络,在图像上表现特别出色。卷积神经网络由Yan LeCun在1998年提出,可以识别给定输入图像中存在的数字。使用CNN的其他应用程序包括语音识别,图像分割和文本处理。在卷积神经网络之前,多层感知器(MLP)用于构建图像分类器。

图像分类是指从多波段光栅图像中提取信息类别的任务。多层感知器需要更多的时间和空间来在图片中查找信息,因为每个输入功能都需要与下一层的每个神经元相连。CNN通过使用称为本地连接的概念取代了MLP,该概念涉及将每个神经元仅连接到到输入体积的本地区域。通过允许网络的不同部分专门处理高级功能(如纹理或重复图案),可以最大程度地减少参数数量。

1.33.1.1.比较MLPS和CNNS

卷积层不使用全连接层,而是使用稀疏连接层,也就是说,它们接受矩阵作为输入,这比MLP更具优势。输入特征连接到本地编码节点。在MLP中,每次节点负责获得对整个画面的理解。在CNN中,我们将图像分解为区域(像素的局部区域)。每个隐藏节点都必须输出层报告,在输出层,输出层将接收到的数据组合起来以找到模式

在我们了解CNN如何在图片中找到信息之前,我们需要了解如何提取特征。卷积神经网络使用不同的图层,每一层将保存图像中的特征。例如,考虑一张狗的照片。每当网络需要对狗进行分类时,它都应该识别所有特征-眼睛,耳朵,舌头,腿等。使用过滤器和核,这些特征被分解并在网络的局部层中识别出来。

1.33.1.2.计算机如何看图像?

与人类通过用眼睛了解图像的计算机不同,计算机使用一组介于0到255之间的像素值来了解图片。计算机查看这些像素值并理解它们。乍一看,它不知道物体或颜色,只识别像素值,这就是图像用于计算机的全部。

在分析像素值之后,计算机会慢慢开始了解图像是灰度还是彩色。它知道差异,因为灰度图像只有一个通道,因为每个像素代表一种颜色的强度。零表示黑色,255表示白色,黑色和白色的其他变化形式,即介于两者之间的灰色。另一方面,彩色图像具有三个通道-红色,绿色和蓝色。它们代表三种颜色(3D矩阵)的强度,并且当值同时变化时,它会产生大量的颜色!确定颜色属性后,计算机会识别图像中对象的曲线和轮廓。

import torch import numpy as np from torchvision import datasets import torchvision.transforms as transforms num_workers = 0 batch_size = 20 transform = transforms.ToTensor() train_data = datasets.MNIST(root='data', train=True, download=True, transform=transform) test_data = datasets.MNIST(root='data', train=False, download=True, transform=transform) train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, num_workers=num_workers) test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, num_workers=num_workers) import matplotlib.pyplot as plt %matplotlib inline dataiter = iter(train_loader) images, labels = dataiter.next() images = images.numpy() fig = plt.figure(figsize=(25, 4)) for image in np.arange(20): ax = fig.add_subplot(2, 20/2, image+1, xticks=[], yticks=[]) ax.imshow(np.squeeze(images[image]), cmap='gray') ax.set_title(str(labels[image].item())) 

在这里插入图片描述

img = np.squeeze(images[7]) fig = plt.figure(figsize = (12,12)) ax = fig.add_subplot(111) ax.imshow(img, cmap='gray') width, height = img.shape thresh = img.max()/2.5 for x in range(width): for y in range(height): val = round(img[x][y],2) if img[x][y] !=0 else 0 ax.annotate(str(val), xy=(y,x), horizontalalignment='center', verticalalignment='center', color='white' if img[x][y]<thresh else 'black') 

在这里插入图片描述

这就是将数字“ 3”分解为像素的方式。从一组手写数字中,随机选择“ 3”,其中显示像素值。在这里,ToTensor()归一化实际像素值(0–255)并将其限制为0到1。为什么?因为,这使得以后的部分中的计算更加容易,无论是在解释图像还是找到图像中存在的通用模式。

import cv2 sobel = np.array([[ -1, -2, -1], [ 0, 0, 0], [ 1, 2, 1]]) img = np.squeeze(images[7]) filtered_image = cv2.filter2D(img, -1, sobel) plt.imshow(filtered_image, cmap='gray') 

在这里插入图片描述

fig = plt.figure(figsize = (12,12)) ax = fig.add_subplot(111) ax.imshow(filtered_image, cmap='gray') width, height = filtered_image.shape thresh = filtered_image.max()/2.5 for x in range(width): for y in range(height): val = round(img[x][y],2) if filtered_image[x][y] !=0 else 0 ax.annotate(str(val), xy=(y,x), color='white' if filtered_image[x][y]<thresh else 'black') 

在这里插入图片描述

filter4x4 = filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) img = np.squeeze(images[7]) filtered_image = cv2.filter2D(img, -1, filter4x4) plt.imshow(filtered_image, cmap='gray') 

在这里插入图片描述

fig = plt.figure(figsize = (12,12)) ax = fig.add_subplot(111) ax.imshow(filtered_image, cmap='gray') width, height = filtered_image.shape thresh = filtered_image.max()/2.5 for x in range(width): for y in range(height): val = round(img[x][y],2) if filtered_image[x][y] !=0 else 0 ax.annotate(str(val), xy=(y,x), color='white' if filtered_image[x][y]<thresh else 'black') 

在这里插入图片描述

1.33.1.3.建立自己的滤波器

在卷积神经网络中,图像中的像素信息被过滤。为什么我们完全需要滤波器?就像孩子一样,计算机需要经历了解图像的学习过程。值得庆幸的是,这不需要几年的时间!计算机通过从头开始学习,然后逐步进行到整体来完成此任务。因此,网络必须首先知道图像中的所有原始部分,例如边缘,轮廓和其他低层特征。一旦检测到这些,计算机便可以处理更复杂的功能。简而言之,必须先提取低级功能,然后再提取中级功能,然后再提取高级功能。滤波器提供了一种提取信息的方法。

可以使用特定的滤波器提取低级特征,该滤波器也是类似于图像的一组像素值。可以理解为连接CNN中各层的权重。将这些权重或滤波器与输入相乘,得出中间图像,中间图像表示计算机对图像的部分理解。然后,这些副产品再与更多的滤波器相乘以扩展视图。该过程以及对功能的检测一直持续到计算机了解其外观为止。

您可以根据自己的需要使用很多滤波器。您可能需要模糊,锐化,加深,进行边缘检测等-都是滤波器。

让我们看一些代码片段,以了解滤波器的功能(以下代码可以在github: https://github.com/vihar/visualising-cnns/blob/master/02_Writing%20Your%20Own%20Filter.ipynb)。

import matplotlib.pyplot as plt import matplotlib.image as mpimg import cv2 import numpy as np %matplotlib inline image = mpimg.imread('dog.jpg') plt.imshow(image) 

在这里插入图片描述

gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) plt.imshow(gray, cmap='gray') 

在这里插入图片描述

custom_2x2 = np.array([[1,0], [1,0]]) filtered_image = cv2.filter2D(gray, -1, custom_2x2) plt.imshow(filtered_image, cmap='gray') 

在这里插入图片描述

sobel_y = np.array([[ -1, -2, -1], [ 0, 0, 0], [ 1, 2, 1]])  TODO: Create and apply a Sobel x operator # Filter the image using filter2D, which has inputs: (grayscale image, bit-depth, kernel)  filtered_image = cv2.filter2D(gray, -1, sobel_y) plt.imshow(filtered_image, cmap='gray') 

在这里插入图片描述
这是应用滤波器后图像的外观。这种情况下,我们使用了Sobel滤波器。

1.33.2.完整的卷积神经网络(CNNS)

卷积神经网络包含卷积层(Convolution)、非线性激活层(常用ReLU层)、池化层(pooling)、全连接层(Full-Connected)和Softmax层。卷积神经网络的基本结构如下图所示。
在这里插入图片描述

1.33.2.1.CNN各层的作用

卷积层—卷积层(CONV)使用过滤器执行卷积操作,同时扫描输入图像的尺寸。它的超参数包括滤波器尺寸,通常设置为2 * 2, 3 * 3, 4 * 4, 5 * 5(但并不仅仅限于这些尺寸),步长(S)。输出结果(O)被称为特征图或激活图,包含了输入层和滤波器计算出的所有特征。下图描述了应用卷积时产生的特殊图:
在这里插入图片描述
卷积操作,左侧图像是6 * 6的大小,滤波器尺寸大小为3 * 3,步长为1,经过卷积操作之后,变成了4 * 4的大小。

池化层–池化层(POOL)用于特征的降采样,通常在卷积层之后应用。常见的两种池化操作为最大池化和平均池化,分别求取特征的最大值和平均值。下图描述了池化的基本原理:
在这里插入图片描述
最大池化
在这里插入图片描述
平均池化



全连接层—全连接层(FC)作用于一个扁平的输入,其中每个输入都连接到所有的神经元。全连接层通常用于网络的末端,将隐藏层连接到输出层,这有助于优化类分数。
在这里插入图片描述
全连接层

1.33.2.2.在Pytorch可视化CNN

我们对CNN的函数有了更好的了解,现在让我们使用Facebook的PyTorch框架来实现它。

步骤1:加载输入图像。我们将使用NumPy和OpenCV。(在GitHub上可找到代码: https://github.com/vihar/visualising-cnns/blob/master/02_Writing%20Your%20Own%20Filter.ipynb)

import matplotlib.pyplot as plt import matplotlib.image as mpimg import cv2 import numpy as np %matplotlib inline img_path = 'dog.jpg' bgr_img = cv2.imread(img_path) gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # Normalise gray_img = gray_img.astype("float32")/255 plt.imshow(gray_img, cmap='gray') plt.show() 

在这里插入图片描述

步骤2:可视化滤波器,以更好地了解我们将使用的滤波器。(在GitHub上可找到代码:https://github.com/vihar/visualising-cnns/blob/master/02_Writing%20Your%20Own%20Filter.ipynb)

import numpy as np filter_vals = np.array([ [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1] ]) print('Filter shape: ', filter_vals.shape) # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) fig = plt.figure(figsize=(10, 5)) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) width, height = filters[i].shape for x in range(width): for y in range(height): ax.annotate(str(filters[i][x][y]), xy=(y,x), color='white' if filters[i][x][y]<0 else 'black') 

在这里插入图片描述
步骤3:定义卷积神经网络。该CNN具有卷积层和最大池化层,并且权重使用上述滤波器进行初始化:(GitHub上可找到代码:https://github.com/vihar/visualising-cnns/blob/master/03_CNN%20Layers%20Visualisations%20.ipynb)

import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(2, 2) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) 

步骤4:可视化滤波器。快速浏览一下正在使用的滤波器。(在GitHub上可找到代码)

def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1) ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) # plt.imshow(gray_img, cmap='gray') fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) conv_x, activated_layer, pooled_layer = model.forward(gray_img_tensor) 

在这里插入图片描述
滤波器:
在这里插入图片描述
步骤5:跨层滤波器输出。在CONV和POOL层中输出的图像如下所示:


viz_layer(activated_layer) viz_layer(pooled_layer) 

卷积层
在这里插入图片描述
池化层
在这里插入图片描述


免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/109802.html

(0)
上一篇 2026-02-04 16:21
下一篇 2026-02-04 16:33

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信