[Pytorch系列-30]:神经网络基础 - torch.nn库五大基本功能:nn.Parameter、nn.Linear、nn.functioinal、nn.Module、nn.Sequentia
作者主頁(文火冰糖的硅基工坊):文火冰糖(王文兵)的博客_文火冰糖的硅基工坊_CSDN博客
本文網址:https://blog.csdn.net/HiWangWenBing/article/details/120614234
目錄
前言 深度學習模型框架
第1章 torch.nn簡介
1.1?torch.nn相關庫的導入
1.2?torch.nn概述
第2章 nn.Linear類(全連接層)
2.1 函數(shù)功能
2.2 函數(shù)說明
2.3 多個全連接層構建全連接網絡
2.4 使用nn.Linear類創(chuàng)建全連接層
第3章 nn.functional(常見函數(shù))
3.1?nn.functional概述
3.2?nn.functional函數(shù)分類
3.3 激活函數(shù)的案例
第4章? nn.xxx和nn.functional.xxx比較
4.1 相同點
4.2 不同點
第5章 nn.Parameter類
5.1?nn.Parameter概述
5.2 單個全連接層中參數(shù)的個數(shù)
5.3 使用參數(shù)創(chuàng)建全連接層代碼案例
第6章 nn.Module類
第7章 利用nn.Sequential類創(chuàng)建神經網絡(繼承與nn.Module類)
7.1 概述
7.2 以列表的形式,串聯(lián)函數(shù)運算,構建串行執(zhí)行的神經網絡
7.3?以字典的形式,串聯(lián)函數(shù)運算,構建串行執(zhí)行的神經網絡
7.4?案例2
第8章 自定義神經網絡模型類(繼承于Module類)
前言 深度學習模型框架
[人工智能-深度學習-8]:神經網絡基礎 - 機器學習、深度學習模型、模型訓練_文火冰糖(王文兵)的博客-CSDN博客_神經網絡與深度學習第1章 白話機器學習[人工智能-綜述-4]:白話深度學習-- 無基礎小白都能理解機器學習的核心概念_文火冰糖(王文兵)的博客-CSDN博客[人工智能-深度學習-7]:神經網絡基礎 - 人工神經網絡ANN_文火冰糖(王文兵)的博客-CSDN博客第2章 機器學習的模型與步驟2.1深度學習與機器學習上述三個概念中:人工智能的概念最廣泛,所以有能機器具有類”人“一樣智能的技術、非技術(如倫理)的領域,都是人工智能。機器獲取“智能”的一個重要手段是,機器具備“自我學習”的能力,...https://blog.csdn.net/HiWangWenBing/article/details/120462734
第1章 torch.nn簡介
1.1?torch.nn相關庫的導入
#環(huán)境準備 import numpy as np # numpy數(shù)組庫 import math # 數(shù)學運算庫 import matplotlib.pyplot as plt # 畫圖庫import torch # torch基礎庫 import torch.nn as nn # torch神經網絡庫 import torch.nn.functional as F1.2?torch.nn概述
Pytorch提供了幾個設計得非常棒的模塊和類,比如 torch.nn,torch.optim,Dataset 以及 DataLoader,來幫助程序員設計和訓練神經網絡。
nn是Neural Network的簡稱,幫助程序員方便執(zhí)行如下的與神經網絡相關的行為:
(1)創(chuàng)建神經網絡
(2)訓練神經網絡
(3)保存神經網絡
(4)恢復神經網絡
其包括如下五大基本功能模塊:
第2章 nn.Linear類(全連接層)
2.1 函數(shù)功能
用于創(chuàng)建一個多輸入、多輸出的全連接層。
?備注:nn.Linear本身并不包含激活函數(shù)(Functional)
2.2 函數(shù)說明
- in_features:
指的是輸入的二維張量的大小,即輸入的[batch_size, size]中的size。
in_features的數(shù)量,決定的參數(shù)的個數(shù)? ?Y = WX + b,? X的維度就是in_features,X的維度決定的W的維度, 總的參數(shù)個數(shù) =?in_features + 1
- out_features:
指的是輸出的二維張量的大小,即輸出的二維張量的形狀為[batch_size output_size]。
out_features的數(shù)量,決定了全連接層中神經元的個數(shù),因為每個神經元只有一個輸出。
多少個輸出,就需要多個個神經元。
從輸入輸出的張量的shape角度來理解,相當于一個輸入為[batch_size, in_features]的張量變換成了[batch_size, out_features]的輸出張量。
2.3 多個全連接層構建全連接網絡
?
2.4 使用nn.Linear類創(chuàng)建全連接層
# nn.Linear # 建立單層的多輸入、多輸出全連接層 # in_features由輸入張量的形狀決定,out_features則決定了輸出張量的形狀 full_connect_layer = nn.Linear(in_features = 28 * 28 * 1, out_features = 3) print("full_connect_layer:", full_connect_layer) print("parameters :", full_connect_layer.parameters)# 假定輸入的圖像形狀為[64,64,3] x_input = torch.randn(1, 28, 28, 1)# 將四維張量轉換為二維張量之后,才能作為全連接層的輸入 x_input = x_input.view(1, 28 * 28 * 1) print("x_input.shape:", x_input.shape)# 調用全連接層 y_output = full_connect_layer(x_input) print("y_output.shape:", y_output.shape) print("y_output:", y_output) full_connect_layer: Linear(in_features=784, out_features=3, bias=True) parameters : <bound method Module.parameters of Linear(in_features=784, out_features=3, bias=True)> x_input.shape: torch.Size([1, 784]) y_output.shape: torch.Size([1, 3]) y_output: tensor([[-0.2892, -0.3084, 0.9027]], grad_fn=<AddmmBackward>)第3章 nn.functional(常見函數(shù))
3.1?nn.functional概述
nn.functional定義了創(chuàng)建神經網絡所需要的一些常見的處理函數(shù)。如沒有激活函數(shù)的神經元,各種激活函數(shù)等。
3.2?nn.functional函數(shù)分類
nn.functional包括神經網絡前向和后向處理所需要到的常見函數(shù)。
(1)神經元處理函數(shù)
(2)激活函數(shù)
3.3 激活函數(shù)的案例
(1)relu案例
# nn.functional.relu( ) print(y_output) out = nn.functional.relu(y_output) print(out.shape) print(out) tensor([[ 0.1023, 0.7831, -0.2368]], grad_fn=<AddmmBackward>) torch.Size([1, 3]) tensor([[0.1023, 0.7831, 0.0000]], grad_fn=<ReluBackward0>)(2)sigmoid案例
# nn.functional.sigmoid( ) print(y_output) out = nn.functional.sigmoid(y_output) print(out.shape) print(out) tensor([[ 0.1023, 0.7831, -0.2368]], grad_fn=<AddmmBackward>) torch.Size([1, 3]) tensor([[0.5255, 0.6863, 0.4411]], grad_fn=<SigmoidBackward>)第4章? nn.xxx和nn.functional.xxx比較
4.1 相同點
- nn.Xxx和nn.functional.xxx的實際功能是相同的,即nn.Conv2d和nn.functional.conv2d 都是進行卷積,nn.Dropout 和nn.functional.dropout都是進行dropout,。。。。。;
- 運行效率也是近乎相同。
4.2 不同點
-
形式看:nn.functional.xxx是小寫字母開頭,nn.Xxx中的函數(shù)是大寫字母開頭。
-
nn.functional.xxx是API函數(shù)接口,而nn.Xxx是對原始API函數(shù)nn.functional.xxx的類封裝。
-
所有nn.Xxx都繼承于于共同祖先nn.Module。這一點導致nn.Xxx除了具有nn.functional.xxx功能之外,內部附帶了nn.Module相關的屬性和方法,例如train(), eval(),load_state_dict, state_dict 等。
-
nn.Xxx繼承于nn.Module, 能夠很好的與nn.Sequential結合使用, 而nn.functional.xxx無法與nn.Sequential結合使用。
-
nn.Xxx?需要先實例化并傳入參數(shù),然后以函數(shù)調用的方式調用實例化的對象并傳入輸入數(shù)據(jù)。nn.functional.xxx同時傳入輸入數(shù)據(jù)和weight, bias等其他參數(shù) 。
-
nn.Xxx不需要你自己定義和管理weight;而nn.functional.xxx需要你自己定義weight,每次調用的時候都需要手動傳入weight, 不利于代碼復用。
第5章 nn.Parameter類
5.1?nn.Parameter概述
Parameter實際上也是Tensor,也就是說是一個多維矩陣,是Variable類中的一個特殊類。
當我們創(chuàng)建一個model時,nn會自動創(chuàng)建相應的參數(shù)parameter,并會自動累加到模型的Parameter 成員列表中。
5.2 單個全連接層中參數(shù)的個數(shù)
in_features的數(shù)量,決定的參數(shù)的個數(shù)? ?Y = WX + b,? X的維度就是in_features,X的維度決定的W的維度, 總的參數(shù)個數(shù) =?in_features + 1
out_features的數(shù)量,決定了全連接層中神經元的個數(shù),因為每個神經元只有一個輸出。
多少個輸出,就需要多個個神經元。
總的W參數(shù)的個數(shù)=? in_features?*?out_features
總的b參數(shù)的個數(shù)=? 1 *?out_features
總的參數(shù)(W和B)的個數(shù)=? (in_features + 1) *?out_features
5.3 使用參數(shù)創(chuàng)建全連接層代碼案例
# nn.functional.linear( ) x_input = torch.Tensor([1., 1., 1.]) print("x_input.shape:", x_input.shape) print("x_input :", x_input) print("")Weights1 = nn.Parameter(torch.rand(3)) print("Weights.shape:", Weights1.shape) print("Weights :", Weights1) print("")Bias1 = nn.Parameter(torch.rand(1)) print("Bias.shape:", Bias1.shape) print("Bias :", Bias1) print("")Weights2 = nn.Parameter(torch.Tensor(3)) print("Weights.shape:", Weights2.shape) print("Weights :", Weights2)print("\nfull_connect_layer") full_connect_layer = nn.functional.linear(x_input, Weights1) print(full_connect_layer) x_input.shape: torch.Size([3]) x_input : tensor([1., 1., 1.])Weights.shape: torch.Size([3]) Weights : Parameter containing: tensor([0.3339, 0.7027, 0.9703], requires_grad=True)Bias.shape: torch.Size([1]) Bias : Parameter containing: tensor([0.4936], requires_grad=True)Weights.shape: torch.Size([3]) Weights : Parameter containing: tensor([0.0000e+00, 1.8980e+01, 1.1210e-44], requires_grad=True)full_connect_layer tensor(2.0068, grad_fn=<DotBackward>)第6章 nn.Module類
第7章 利用nn.Sequential類創(chuàng)建神經網絡(繼承與nn.Module類)
7.1 概述
A sequential container. Modules will be added to it in the order they are passed in the constructor. Alternatively, an ordered dict of modules can also be passed in.
nn.Sequential是一個有序的容器,該類將按照傳入構造器的順序,依次創(chuàng)建相應的函數(shù),并記錄在Sequential類對象的數(shù)據(jù)結構中,同時以神經網絡模塊為元素的有序字典也可以作為傳入參數(shù)。
因此,Sequential可以看成是有多個函數(shù)運算對象,串聯(lián)成的神經網絡,其返回的是Module類型的神經網絡對象。
7.2 以列表的形式,串聯(lián)函數(shù)運算,構建串行執(zhí)行的神經網絡
print("利用系統(tǒng)提供的神經網絡模型類:Sequential,以參數(shù)列表的方式來實例化神經網絡模型對象") # A sequential container. Modules will be added to it in the order they are passed in the constructor. # Example of using Sequential model_c = nn.Sequential(nn.Linear(28*28, 32), nn.ReLU(), nn.Linear(32, 10), nn.Softmax(dim=1)) print(model_c)print("\n顯示網絡模型參數(shù)") print(model_c.parameters)print("\n定義神經網絡樣本輸入") x_input = torch.randn(2, 28, 28, 1) print(x_input.shape)print("\n使用神經網絡進行預測") y_pred = model.forward(x_input.view(x_input.size()[0],-1)) print(y_pred) 利用系統(tǒng)提供的神經網絡模型類:Sequential,以參數(shù)列表的方式來實例化神經網絡模型對象 Sequential((0): Linear(in_features=784, out_features=32, bias=True)(1): ReLU()(2): Linear(in_features=32, out_features=10, bias=True)(3): Softmax(dim=1) )顯示網絡模型參數(shù) <bound method Module.parameters of Sequential((0): Linear(in_features=784, out_features=32, bias=True)(1): ReLU()(2): Linear(in_features=32, out_features=10, bias=True)(3): Softmax(dim=1) )>定義神經網絡樣本輸入 torch.Size([2, 28, 28, 1])使用神經網絡進行預測 tensor([[-0.1526, 0.0437, -0.1685, 0.0034, -0.0675, 0.0423, 0.2807, 0.0527,-0.1710, 0.0668],[-0.1820, 0.0860, 0.0174, 0.0883, 0.2046, -0.1609, 0.0165, -0.2392,-0.2348, 0.1697]], grad_fn=<AddmmBackward>)7.3?以字典的形式,串聯(lián)函數(shù)運算,構建串行執(zhí)行的神經網絡
# Example of using Sequential with OrderedDict print("利用系統(tǒng)提供的神經網絡模型類:Sequential,以字典的方式來實例化神經網絡模型對象") model = nn.Sequential(OrderedDict([('h1', nn.Linear(28*28, 32)),('relu1', nn.ReLU()),('out', nn.Linear(32, 10)),('softmax', nn.Softmax(dim=1))]))print(model)print("\n顯示網絡模型參數(shù)") print(model.parameters)print("\n定義神經網絡樣本輸入") x_input = torch.randn(2, 28, 28, 1) print(x_input.shape)print("\n使用神經網絡進行預測") y_pred = model.forward(x_input.view(x_input.size()[0],-1)) print(y_pred) 利用系統(tǒng)提供的神經網絡模型類:Sequential,以字典的方式來實例化神經網絡模型對象 Sequential((h1): Linear(in_features=784, out_features=32, bias=True)(relu1): ReLU()(out): Linear(in_features=32, out_features=10, bias=True)(softmax): Softmax(dim=1) )顯示網絡模型參數(shù) <bound method Module.parameters of Sequential((h1): Linear(in_features=784, out_features=32, bias=True)(relu1): ReLU()(out): Linear(in_features=32, out_features=10, bias=True)(softmax): Softmax(dim=1) )>定義神經網絡樣本輸入 torch.Size([2, 28, 28, 1])使用神經網絡進行預測 tensor([[0.1249, 0.1414, 0.0708, 0.1031, 0.1080, 0.1351, 0.0859, 0.0947, 0.0753,0.0607],[0.0982, 0.1102, 0.0929, 0.0855, 0.0848, 0.1076, 0.1077, 0.0949, 0.1153,0.1029]], grad_fn=<SoftmaxBackward>)7.4?案例2
第8章 自定義神經網絡模型類(繼承于Module類)
# 定義網絡模型:帶relu的兩層全連接神經網絡 print("自定義新的神經網絡模型的類") class NetC(torch.nn.Module):# 定義神經網絡def __init__(self, n_feature, n_hidden, n_output):super(NetC, self).__init__()self.h1 = nn.Linear(n_feature, n_hidden)self.relu1 = nn.ReLU()self.out = nn.Linear(n_hidden, n_output)self.softmax = nn.Softmax(dim=1)#定義前向運算def forward(self, x):# 得到的數(shù)據(jù)格式torch.Size([64, 1, 28, 28])需要轉變?yōu)?#xff08;64,784)x = x.view(x.size()[0],-1) # -1表示自動匹配h1 = self.h1(x)a1 = self.relu1(h1)out = self.out(a1)a_out = self.softmax(out)return outprint("\n實例化神經網絡模型對象") model = NetC(28*28, 32, 10) print(model)print("\n顯示網絡模型參數(shù)") print(model.parameters)print("\n定義神經網絡樣本輸入") x_input = torch.randn(2, 28, 28, 1) print(x_input.shape)print("\n使用神經網絡進行預測") y_pred = model.forward(x_input) print(y_pred) 自定義新的神經網絡模型的類實例化神經網絡模型對象 NetC((h1): Linear(in_features=784, out_features=32, bias=True)(relu1): ReLU()(out): Linear(in_features=32, out_features=10, bias=True)(softmax): Softmax(dim=1) )顯示網絡模型參數(shù) <bound method Module.parameters of NetC((h1): Linear(in_features=784, out_features=32, bias=True)(relu1): ReLU()(out): Linear(in_features=32, out_features=10, bias=True)(softmax): Softmax(dim=1) )>定義神經網絡樣本輸入 torch.Size([2, 28, 28, 1])使用神經網絡進行預測 tensor([[-0.3095, 0.3118, 0.3795, -0.2508, 0.1127, -0.2721, -0.3563, 0.3058,0.5193, 0.0436],[-0.2070, 0.6417, 0.2125, -0.0413, 0.0827, 0.2448, -0.0399, 0.2837,0.0052, -0.1834]], grad_fn=<AddmmBackward>)作者主頁(文火冰糖的硅基工坊):文火冰糖(王文兵)的博客_文火冰糖的硅基工坊_CSDN博客
本文網址:https://blog.csdn.net/HiWangWenBing/article/details/120614234
總結
以上是生活随笔為你收集整理的[Pytorch系列-30]:神经网络基础 - torch.nn库五大基本功能:nn.Parameter、nn.Linear、nn.functioinal、nn.Module、nn.Sequentia的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ZOJ 3380 Patchouli's
- 下一篇: [1119] Patchouli's B