当前位置:网站首页>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 .
边栏推荐
- Ut2014 supplementary learning notes
- Leetcode刷题---704
- Leetcode - 706 design hash mapping (Design)*
- Ind yff first week
- [LZY learning notes -dive into deep learning] math preparation 2.5-2.7
- Ut2017 learning notes
- mysql5.7安装和配置教程(图文超详细版)
- Tensorflow—Neural Style Transfer
- Step 1: teach you to trace the IP address of [phishing email]
- Ut2016 learning notes
猜你喜欢
A complete answer sheet recognition system
[C question set] of Ⅵ
Leetcode - 706 design hash mapping (Design)*
What can I do to exit the current operation and confirm it twice?
Realize an online examination system from zero
深度学习入门之线性代数(PyTorch)
Hands on deep learning pytorch version exercise solution - 2.3 linear algebra
Model evaluation and selection
Anaconda installation package reported an error packagesnotfounderror: the following packages are not available from current channels:
Flutter 退出当前操作二次确认怎么做才更优雅?
随机推荐
Leetcode-106: construct a binary tree according to the sequence of middle and later traversal
Ind yff first week
Tensorflow - tensorflow Foundation
Content type ‘application/x-www-form-urlencoded;charset=UTF-8‘ not supported
Discrete-event system
Seata分布式事务失效,不生效(事务不回滚)的常见场景
深度学习入门之线性回归(PyTorch)
Softmax 回归(PyTorch)
Leetcode刷题---10
openCV+dlib实现给蒙娜丽莎换脸
Notes - regular expressions
熵值法求权重
Leetcode-404: sum of left leaves
Ind FHL first week
Powshell's set location: unable to find a solution to the problem of accepting actual parameters
Step 1: teach you to trace the IP address of [phishing email]
2018 y7000 upgrade hard disk + migrate and upgrade black apple
深度学习入门之自动求导(Pytorch)
Leetcode刷题---202
Data classification: support vector machine