当前位置:网站首页>2 neural network toolbox NN
2 neural network toolbox NN
2022-07-29 03:22:00 【smiling0927】
1. In practice , The most common practice is to inherit nn.Module, Write your own network layer . Here's how to use nn.Module Realize your own full connection layer .
Fully connected layer , Also known as affine layer , Input y and x Satisfy y=Wx+b,W,b It's a learnable parameter .
import torch as t
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable as V
class Linear(nn.Module):# Inherit nn.Module
def __init__(self,in_features,outfeatures):
super(Linear,self).__init__()# Equivalent to nn.Module.__init__(self)
self.w=nn.Parameter(t.randn(in_features,outfeatures))
self.b=nn.Parameter(t.randn(outfeatures))
def forward(self, x):
x=x.mm(self.w)
return x+self.b.expand_as(x)
# expand_as (a)
# This is a tensor A built-in method of variable , If you use b.expand_as (a)
# Will be b To expand , Expand to a Dimensions , It should be noted that a The low dimension of needs to be better than b Big , for example b Of shape yes 3 * 1, If a Of shape yes 3 * 2
# No mistakes , But it is 2 * 2 It's going to be a mistake
layer=Linear(4,3)
input=V(t.randn(2,4))
output =layer(input)
print(output)Output :
tensor([[-3.0932, 1.7944, -0.4888],
[-1.8203, 1.4885, -0.2306]], grad_fn=<AddBackward0>)
so , The implementation of full connection layer is simple , But we need to pay attention to the following points :
1) Custom layer Linear Must inherit nn.Module, And call... In its constructor nn.Module Constructor for , namely super(Linear,self)__init__(self).
2) In the constructor __init__ You must define your own learnable parameters , And encapsulate it into Parameter, As in this example, we put w,b Encapsulated into Parameter. It's a special Variable, But by default, it requires derivation (required_grad=True).
3)forward Function to realize the forward propagation process , Its input can be one or more variable, Yes x Any operation of must also be variable Supported operations .
4) No need to write back propagation function , Because its forward propagation is right variable To operate ,nn.Module Be able to use autograd Automatic back propagation , This is better than Function Simple and many .
2.Module Can automatically detect their own parameter, And as a learning parameter . except parameter,Module Also contains children Module, Lord Module Can recursively find sub Module Medium parameter.
Multilayer perceptron , It consists of two fully connected layers , use sigmoid Function as activation function .
class Perceptron(nn.Module):
def __init__(self,in_features,hidden_features,out_features):
nn.Module.__init__(self)
#super (Perceptron, self).__init__ ()
self.layer1=Linear(in_features,hidden_features)
self.layer2 = Linear (hidden_features, out_features)
def forward(self, x):
x=self.layer1(x)
x=t.sigmoid(x)
return self.layer2(x)
perceptron =Perceptron(3,4,1)
for name,parameter in perceptron.named_parameters():
print(name,parameter.size())#w,bOutput :
layer1.w torch.Size([3, 4])
layer1.b torch.Size([4])
layer2.w torch.Size([4, 1])
layer2.b torch.Size([1])
1) Constructors __init__ in , You can use the customized Linear layer (Module) As the present Module A child of the object of Module, His learnable parameters , It will also become the present Module The learnable parameters of .
2) In the forward propagation function , We consciously Name the output variables x, It's to make Python Recycle some output from the middle layer , thus Save memory .
3)Module in parameter The global naming conventions for are as follows :
①Parameter Direct naming . for example self.param_name=nn.Parameter(t.randn(3,4)), Name it param_name.
② Son Module Medium parameter, Will add the current before its name Module Name . for example :self.sub_module=SubModel(),SubModel There is one of them. parameter Is also called param_name, Then the two are combined parameter name Namely sub_module.param_name.
4) Arguments to the constructor , Such as nn.Linear(in_feature,out_feature,bias), We need to pay attention to the role of these three parameters .
attribute 、 Learnable parameters and subsets Module. Such as nn.Linear There is weight and bias Two learnable parameters , It doesn't contain children Module.
The shape of the input and output , Such as nn.linear The input shape for is (N,input_features), Output is (N,output_features),N yes batch_size.
Be careful : Self defined layer There are assumptions about the input shape : The input is not a single data , It is a batch. If you want to input a data , Must call unsqueeze(0) Function disguised as batch_size=1 Of batch.
边栏推荐
- Introduction and advanced level of MySQL (11)
- 军品技术文件划分及说明
- xxxxx
- 12_ UE4 advanced_ Change a more beautiful character model
- Redis之sentinel哨兵集群怎么部署
- SAP 中国本地化内容汇总
- MySQL流程控制之while、repeat、loop循环实例分析
- C语言基础知识点汇总
- Division and description of military technical documents
- [freeswitch development practice] media bug obtains call voice flow
猜你喜欢

Reproduce 20 character short domain name bypass and XSS related knowledge points

Example analysis of while, repeat and loop loops in MySQL process control

Chapter 2 VRP command line

带你来浅聊一下,单商户功能模块汇总

Unity 之游戏特效

01-sdram: Code of initialization module

Verilog: blocking assignment and non blocking assignment

Configure vscade to realize ROS writing

3D高级渲染器:Artlantis studio 2021.2中文版

【C】 Array
随机推荐
i. MX 8m plus integrated dedicated neural processing engine (NPU)
Asynchronous callback future mode of concurrent mode
Digital image processing Chapter 10 - image segmentation
Shardingsphere's level table practice (III)
【科技1】
带你来浅聊一下,单商户功能模块汇总
MySQL流程控制之while、repeat、loop循环实例分析
How to solve the time zone problem in MySQL timestamp
Detailed steps for installing MySQL 8.0 under Linux
4000 多字学懂弄通 js 中 this 指向问题,顺便手写实现 call、apply 和 bind
C obtains JSON format data asynchronously from the web address
【C】 Array
Minesweeping simple version
Data truncation and estimation
Tonight at 7:30 | is the AI world in the eyes of Lianjie, Jiangmen, Baidu and country garden venture capital continue to be advanced or return to the essence of business
Engineering boy: under 20 years old, ordinary but not mediocre
2. Nodejs -- path (\dirname, \filname), URL URL, querystring module, mime module, various paths (relative paths), web page loading (interview questions *)
Verilog: blocking assignment and non blocking assignment
mysql的timestamp存在的时区问题怎么解决
生产部署zabbix5.0笔记