繁体   English   中英

如何使用 AutoGrad 包?

[英]How to Use AutoGrad Packages?

我正在尝试做一件简单的事情:使用 autograd 获取梯度并进行梯度下降:

import tangent

def model(x):
    return a*x + b

def loss(x,y):
    return (y-model(x))**2.0

在输入-输出对得到损失后,我想得到梯度 wrt 损失:

    l = loss(1,2)
    # grad_a = gradient of loss wrt a?
    a = a - grad_a
    b = b - grad_b

但是库教程没有展示如何获得关于 a 或 b 的梯度,即参数,无论是 autograd 还是 tangent。

您可以使用 grad 函数的第二个参数指定它:

def f(x,y):
    return x*x + x*y

f_x = grad(f,0) # derivative with respect to first argument
f_y = grad(f,1) # derivative with respect to second argument

print("f(2,3)   = ", f(2.0,3.0))
print("f_x(2,3) = ", f_x(2.0,3.0)) 
print("f_y(2,3) = ", f_y(2.0,3.0))

在您的情况下,'a' 和 'b' 应该是损失函数的输入,损失函数将它们传递给模型以计算导数。

我刚刚回答了一个类似的问题: Partial Derivative using Autograd

这可能会有所帮助:

import autograd.numpy as np
from autograd import grad
def tanh(x):
  y=np.exp(-x)
  return (1.0-y)/(1.0+y)

grad_tanh = grad(tanh)

print(grad_tanh(1.0))

e=0.00001
g=(tanh(1+e)-tanh(1))/e
print(g)

输出:

0.39322386648296376
0.39322295790622513

以下是您可以创建的内容:

import autograd.numpy as np
from autograd import grad  # grad(f) returns f'

def f(x): # tanh
  y = np.exp(-x)
  return  (1.0 - y) / ( 1.0 + y)

D_f   = grad(f) # Obtain gradient function
D2_f = grad(D_f)# 2nd derivative
D3_f = grad(D2_f)# 3rd derivative
D4_f = grad(D3_f)# etc.
D5_f = grad(D4_f)
D6_f = grad(D5_f)

import  matplotlib.pyplot  as plt
plt.subplots(figsize = (9,6), dpi=153 )
x = np.linspace(-7, 7, 100)
plt.plot(x, list(map(f, x)),
         x, list(map(D_f , x)),
         x, list(map(D2_f , x)),
         x, list(map(D3_f , x)),
         x, list(map(D4_f , x)),
         x, list(map(D5_f , x)),
         x, list(map(D6_f , x)))
plt.show()

输出:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM