python - 微分梯度

标签 python neural-network deep-learning gradient-descent pytorch

有没有办法在 PyTorch 中区分梯度?

例如,我可以在 TensorFlow 中这样做:

from pylab import *
import tensorflow as tf
tf.reset_default_graph()
sess = tf.InteractiveSession()

def gradient_descent( loss_fnc, w, max_its, lr):
    '''a gradient descent "RNN" '''    
    for k in range(max_its):
        w = w - lr * tf.gradients( loss_fnc(w), w )[0]
    return w

lr = tf.Variable( 0.0, dtype=tf.float32)
w = tf.Variable( tf.zeros(10), dtype=tf.float32)
reg = tf.Variable( 1.0, dtype=tf.float32 )

def loss_fnc(w):
    return tf.reduce_sum((tf.ones(10) - w)**2) + reg * tf.reduce_sum( w**2 )

w_n = gradient_descent( loss_fnc, w, 10, lr )

sess.run( tf.initialize_all_variables())

# differentiate through the gradient_descent RNN with respnect to the initial weight 
print(tf.gradients( w_n, w))

# differentiate through the gradient_descent RNN with respnect to the learning rate
print(tf.gradients( w_n, lr))

输出是

[<tf.Tensor 'gradients_10/AddN_9:0' shape=(10,) dtype=float32>]

[<tf.Tensor 'gradients_11/AddN_9:0' shape=() dtype=float32>]

我如何在 PyTorch 中做类似的事情?

最佳答案

你只需要使用函数 torch.autograd.grad 它与 tf.gradients 完全一样。

所以在 pytorch 中这将是:

from torch.autograd import Variable, grad
import torch



def gradient_descent( loss_fnc, w, max_its, lr):
    '''a gradient descent "RNN" '''    
    for k in range(max_its):
        w = w - lr * grad( loss_fnc(w), w )
    return w

lr = Variable(torch.zeros(1), , requires_grad=True)
w = Variable( torch.zeros(10), requires_grad=True)
reg = Variable( torch.ones(1) , requires_grad=True)

def loss_fnc(w):
    return torch.sum((Variable(torch.ones(10)) - w)**2) + reg * torch.sum( w**2 )

w_n = gradient_descent( loss_fnc, w, 10, lr )


# differentiate through the gradient_descent RNN with respnect to the initial weight 
print(grad( w_n, w))

# differentiate through the gradient_descent RNN with respnect to the learning rate
print(grad( w_n, lr))

关于python - 微分梯度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49149699/

相关文章:

python - 为什么我在图片上添加评论后图片的尺寸会变小?

artificial-intelligence - 随机化神经网络输入顺序的影响

python - 在 MLPClassification Python 中实现 K 折交叉验证

python - 如何将 Pytorch 模型导入 MATLAB

python - tensorflow 中的三阶张量与二阶张量相乘

python - Keras Conv1d 输入形状 : Error when checking input

python - 使用带彩色框的 matplotlib 在绘图中显示图像

python - 将独立循环分解为并行线程/进程的简单且最简单的方法

machine-learning - 在caffe中记录权重和偏差

python - 如何在 Django 中将查询参数动态设置为 request.GET