## 自动求导

### 链式法则和自动求导

#### 向量链式法则

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} f ( u ) , u = g ( x )   =

### 自动求导

l n [ 1 ] : = D [ 4 x 3 + x 2 + 3 , x ] ln[1]:= D[4x^3+x^2+3, x] l n [ 1 ] : D [ 4 x 3 + 3 , x ]
O u t [ 1 ] = 2 x + 12 x 2 Out[1]= 2x+12x^2 O u t [ 1 ] = 2 x + 1 2 x 2

∂ 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 ) ​ = l i m h − > 0 ​ h f ( x + h ) − f ( x ) ​

Tensorflow/Theano/MXNet

from mxnet import sym
a = sym.var()
b = sym.var()
c = 2 * a + b
# bind data into a and b later

Pytorch/MXNet

from mxnet import autograd, nd
a = nd.ones((2, 1))
b = nd.ones((2, 1))
c = 2 * a + b

### 自动求导的两种模式

#### 反向累积总结

O(n)计算复杂度用来计算一个变量的梯度
O(1)内存复杂度

## 自动求导实现

### 自动求导

import torch
x = torch.arange(4.0)
x

tensor([0., 1., 2., 3.])

x.requires_grad(True)# 等价于 x = torch.arange(4.0, requires_grad=True)
x.grad# 默认值是None

y = 2 * torch.dot(x, x)
y

tensor(28.)

y.backward()
x.grad

tensor([ 0., 4., 8., 12.])

x.grad == 4 * x

tensor([True, True, True, True])

# 在默认情况下，PyTorch会累积梯度，我们需要清除之前的值
y = x.sum()
y.backward()
x.grad

tensor([1., 1., 1., 1.])

# 对非标量用backword需要传入一个gradient参数，该参数指定微分参数
y = x * x
# 等价于y.backword(torch.ones(len(x))
y.sum().backward()
x.grad

tensor([0., 2., 4., 6.])

x.grad.zero_()
y = x * x
u = y.detach()# 将参数常数化
z = u * x
z.sum().backward()
x.grad == u

tensor([True, True, True, True])

x.grad.zero_()
y.sum().backward()
x.grad == 2 * x

tensor([True, True, True, True])

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
d = f(a)
d.backward()
a.grad == d / a

tensor(True)