【发布时间】:2021-12-17 09:37:21
【问题描述】:
我正在学习钩子并使用二值化神经网络。问题是有时我的梯度在反向传递中为 0。我正在尝试用某个值替换这些渐变。
假设我有以下网络
import torch
import torch.nn as nn
import torch.optim as optim
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.fc1 = nn.Linear(1, 2)
self.fc2 = nn.Linear(2, 3)
self.fc3 = nn.Linear(3, 1)
def forward(self, x):
x = self.fc1(x)
x = torch.relu(x)
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Model()
opt = optim.Adam(net.parameters())
还有一些功能
features = torch.rand((3,1))
我可以正常训练它:
for i in range(10):
opt.zero_grad()
out = net(features)
loss = torch.mean(torch.square(torch.tensor(5) - torch.sum(out)))
loss.backward()
opt.step()
如何附加一个钩子函数,该函数将具有以下条件用于向后传递(对于每一层):
-
如果单层的所有梯度都为0,则改为1.0。
-
如果其中一个梯度为 0,但至少有一个梯度不为 0,则将其更改为 0.5。
【问题讨论】:
标签: python machine-learning pytorch backpropagation