我在实现以下功能时遇到困难。
假设我们已经训练了一个网络模型,我想从输出层反向传播到输入层(不是第一层)以获得一个新的输入数据。想知道pytorch里面有没有什么功能或者其他已有的功能可以实现这个功能,在pytorch教程里没找到相关的功能。
答案 0 :(得分:1)
如果你想要输入的梯度w.r.t,你可以简单地从.grad
中获取:
x.requires_grad_(True) # explicitly ask pytorch to estimate the gradient w.r.t x
# forward pass:
pred = model(x) # make a prediction
loss = criterion(pred, y) # compute the loss
# backward pass - compute gradients:
loss.bacward()
# now you have access to the gradient of loss w.r.t the input:
x_grad = x.grad
如果您有兴趣检查特定层的梯度,则需要使用 hooks。