七、torch.nn

一、神经网络模块

进入到PyTorch的torch.nnAPI学习页面
PyTorch提供了很多的神经网络方面的模块,NN就是Neural Networks的简称
在这里插入图片描述

二、Containers

torch.nn下的Containers
一共有六个模块,最常用的就是Module模块,看解释可以知道,Module是为所有的神经网络所提供的基础类
在这里插入图片描述

Moduel

torch.nn.Containers下的Moduel
自己所搭建的神经网络必须继承这个Moduel类,其也相当于一个模板
在这里插入图片描述
模仿一下,创建一个神经网络模型,y = 5 + x
神经网络中的参数都是tensor类型,这点需要注意

import torch
from torch import nnclass Beyond(nn.Module):def __init__(self):super().__init__()def forward(self,input):output = input + 5return outputbeyond = Beyond()
x = torch.tensor(5.0)
out = beyond(x)
print(out)#tensor(10.)

三、Convolution Layers

torch.nn下的Convolution Layers卷积层
常用的就是nn.Conv2d二维卷积,卷积核是二维
在这里插入图片描述

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

TORCH.NN.FUNCTIONAL.CONV2D方法使用说明
在这里插入图片描述

参数描述解释
input形状的输入张量
weight权重也就是卷积核
bias偏置
stride卷积核的步幅。可以是单个数字或元组(sH, sW)。默认值:1可以指定两个方向的步长,也可以输入一个参数同时设置两个方向
padding输入两侧的隐式填充也就是加边

卷积操作这里就不再赘述了,与kernel对应相乘再相加运算而已

import torch
import torch.nn.functionalinput = torch.tensor([[1,2,3,4,5],[5,4,3,2,1],[1,2,3,4,5],[5,4,3,2,1],[1,2,3,4,5]])kernel = torch.tensor([[1,2,3],[3,2,1],[1,2,3]])
print(input.shape)#torch.Size([5, 5])
print(kernel.shape)#torch.Size([3, 3])
#目前input和weight仅为(H,W),不符合conv2d的输入要求#由官网看到的input为四维(minibatch,in_channels,iH,iW)数据,故通过reshape进行转变
#weight也就是kernel是要求四维数据信息
input_re = torch.reshape(input,(1,1,5,5))
kernel_re = torch.reshape(kernel,(1,1,3,3,))
print(input_re.shape)#torch.Size([1, 1, 5, 5])
print(kernel_re.shape)#torch.Size([1, 1, 3, 3])out_1 = torch.nn.functional.conv2d(input_re,kernel_re,stride=1)
print(out_1)
"""
tensor([[[[54, 60, 66],[54, 48, 42],[54, 60, 66]]]])
"""out_2 = torch.nn.functional.conv2d(input_re,kernel_re,stride=2)
print(out_2)
"""
tensor([[[[54, 66],[54, 66]]]])
"""out_3 = torch.nn.functional.conv2d(input_re,kernel_re,stride=1,padding=1)
print(out_3)
"""
tensor([[[[26, 32, 32, 32, 26],[30, 54, 60, 66, 36],[48, 54, 48, 42, 30],[30, 54, 60, 66, 36],[26, 32, 32, 32, 26]]]])
"""

五、torch.nn.ReLU(inplace=False)

ⅠReLU函数介绍

torch.nn.ReLU(inplace=False)官网提供的API
其中inplace表示是否在对原始数据进行替换

由函数图可以看出,负数通过ReLU之后会变成0,正数则不发生变化
在这里插入图片描述
例如:input = -1,若inplace = True,表示对原始输入数据进行替换,当通过ReLU函数(负数输出均为0)之后,input = 0
若inplace = False(默认),表示不对原始输入数据进行替换,则需要通过另一个变量(例如output)来对ReLU函数的结果进行接收存储,通过ReLU函数之后,output = 0,input = -1

ⅡReLU函数使用

创建一个二维tensor数据,通过reshape转换成(batch_size,channel,H,W)类型数据格式
传入仅含有ReLU的神经网络中,运行结果可以看出,负数都变成了0,正数均保持不变

import torch
from torch import nninput = torch.tensor([[1,-0.7],[-0.8,2]])input = torch.reshape(input,(-1,1,2,2))print(input)
"""
tensor([[[[ 1.0000, -0.7000],[-0.8000,  2.0000]]]])
"""class Beyond(nn.Module):def __init__(self):super(Beyond,self).__init__()self.relu_1 = torch.nn.ReLU()def forward(self,input):output = self.relu_1(input)return  outputbeyond = Beyond()
output = beyond(input)
print(output)
"""
tensor([[[[1., 0.],[0., 2.]]]])
"""

ⅢReLU训练CIFAR-10数据集上传至tensorboard

import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriterdataset_test = torchvision.datasets.CIFAR10("CIFAR_10",train=False,transform=torchvision.transforms.ToTensor(),download=True)dataloader = DataLoader(dataset_test,batch_size=64)class Beyond(nn.Module):def __init__(self):super(Beyond,self).__init__()self.relu_1 = torch.nn.ReLU()def forward(self,input):output = self.relu_1(input)return outputwriter = SummaryWriter("y_log")beyond = Beyond()
i=0
for data in dataloader:imgs,targets = datawriter.add_images("input_ReLU",imgs,i)output = beyond(imgs)writer.add_images("output_ReLU",output,i)i = i + 1writer.close()

在Terminal下运行tensorboard --logdir=y_log --port=9999,logdir为打开事件文件的路径,port为指定端口打开;
通过指定端口9999进行打开tensorboard,若不设置port参数,默认通过6006端口进行打开。
在这里插入图片描述
点击该链接或者复制链接到浏览器打开即可
在这里插入图片描述

六、torch.nn.Sigmoid

ⅠSigmoid函数介绍

torch.nn.Sigmoid
在这里插入图片描述

ⅡSigmoid函数使用

创建一个二维tensor数据,通过reshape转换成(batch_size,channel,H,W)类型数据格式
传入仅含有Sigmoid的神经网络中,代入Sigmodi公式即可得到相应返回结果

import torch
from torch import nninput = torch.tensor([[1,-0.7],[-0.8,2]])input = torch.reshape(input,(-1,1,2,2))print(input)
"""
tensor([[[[ 1.0000, -0.7000],[-0.8000,  2.0000]]]])
"""class Beyond(nn.Module):def __init__(self):super(Beyond,self).__init__()self.sigmoid_1 = torch.nn.Sigmoid()def forward(self,input):output = self.sigmoid_1(input)return  outputbeyond = Beyond()
output = beyond(input)
print(output)
"""
tensor([[[[0.7311, 0.3318],[0.3100, 0.8808]]]])
"""

ⅢSigmoid训练CIFAR-10数据集上传至tensorboard

import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriterdataset_test = torchvision.datasets.CIFAR10("CIFAR_10",train=False,transform=torchvision.transforms.ToTensor(),download=True)dataloader = DataLoader(dataset_test,batch_size=64)class Beyond(nn.Module):def __init__(self):super(Beyond,self).__init__()self.sigmoid_1 = torch.nn.Sigmoid()def forward(self,input):output = self.sigmoid_1(input)return  outputwriter = SummaryWriter("y_log")beyond = Beyond()
i=0
for data in dataloader:imgs,targets = datawriter.add_images("input_Sigmoid",imgs,i)output = beyond(imgs)writer.add_images("output_Sigmoid",output,i)i = i + 1writer.close()

在Terminal下运行tensorboard --logdir=y_log --port=9999,logdir为打开事件文件的路径,port为指定端口打开;
通过指定端口9999进行打开tensorboard,若不设置port参数,默认通过6006端口进行打开。
在这里插入图片描述

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

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

相关文章

Java多线程初学者指南(8):从线程返回数据的两种方法

本文介绍学习Java多线程中需要学习的从线程返回数据的两种方法。从线程中返回数据和向线程传递数据类似。也可以通过类成员以及回调函数来返回数据。原文链接 从线程中返回数据和向线程传递数据类似。也可以通过类成员以及回调函数来返回数据。但类成员在返回数据和传递数据时有…

【C++进阶】 遵循TDD原则,实现平面向量类(Vec2D)

目录1、明确要实现的类的方法以及成员函数2、假设已经编写Vec2D,根据要求,写出测试代码3、编写平面向量类Vec2D,并进行测试4、完整代码5、最终结果1、明确要实现的类的方法以及成员函数 考虑到效率问题,我们一般将函数的参数设置为引用类型。…

Keilc的中断号计算方法

中断号码 (中断向量-3)/8转载于:https://www.cnblogs.com/yuqilihualuo/p/3423634.html

md5模式 签名_MD的完整形式是什么?

md5模式 签名医师:医学博士/常务董事 (MD: Doctor of Medicine / Managing Director) 1)医学博士:医学博士 (1) MD: Doctor of Medicine) MD is an abbreviation of a Doctor of Medicine degree. In the field of Medicine, it is the main academic de…

八、卷积层

一、Conv2d torch.nn.Conv2d官网文档 torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride1, padding0, dilation1, groups1, biasTrue, padding_modezeros, deviceNone, dtypeNone) 参数解释官网详情说明in_channels输入的通道数,如果是彩色照片通道…

HTMl5结构元素:header

页眉header 页眉将是页面加载的第一个元素&#xff0c;包含了站点的标题、logo、网站导航等。<header> <div class"container_16"> <div class"logo"> <h1><a href"index.html"><strong>Real</st…

【C++grammar】左值、右值和将亡值

目录C03的左值和右值C11的左值和右值将亡值在C03中就有相关的概念 C03的左值和右值 通俗的理解&#xff1a; (1) 能放在等号左边的是lvalue (2) 只能放在等号右边的是rvalue (3) lvalue可以作为rvalue使用 对于第三点可以举个例子&#xff1a; int x ; x 6; //x是左值&#…

scala字符串的拉链操作_在Scala中对字符串进行操作

scala字符串的拉链操作Scala字符串操作 (Scala strings operation) A string is a very important datatype in Scala. This is why there are a lot of operations that can be done on the string object. Since the regular operations like addition, subtraction is not v…

九、池化层

一、Pooling layers Pooling layers官网文档 MaxPool最大池化层下采样 MaxUnpool最大池化层上采样 AvgPool最大池化层平均采样 例如&#xff1a;池化核为(3,3)&#xff0c;输入图像为(5,5)&#xff0c;步长为1&#xff0c;不加边 最大池化就是选出在池化核为单位图像中的最大…

[分享]SharePoint移动设备解决方案

老外写的一个PPT&#xff0c;讲SharePoint在移动领域的应用&#xff0c;2012年最新的&#xff0c;有iPad哟。/Files/zhaojunqi/SharePoint2010andMobileDevices.pdf 转载于:https://www.cnblogs.com/zhaojunqi/archive/2012/04/12/2444712.html

十、非线性激活函数

一、ReLU torch.nn.ReLU(inplaceFalse)官网提供的API 其中inplace表示是否在对原始数据进行替换 由函数图可以看出&#xff0c;负数通过ReLU之后会变成0&#xff0c;正数则不发生变化 例如&#xff1a;input -1&#xff0c;若inplace True&#xff0c;表示对原始输入数据进…

最短公共子序列_最短公共超序列

最短公共子序列Problem statement: 问题陈述&#xff1a; Given two strings, you have to find the shortest common super sequence between them and print the length of the super sequence. 给定两个字符串&#xff0c;您必须找到它们之间最短的公共超级序列&#xff0c…

单调栈 leetcode整理(二)

目录为什么单调栈的时间复杂度是O(n)496. 下一个更大元素 I方法一&#xff1a;暴力方法二:单调栈哈希表739. 每日温度单调栈模版解优化503. 下一个更大元素 II单调栈循环遍历为什么单调栈的时间复杂度是O(n) 尽管for 循环里面还有while 循环&#xff0c;但是里面的while最多执…

Android中引入第三方Jar包的方法(java.lang.NoClassDefFoundError解决办法)

ZZ&#xff1a;http://www.blogjava.net/anchor110/articles/355699.html1、在工程下新建lib文件夹&#xff0c;将需要的第三方包拷贝进来。2、将引用的第三方包&#xff0c;添加进工作的build path。3、&#xff08;关键的一步&#xff09;将lib设为源文件夹。如果不设置&…

QTP自传之web常用对象

随着科技的进步&#xff0c;“下载-安装-运行”这经典的三步曲已离我们远去。web应用的高速发展&#xff0c;改变了我们的思维和生活习惯&#xff0c;同时也使web方面的自动化测试越来越重要。今天&#xff0c;介绍一下我对web对象的识别&#xff0c;为以后的对象库编程打下基础…

leetcode中使用c++需要注意的点以及各类容器的初始化、常用成员函数

目录1、传引用2、vector使用初始化方法常用成员函数3、字符串string初始化方法常用成员函数4、哈希表 unordered_map初始化常用成员函数示例&#xff1a;计数器5、哈希集合 unordered_set初始化常用成员函数6、队列 queue初始化成员函数7、栈stack初始化常用成员函数7、emplace…

Linq list 排序,Dictionary 排序

C# 对List成员排序的简单方法 http://blog.csdn.net/wanzhuan2010/article/details/6205884 LINQ之路系列博客导航 http://www.cnblogs.com/lifepoem/archive/2011/12/16/2288017.html 用一句Linq把一个集合的属性值根据条件改了&#xff0c;其他值不变 list去重 list.Where((x…

javascript Ajax 同步请求与异步请求的问题

先来看以下代码&#xff1a; var flagtrue; var index0; $.ajax({url: "http://www.baidu.com/",success: function(data){flagfalse;} }); while(flag){index; } alert(index); 请问最后alert的index的结果是多少&#xff1f; 可能有人会说0呗。实际上却没那么简单…

定义类的Python示例

The task to define a class in Python. 在Python中定义类的任务。 Here, we are defining a class named Number with an attribute num, initializing it with a value 123, then creating two objects N1 and N2 and finally, printing the objects memory locations and a…

十一、线性层

一、Linear Layers torch.nn.Linear(in_features, out_features, biasTrue, deviceNone, dtypeNone) 以VGG神经网络为例&#xff0c;Linear Layers可以将特征图的大小进行变换由(1,1,4096)转换为(1,1,1000) 二、torch.nn.Linear实战 将CIFAR-10数据集中的测试集二维图像[6…