(pytorch-深度学习系列)使用Pytorch实现小型卷积神经网络网络

卷积层

卷积神经网络中每层卷积层(Convolutional layer)由若干卷积单元组成,每个卷积单元的参数都是通过反向传播算法最佳化得到的。卷积运算的目的是提取输入的不同特征,第一层卷积层可能只能提取一些低级的特征如边缘、线条和角等层级,更多层的网路能从低级特征中迭代提取更复杂的特征。
·
pytorch的卷积层:

class torch.nn.Conv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

一维卷积层,输入的尺度是(N, C_in,L),输出尺度( N,C_out,L_out)的计算方式:

out(N_i, C_{out_j})=bias(C {out_j})+\sum^{C{in}-1}{k=0}weight(C{out_j},k)\bigotimes input(N_i,k)
bigotimes: 表示相关系数计算
stride: 控制相关系数的计算步长
dilation: 用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)
groups: 控制输入和输出之间的连接, group=1,输出是所有的输入的卷积;group=2,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。

参数说明如下:

Parameters:in_channels(int) – 输入信号的通道
out_channels(int) – 卷积产生的通道
kerner_size(int or tuple) - 卷积核的尺寸
stride(int or tuple, optional) - 卷积步长
padding (int or tuple, optional)- 输入的每一条边补充0的层数
dilation(int or tuple, `optional``) – 卷积核元素之间的间距
groups(int, optional) – 从输入通道到输出通道的阻塞连接数
bias(bool, optional) - 如果bias=True,添加偏置

举例:

m = nn.Conv1d(16, 33, 3, stride=2)
input = Variable(torch.randn(20, 16, 50))
output = m(input)
print(output.size())
#torch.Size([20, 33, 24])

二维卷积层:

class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

例子:

>>> # With square kernels and equal stride
>>> m = nn.Conv2d(16, 33, 3, stride=2)
>>> # non-square kernels and unequal stride and with padding
>>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
>>> # non-square kernels and unequal stride and with padding and dilation
>>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
>>> input = autograd.Variable(torch.randn(20, 16, 50, 100))
>>> output = m(input)

池化层

class torch.nn.MaxPool1d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)

对于输入信号的输入通道,提供1维最大池化(max pooling)操作

参数:kernel_size(int or tuple) - max pooling的窗口大小
stride(int or tuple, optional) - max pooling的窗口移动的步长。默认值是kernel_size
padding(int or tuple, optional) - 输入的每一条边补充0的层数
dilation(int or tuple, optional) – 一个控制窗口中元素步幅的参数
return_indices - 如果等于True,会返回输出最大值的序号,对于上采样操作会有帮助
ceil_mode - 如果等于True,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作

例子:

>>> # pool of size=3, stride=2
>>> m = nn.MaxPool1d(3, stride=2)
>>> input = autograd.Variable(torch.randn(20, 16, 50))
>>> output = m(input)

全连接层

class torch.nn.Linear(in_features, out_features, bias=True)
参数:
in_features - 每个输入样本的大小
out_features - 每个输出样本的大小
bias - 若设置为False,这层不会学习偏置。默认值:True

卷积神经网络

卷积神经网络(Convolutional Neural Network,CNN)是一种前馈神经网络,它的人工神经元可以响应一部分覆盖范围内的周围单元,对于大型图像处理有出色表现。


pytorch实现ConvNet(注释详解)

import torch
from torch.autograd import Variable
#torch.autograd提供了类和函数用来对任意标量函数进行求导。
import torch.nn as nn
import torch.nn.functional as F
class MNISTConvNet(nn.Module):def __init__(self):super(MNISTConvNet, self).__init__()'''
这是对继承自父类的属性进行初始化。而且是用父类的初始化方法来初始化继承的属性。
也就是说,子类继承了父类的所有属性和方法,父类属性自然会用父类方法来进行初始化。'''
#定义网络结构self.conv1 = nn.Conv2d(1, 10, 5)self.pool1 = nn.MaxPool2d(2, 2)self.conv2 = nn.Conv2d(10, 20, 5)self.pool2 = nn.MaxPool2d(2, 2)self.fc1 = nn.Linear(320, 50)self.fc2 = nn.Linear(50, 10)def forward(self, input):x = self.pool1(F.relu(self.conv1(input)))x = self.pool2(F.relu(self.conv2(x))).view(320)x = self.fc1(x)x = self.fc2(x)return xnet = MNISTConvNet()
print(net)
input = Variable(torch.randn(1, 1, 28, 28))
out = net(input)
print(out.size())

pytorch卷积层与池化层输出的尺寸的计算公式详解

要设计卷积神经网络的结构,必须匹配层与层之间的输入与输出的尺寸,这就需要较好的计算输出尺寸
我在这里详细讲了如何计算尺寸,请浏览


torch.nn.functional详解

· Convolution 函数

torch.nn.functional.conv1d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1)

对几个输入平面组成的输入信号应用1D卷积。

参数: 
-  -input – 输入张量的形状 (minibatch x in_channels x iW)
-  - weight – 过滤器的形状 (out_channels, in_channels, kW) 
- - bias – 可选偏置的形状 (out_channels) 
- - stride – 卷积核的步长,默认为1

例子:

>>> filters = autograd.Variable(torch.randn(33, 16, 3))
>>> inputs = autograd.Variable(torch.randn(20, 16, 50))
>>> F.conv1d(inputs, filters)

· Pooling 函数

torch.nn.functional.avg_pool1d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True)

对由几个输入平面组成的输入信号进行一维平均池化。

参数: 
- kernel_size – 窗口的大小 
- - stride – 窗口的步长。默认值为kernel_size 
- - padding – 在两边添加隐式零填充 
- - ceil_mode – 当为True时,将使用ceil代替floor来计算输出形状 
- - count_include_pad – 当为True时,这将在平均计算时包括补零

例子:

>>> # pool of square window of size=3, stride=2
>>> input = Variable(torch.Tensor([[[1,2,3,4,5,6,7]]]))
>>> F.avg_pool1d(input, kernel_size=3, stride=2)
Variable containing:
(0 ,.,.) =2  4  6
[torch.FloatTensor of size 1x1x3]

· 非线性激活函数

torch.nn.functional.relu(input, inplace=False)

· Normalization 函数

torch.nn.functional.batch_norm(input, running_mean, running_var, weight=None, bias=None, training=False, momentum=0.1, eps=1e-05)

· 线性函数

torch.nn.functional.linear(input, weight, bias=None)

· Dropout 函数

torch.nn.functional.dropout(input, p=0.5, training=False, inplace=False)

· 距离函数(Distance functions)

torch.nn.functional.pairwise_distance(x1, x2, p=2, eps=1e-06)

计算向量v1、v2之间的距离

x1:第一个输入的张量
x2:第二个输入的张量
p:矩阵范数的维度。默认值是2,即二范数。

例子:

>>> input1 = autograd.Variable(torch.randn(100, 128))
>>> input2 = autograd.Variable(torch.randn(100, 128))
>>> output = F.pairwise_distance(input1, input2, p=2)
>>> output.backward()

· 损失函数(Loss functions)

torch.nn.functional.nll_loss(input, target, weight=None, size_average=True)

负的log likelihood损失函数.

参数:- input - (N,C) C 是类别的个数 - - target - (N) 其大小是 0 <= targets[i] <= C-1 - - weight (Variable, optional) – 一个可手动指定每个类别的权重。如果给定的话,必须是大小为nclasses的Variable - - size_average (bool, optional) – 默认情况下,是mini-batchloss的平均值,然而,如果size_average=False,则是mini-batchloss的总和。

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

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

相关文章

RuntimeError: size mismatch, m1: [80 x 4], m2: [320 x 50] at ..\aten\src\TH/generic/THTensorMath.cpp

RuntimeError: size mismatch, m1: [80 x 4], m2: [320 x 50] at …\aten\src\TH/generic/THTensorMath.cpp:41 使用pytorch进行深度学习的训练会出现这种问题&#xff0c;原因是fc全连接层的输入维度问题&#xff0c;由于输入是二维的数据&#xff0c;很多时候在输入全连接层…

idea创建springboot项目,一直在reading pom.xml

problem&#xff1a;遇到的问题 idea创建springboot项目&#xff0c;一直在reading pom.xml 解决方法有三种&#xff1a; &#xff08;1&#xff09;修改windows配置文件 c;\windows\System32\drivers\etc\hosts将12.0.0.1 localhost前的注释符号#去掉 &#xff08;2&#x…

springboot 项目实战 基本框架搭建(IDEA)

springboot 项目实战 基本框架搭建&#xff08;IDEA&#xff09; IDEA下载 我使用的是破解的专业版IDEA&#xff0c;使用权一直到2089年&#xff1a; 下载IDEA: 下载processional版本&#xff0c;然后百度搜索激活码即可概率激活&#xff0c;如果你不成功就多找几个激活码 配…

使用IDEA 连接mysql数据库,执行sql指令

使用IDEA 连接mysql数据库&#xff0c;执行sql指令 1 配置项目的SQL依赖 首先参考这篇博文&#xff0c;创建springboot的基本框架 在创建项目的过程中&#xff0c;需要选择SQL相关的依赖&#xff0c;如下&#xff1a; SQL勾选&#xff1a;MySQL Driver&#xff0c;JDBC API …

thymeleaf There was an unexpected error (type=Internal Server Error, status=500).

thymeleaf There was an unexpected error (typeInternal Server Error, status500). 使用thymeleaf依赖&#xff0c;无法访问html文件&#xff0c;解决方法有以下几种可能&#xff1a; 1. 未加载thymeleaf依赖&#xff0c;打开pom.xml&#xff0c;加入依赖&#xff1a; <…

org.attoparser.ParseException: Could not parse as expression: “

Caused by: org.attoparser.ParseException: Could not parse as expression: " {field: ‘id’, title: ‘ID’, fixed: ‘left’, unresize: true, sort: true} , {field: ‘number’, title: ‘学号’, edit: ‘number’, sort: true} , {field: ‘name’, title: ‘姓…

windows10 计算文件的HASH(SHA256\MD5等)

windows10 计算文件的HASH&#xff08;SHA256\MD5等&#xff09; certutil -hashfile .\文件名 带后缀 SHA256可选哈希算法参数&#xff1a;MD2 MD4 MD5 SHA1 SHA256 SHA384 SHA512

ubuntu给pip换源,给conda换源

ubuntu 给pip换源&#xff0c;给conda换源 //修改 ~/.pip/pip.conf (没有就创建一个)&#xff0c; 内容如下&#xff1a; [global] timeout 6000 index-url https://pypi.tuna.tsinghua.edu.cn/simple trusted-host pypi.tuna.tsinghua.edu.cn //给conda换源 conda config …

ubuntu怎么在jupyter notebook中引入anaconda虚拟环境

ubuntu怎么在jupyter notebook中引入anaconda虚拟环境 ~坑&#xff1a; 先activate visaul envirument 再打开jupyter notebook 是不行的 conda install nb_conda 也是不行的 正确做法&#xff1a; conda create -n your_env_name pythonX.X #创建环境 //先activate pytorch …

傅里叶变换原理解析

傅里叶变换原理解析 震动频率&#xff1a;节拍数/秒 矢量旋转频率&#xff1a;圈/秒傅里叶频域就是&#xff1a;音频信号波形以不同的频率旋转形成的图形的质心的坐标变化&#xff0c;即&#xff08;frequency, (x,y)&#xff09; &#xff08;其中实数为x轴坐标&#xff0c;虚…

(pytorch-深度学习系列)pytorch数据操作

pytorch数据操作 基本数据操作&#xff0c;都详细注释了&#xff0c;如下&#xff1a; import torch#5x3的未初始化的Tensor x torch.empty(5, 3) print("5x3的未初始化的Tensor:") print(x) print("******************************")#5x3的随机初始化的…

(pytorch-深度学习系列)pytorch中backwards()函数对梯度的操作

backwards()函数对梯度的操作 对于一个新的tensor来说&#xff0c;梯度是空的&#xff1b;但当对这个tensor进行运算操作后&#xff0c;他就会拥有一个梯度&#xff1a; x torch.ones(2, 2, requires_gradTrue) print(x) print(x.grad_fn)y x 2 print(y) print(y.grad_fn)…

(pytorch-深度学习系列)pytorch实现线性回归

pytorch实现线性回归 1. 实现线性回归前的准备 线性回归输出是一个连续值&#xff0c;因此适用于回归问题。回归问题在实际中很常见&#xff0c;如预测房屋价格、气温、销售额等连续值的问题。 与回归问题不同&#xff0c;分类问题中模型的最终输出是一个离散值。我们所说的图…

(pytorch-深度学习系列)pytorch线性回归的便捷实现

pytorch线性回归的便捷实现 继上一篇blog&#xff0c;使用更加简洁的方法实现线性回归 生成数据集&#xff1a; num_inputs 2 num_examples 1000 true_w [2, -3.4] true_b 4.2 features torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtypetorch.f…

(pytorch-深度学习系列)pytorch实现对Fashion-MNIST数据集进行图像分类

pytorch实现对Fashion-MNIST数据集进行图像分类 导入所需模块&#xff1a; import torch import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import time import sys对数据集的操作&#xff08;读取数据集&#xff09;&#…

(pytorch-深度学习系列)使用softmax回归实现对Fashion-MNIST数据集进行分类-学习笔记

使用softmax回归实现对Fashion-MNIST数据集进行分类 import torch from torch import nn from torch.nn import init import numpy as np import sys读取数据集&#xff1a; mnist_train torchvision.datasets.FashionMNIST(root~/Datasets/FashionMNIST, trainTrue, downlo…

(pytorch-深度学习系列)pytorch实现多层感知机(手动定义模型)对Fashion-MNIST数据集进行分类-学习笔记

pytorch实现多层感知机对Fashion-MNIST数据集进行分类&#xff08;手动定义模型&#xff09; 多层感知机&#xff1a; 多层感知机在单层神经网络的基础上引入了一到多个隐藏层&#xff08;hidden layer&#xff09;。隐藏层位于输入层和输出层之间。 输入和输出个数分别为4和…

(pytorch-深度学习系列)pytorch实现多层感知机(自动定义模型)对Fashion-MNIST数据集进行分类-学习笔记

pytorch实现多层感知机&#xff08;自动定义模型&#xff09;对Fashion-MNIST数据集进行分类 导入模块&#xff1a; import torch from torch import nn from torch.nn import init import numpy as np定义数据集&#xff1a; class FlattenLayer(nn.Module): # 定义一个ten…

(pytorch-深度学习系列)pytorch避免过拟合-权重衰减的实现-学习笔记

pytorch避免过拟合-权重衰减的实现 首先学习基本的概念背景 L0范数是指向量中非0的元素的个数&#xff1b;(L0范数难优化求解) L1范数是指向量中各个元素绝对值之和&#xff1b; L2范数是指向量各元素的平方和然后求平方根。 权重衰减等价于 L2范数正则化&#xff08;regular…

(pytorch-深度学习系列)pytorch避免过拟合-dropout丢弃法的实现-学习笔记

pytorch避免过拟合-dropout丢弃法的实现 对于一个单隐藏层的多层感知机&#xff0c;其中输入个数为4&#xff0c;隐藏单元个数为5&#xff0c;且隐藏单元hih_ihi​&#xff08;i1,…,5i1, \ldots, 5i1,…,5&#xff09;的计算表达式为&#xff1a; hiϕ(x1w1ix2w2ix3w3ix4w4ib…