from mxnet import autograd, np, npx npx.set_np() x = np.arange(4) x
array([0., 1., 2., 3.])
创建空间用来储存关于 x 的导数。
x
x.attach_grad()
使用 record 来记录计算。
record
with autograd.record(): y = 2.0 * np.dot(x, x) y
array(28.)
函数 $y = 2\mathbf{x}^{\top}\mathbf{x}$ 关于 $\mathbf{x}$ 的导数应该是 $4\mathbf{x}$。
y.backward() x.grad - 4 * x
array([0., 0., 0., 0.])