当前位置:网站首页>Automatic derivation of introduction to deep learning (pytoch)
Automatic derivation of introduction to deep learning (pytoch)
2022-07-03 10:33:00 【-Plain heart to warm】
Automatic derivation
Automatic derivation
Chain rule and automatic derivation
Vector chain rule
Scalar chain rule
y = f ( u ) , u = g ( x ) ∂ y ∂ x = ∂ y ∂ u ∂ u ∂ x y=f(u),u=g(x) \quad\ {\partial y \over \partial x}={\partial y \over \partial u}{\partial u \over \partial x} y=f(u),u=g(x) ∂x∂y=∂u∂y∂x∂uExpand to vector
Example 1
Example 2
Automatic derivation
- Automatic derivation calculates the derivative of a function at a specified value
- It is different from
- Sign derivation
l n [ 1 ] : = D [ 4 x 3 + x 2 + 3 , x ] ln[1]:= D[4x^3+x^2+3, x] ln[1]:=D[4x3+x2+3,x]
O u t [ 1 ] = 2 x + 12 x 2 Out[1]= 2x+12x^2 Out[1]=2x+12x2 - Numerical derivation
∂ f ( x ) ∂ x = l i m h − > 0 f ( x + h ) − f ( x ) h {\partial f(x) \over \partial x }= lim_{h->0}{f(x+h) - f(x) \over h} ∂x∂f(x)=limh−>0hf(x+h)−f(x)
- Sign derivation
Calculation chart
- Decompose the code into operands
- The calculation is expressed as an acyclic graph
- Show construction
- Tensorflow/Theano/MXNet
from mxnet import sym
a = sym.var()
b = sym.var()
c = 2 * a + b
# bind data into a and b later
First define the formula , Then bring the value into
- Implicit construction
- Pytorch/MXNet
from mxnet import autograd, nd
with autograd.record():
a = nd.ones((2, 1))
b = nd.ones((2, 1))
c = 2 * a + b
Two modes of automatic derivation
Reverse accumulation
Reverse cumulative summary
- Construction calculation diagram
- Forward direction : Execution diagram , Store intermediate results
- reverse : Execute the diagram from the opposite direction
- Remove unwanted branches
- Remove unwanted branches
Complexity
- Computational complexity :O(n),n Is the number of operands
- Usually the cost of forward and direction is similar
- Memory complexity :O(n), Because you need to store all the intermediate results in the forward direction
Because you want to store all the intermediate results , So it's very expensive GPU resources
- Compared with positive accumulation :
- O(n) Computational complexity is used to calculate the gradient of a variable
- O(1) Memory complexity
Automatic derivation implementation
Automatic derivation
Let's say we want to test the function y = 2 x T x y = 2x^Tx y=2xTx About column vectors x Derivation
import torch
x = torch.arange(4.0)
x
tensor([0., 1., 2., 3.])
In our calculation y About x Before the gradient of , We need a place to store gradients .
x.requires_grad(True) # Equivalent to `x = torch.arange(4.0, requires_grad=True)`
x.grad # The default value is None
Now let's calculate y.
y = 2 * torch.dot(x, x)
y
tensor(28.)
Automatically calculate by calling the back propagation function y
About x
The gradient of each component
y.backward()
x.grad
tensor([ 0., 4., 8., 12.])
The calculated value should be 4x, You can verify that
x.grad == 4 * x
tensor([True, True, True, True])
Now let's calculate x
Another function of
# By default ,PyTorch It accumulates gradients , We need to clear the previous value
x.grad.zero_()
y = x.sum()
y.backward()
x.grad
tensor([1., 1., 1., 1.])
Deep learning , Our purpose is not to calculate the differential matrix , It is the sum of the partial derivatives calculated separately for each sample in the batch .
# For non scalars `backword` Need to pass in a `gradient` Parameters , This parameter specifies the differential parameter
x.grad.zero_()
y = x * x
# Equivalent to y.backword(torch.ones(len(x))
y.sum().backward()
x.grad
tensor([0., 2., 4., 6.])
Why do we do this when we take the derivative sum operation ?
Gradient can only be scalar ( That is, a number ) Output implicitly creates .
Move some calculations out of the recorded calculation diagram
x.grad.zero_()
y = x * x
u = y.detach() # Make the parameter constant
z = u * x
z.sum().backward()
x.grad == u
tensor([True, True, True, True])
Later, when some network parameters are fixed , It is useful to
x.grad.zero_()
y.sum().backward()
x.grad == 2 * x
tensor([True, True, True, True])
Even if the calculation diagram of the construction function needs to pass Python control flow ( for example , Conditions 、 Loop or any function call ), We can still calculate the gradient of the variable .
def f(a):
b = a * 2
while b.norm() < 1000:
b = b * 2
if b.sum() > 0:
c = b
else:
c = 100 * b
return c
a = torch.randn(size=(), requires_grad=True)
d = f(a)
d.backward()
a.grad == d / a
tensor(True)
QA
The difference between explicit construction and implicit construction ?
Show calculation : Give the formula first and then the value
Implicit calculation : Give the value first and then the formulaWhy does deep learning generally take derivatives from scalars ?
because Loss Most of the time it's scalar .
边栏推荐
- 2018 y7000 upgrade hard disk + migrate and upgrade black apple
- 20220607 others: sum of two integers
- Ind yff first week
- 4.1 Temporal Differential of one step
- Anaconda installation package reported an error packagesnotfounderror: the following packages are not available from current channels:
- Leetcode刷题---283
- Hands on deep learning pytorch version exercise answer - 2.2 preliminary knowledge / data preprocessing
- EFFICIENT PROBABILISTIC LOGIC REASONING WITH GRAPH NEURAL NETWORKS
- Hands on deep learning pytorch version exercise solution-3.3 simple implementation of linear regression
- Tensorflow—Neural Style Transfer
猜你喜欢
Convolutional neural network (CNN) learning notes (own understanding + own code) - deep learning
Ut2013 learning notes
Tensorflow—Neural Style Transfer
Ut2017 learning notes
Training effects of different data sets (yolov5)
丢弃法Dropout(Pytorch)
Hands on deep learning pytorch version exercise answer - 2.2 preliminary knowledge / data preprocessing
A complete answer sheet recognition system
Ind kwf first week
Ut2016 learning notes
随机推荐
侯捷——STL源码剖析 笔记
Model evaluation and selection
openCV+dlib实现给蒙娜丽莎换脸
Implementation of "quick start electronic" window dragging
Rewrite Boston house price forecast task (using paddlepaddlepaddle)
20220601数学:阶乘后的零
openCV+dlib實現給蒙娜麗莎換臉
Configure opencv in QT Creator
二分查找法
Several problems encountered in installing MySQL under MAC system
Ut2014 learning notes
20220610 other: Task Scheduler
Label Semantic Aware Pre-training for Few-shot Text Classification
[LZY learning notes -dive into deep learning] math preparation 2.1-2.4
Secure in mysql8.0 under Windows_ file_ Priv is null solution
What useful materials have I learned from when installing QT
Stroke prediction: Bayesian
Leetcode - 1172 plate stack (Design - list + small top pile + stack))
Leetcode - 705 design hash set (Design)
2018 y7000 upgrade hard disk + migrate and upgrade black apple