【发布时间】:2018-08-20 21:15:23
【问题描述】:
在forward 方法中,我只执行一组torch.add(torch.bmm(x, exp_w), self.b),然后我的模型会正确返回传播。当我添加另一层时 - torch.add(torch.bmm(out, exp_w2), self.b2) - 然后梯度不会更新,模型也不会学习。如果我将激活函数从nn.Sigmoid 更改为nn.ReLU,那么它适用于两层。
现在一直在思考这个问题,但不明白为什么它不能与 nn.Sigmoid 一起工作。
我尝试了不同的学习率、损失函数和优化函数,但似乎没有任何组合有效。当我将训练前后的权重相加时,它们是相同的。
代码:
class MyModel(nn.Module):
def __init__(self, input_dim, output_dim):
torch.manual_seed(1)
super(MyModel, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
hidden_1_dimentsions = 20
self.w = torch.nn.Parameter(torch.empty(input_dim, hidden_1_dimentsions).uniform_(0, 1))
self.b = torch.nn.Parameter(torch.empty(hidden_1_dimentsions).uniform_(0, 1))
self.w2 = torch.nn.Parameter(torch.empty(hidden_1_dimentsions, output_dim).uniform_(0, 1))
self.b2 = torch.nn.Parameter(torch.empty(output_dim).uniform_(0, 1))
def activation(self):
return torch.nn.Sigmoid()
def forward(self, x):
x = x.view((x.shape[0], 1, self.input_dim))
exp_w = self.w.expand(x.shape[0], self.w.size(0), self.w.size(1))
out = torch.add(torch.bmm(x, exp_w), self.b)
exp_w2 = self.w2.expand(out.shape[0], self.w2.size(0), self.w2.size(1))
out = torch.add(torch.bmm(out, exp_w2), self.b2)
out = self.activation()(out)
return out.view(x.shape[0])
【问题讨论】: