自动微分
下面用反正切函数作为例子:
import autograd.numpy as np
from autograd import value_and_grad
import matplotlib.pyplot as plt
g = lambda w: np.tanh(w)
w=np.linspace(-5,5,20)
c = g(w)
plt.plot(c)
plt.show
dgdw = value_and_grad(g)
# evaluate the gradient function at a point
w_val = 1.0
print (dgdw(w_val))
输出:(0.76159415595576485, 0.41997434161402608)
第一个为函数g在1.0的值,第二个为该函数在1.0的梯度
下面测试多个输入的情况:
dgdw([-1,1,2,3])
Out[50]:
(array([-0.76159416, 0.76159416, 0.96402758, 0.99505475]),
array([ 0.41997434, 0.41997434, 0.07065082, 0.00986604]))
可见输出两个array,第一个为函数值,第二个为梯度值,对应着其名字:value_and_grad.
参考
- https://jermwatt.github.io/machine_learning_refined/notes/3_First_order_methods/3_5_Automatic.html