欢迎访问 生活随笔!

凯发k8官方网

当前位置: 凯发k8官方网 > 人工智能 > 卷积神经网络 >内容正文

卷积神经网络

卷积神经网络、比较mlps和cnns、滤波器、cnn各层的作用、在pytorch可视化cnn -凯发k8官方网

发布时间:2024/9/27 卷积神经网络 16 豆豆
凯发k8官方网 收集整理的这篇文章主要介绍了 卷积神经网络、比较mlps和cnns、滤波器、cnn各层的作用、在pytorch可视化cnn 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1.33.卷积神经网络
1.33.1.卷积 和 神经网络
1.33.1.1.比较mlps和cnns
1.33.1.2.计算机如何看图像?
1.33.1.3.建立自己的滤波器
1.33.2.完整的卷积神经网络(cnns)
1.33.2.1.cnn各层的作用
1.33.2.2.在pytorch可视化cnn

1.33.卷积神经网络

参考文章:
https://blog.csdn.net/kstheme/article/details/99689564
https://blog.csdn.net/zsd0819qwq/article/details/105396364
https://www.cnblogs.com/wangqinze/p/13508801.html

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

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

1.33.1.卷积 和 神经网络

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

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

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

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

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

1.33.1.1.比较mlps和cnns

考虑到mnist数据集,由于输入图像的大小为28x28 = 784,多层感知器输入层的总数将为784。 网络应该能够预测给定输入图像中的数量,这意味着输出可能属于以下范围中的任何一个,范围从0到9(1、2、3、4、5、6、7、8、9 )。 在输出层中,我们返回类别分数,例如,如果给定的输入是具有数字“ 3”的图像,则在输出层中,对应的神经元“ 3”比其他神经元具有更高的类别分数。 我们需要包含多少个隐藏层,每个层中应该包含多少个神经元?这是一个编码mlp的示例:

上面的代码段是使用称为keras的框架实现的(暂时忽略语法)。它告诉我们在第一个隐藏层中有512个神经元,它们连接到形状为784的输入层。该隐藏层之后是一个随机失活层,该层克服了过拟合的问题。0.2表示在第一个隐藏层之后不考虑神经元的可能性为20%。再次,我们在第二个隐藏层中添加了与第一个隐藏层中相同数量的神经元(512),然后添加了另一个随机失活。最后,我们用包含10个类的输出层结束这组层。具有最高值的此类将是模型预测结果。

这是定义所有层之后的网络多层外观。这种多层感知器的一个缺点是全连接的以供网络学习,这需要更多的时间和空间。mlp仅接受向量作为输入。

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

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

1.33.1.2.计算机如何看图像?

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

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

可以使用pytorch在卷积神经网络中探索此过程,以加载数据集并将滤波器应用于图像。下面是代码片段。(在github上可找到此代码)
github地址是:https://github.com/vihar/visualising-cnns/blob/master/01_mnist-image-overview.ipynb (可以在jupyter notebook启动jupyter)

import torch import numpy as npfrom torchvision import datasets import torchvision.transforms as transformsnum_workers = 0 batch_size = 20transform = 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 inlinedataiter = 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, image1, xticks=[], yticks=[])ax.imshow(np.squeeze(images[image]), cmap='gray')ax.set_title(str(labels[image].item()))

现在,让我们看看如何将单个图像输入神经网络。
(在github上可找到此代码: https://github.com/vihar/visualising-cnns/blob/master/01_mnist-image-overview.ipynb)

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 0ax.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 cv2sobel = 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 0ax.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 0ax.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 your own filter.ipynb)。

import matplotlib.pyplot as plt import matplotlib.image as mpimgimport cv2 import numpy as np%matplotlib inlineimage = 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)

我们已经知道滤波器是如何从图像中提出特征了,但是为了完成整个卷积神经网络我们需要理解用来设计cnn的各层。卷积神经网络中的各层分别叫做:
卷积层
池化层
全连接层

卷积神经网络包含卷积层(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 your own filter.ipynb)

import matplotlib.pyplot as plt import matplotlib.image as mpimgimport 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 your own filter.ipynb)

import numpy as npfilter_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, i1, xticks=[], yticks=[])ax.imshow(filters[i], cmap='gray')ax.set_title('filter %s' % str(i1))width, height = filters[i].shapefor 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 layers visualisations .ipynb)

import torch import torch.nn as nn import torch.nn.functional as fclass 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 filtersk_height, k_width = weight.shape[2:]# assumes there are 4 grayscale filtersself.conv = nn.conv2d(1, 4, kernel_size=(k_height, k_width), bias=false)self.conv.weight = torch.nn.parameter(weight)# define a pooling layerself.pool = nn.maxpool2d(2, 2)def forward(self, x):# calculates the output of a convolutional layer# pre- and post-activationconv_x = self.conv(x)activated_x = f.relu(conv_x)# applies pooling layerpooled_x = self.pool(activated_x)# returns all layersreturn 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, i1)ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray')ax.set_title('output %s' % str(i1))# 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, i1, xticks=[], yticks=[])ax.imshow(filters[i], cmap='gray')ax.set_title('filter %s' % str(i1))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)

卷积层

池化层

总结

以上是凯发k8官方网为你收集整理的卷积神经网络、比较mlps和cnns、滤波器、cnn各层的作用、在pytorch可视化cnn的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得凯发k8官方网网站内容还不错,欢迎将凯发k8官方网推荐给好友。

  • 上一篇:
  • 下一篇:
网站地图