这里主要是想着左手tensorflow,右手pytorch,玩转算法一二三。主要参考资料是 pytorch中文手册。 1 2
自动求导
自动求导是pytorch
最核心的概念,所谓自动求导和高等数学中的导数的概念。
举个例子,
f
(
a
,
x
,
b
)
=
a
2
x
+
b
f(a, x, b) = a^2x+b
f(a,x,b)=a2x+b
分别对
a
,
x
,
b
a,x,b
a,x,b求偏导,则有:
∂
f
∂
a
=
2
a
x
;
\frac{\partial {f}}{\partial {a}} = 2ax;
∂a∂f=2ax;
∂
f
∂
x
=
a
2
\frac{\partial {f}}{\partial {x}} = a^2
∂x∂f=a2
∂
f
∂
b
=
1
\frac{\partial {f}}{\partial {b}} = 1
∂b∂f=1
pytorch
实现如下:
a = torch.tensor(1., requires_grad=True) # 需要求导的话,requires_grad=True,默认False
b = torch.tensor(1., requires_grad=True)
x = torch.tensor(1., requires_grad=True)
f = a*a*x + b
print("before grad: a.grad is {}, b.grad is {}, x.grad is {}".format(a.grad, b.grad, x.grad))
grads = autograd.grad(f, [a, b, x])
print("before grad: a.grad is {}, b.grad is {}, x.grad is {}".format(grads[0], grads[1], grads[2]))
注意⚠️:
上述代码中的1.
不能为1
,否则会报错:
RuntimeError: Only Tensors of floating point and complex dtype can require gradients
模型架构
这是一个数字识别的图像,图像经过卷积层,然后进行