七、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.pswp.cn/news/377581.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377581.shtml
英文地址,請注明出處:http://en.pswp.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…