如何使用AutoGrad软件包?

时间:2018-02-02 13:07:57

标签: python machine-learning deep-learning gradient-descent autograd

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

import tangent

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

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

在输入输出对丢失之后,我想得到渐变的损失:

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

但是图书馆教程没有显示如何获得关于a或b的渐变,即参数如此,既不是autograd也不是切线。

2 个答案:

答案 0 :(得分:1)

您可以使用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'应该是loss函数的输入,它将它们传递给模型以计算导数。

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

答案 1 :(得分:0)

这可能会有所帮助:

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()

输出:

enter image description here