我正在尝试一个基本的平均示例,但是验证和损失不匹配,如果增加训练时间,网络将无法收敛。我正在训练一个具有2个隐藏层的网络,每个隐含层的宽度为[0,9]的三个整数,每500个单位宽,学习速率为1e-1,Adam,批处理大小为1,并且辍学3000次迭代,并验证每个100次迭代。如果标签和假设之间的绝对差小于阈值,则在此处将阈值设置为1,我认为这是正确的。有人可以让我知道这是损失函数的选择问题,Pytorch的问题还是我在做的事情。以下是一些情节:
val_diff = 1
acc_diff = torch.FloatTensor([val_diff]).expand(self.batch_size)
验证期间循环100次:
num_correct += torch.sum(torch.abs(val_h - val_y) < acc_diff)
在每个验证阶段之后附加:
validate.append(num_correct / total_val)
以下是(假设和标签)的一些示例:
[...(-0.7043088674545288, 6.0), (-0.15691305696964264, 2.6666667461395264),
(0.2827358841896057, 3.3333332538604736)]
我尝试了API中通常用于回归的六个损失函数:
torch.nn.L1Loss(size_average = False)
torch.nn.L1Loss()
torch.nn.MSELoss(size_average = False)
torch.nn.MSELoss()
torch.nn.SmoothL1Loss(size_average = False)
torch.nn.SmoothL1Loss()
谢谢。
网络代码:
class Feedforward(nn.Module):
def __init__(self, topology):
super(Feedforward, self).__init__()
self.input_dim = topology['features']
self.num_hidden = topology['hidden_layers']
self.hidden_dim = topology['hidden_dim']
self.output_dim = topology['output_dim']
self.input_layer = nn.Linear(self.input_dim, self.hidden_dim)
self.hidden_layer = nn.Linear(self.hidden_dim, self.hidden_dim)
self.output_layer = nn.Linear(self.hidden_dim, self.output_dim)
self.dropout_layer = nn.Dropout(p=0.2)
def forward(self, x):
batch_size = x.size()[0]
feat_size = x.size()[1]
input_size = batch_size * feat_size
self.input_layer = nn.Linear(input_size, self.hidden_dim).cuda()
hidden = self.input_layer(x.view(1, input_size)).clamp(min=0)
for _ in range(self.num_hidden):
hidden = self.dropout_layer(F.relu(self.hidden_layer(hidden)))
output_size = batch_size * self.output_dim
self.output_layer = nn.Linear(self.hidden_dim, output_size).cuda()
return self.output_layer(hidden).view(output_size)
培训代码:
def train(self):
if self.cuda:
self.network.cuda()
dh = DataHandler(self.data)
# loss_fn = nn.L1Loss(size_average=False)
# loss_fn = nn.L1Loss()
# loss_fn = nn.SmoothL1Loss(size_average=False)
# loss_fn = nn.SmoothL1Loss()
# loss_fn = nn.MSELoss(size_average=False)
loss_fn = torch.nn.MSELoss()
losses = []
validate = []
hypos = []
labels = []
val_size = 100
val_diff = 1
total_val = float(val_size * self.batch_size)
for i in range(self.iterations):
x, y = dh.get_batch(self.batch_size)
x = self.tensor_to_Variable(x)
y = self.tensor_to_Variable(y)
self.optimizer.zero_grad()
loss = loss_fn(self.network(x), y)
loss.backward()
self.optimizer.step()
最佳答案
您似乎误解了pytorch中图层的工作方式,这里有一些提示:
向前执行nn.Linear(...)
时,您将定义新层,而不是使用网络__init__
中预定义的层。因此,由于体重不断增加,它无法学到任何东西。
您无需在.cuda()
中调用net.forward(...)
,因为您已经通过调用train
在self.network.cuda()
中的gpu上复制了网络
理想情况下,net.forward(...)
输入应直接具有第一层的形状,因此您无需修改它。在这里您应该具有x.size() <=> Linear -- > (Batch_size, Features)
。
您的前锋应该接近:
def forward(self, x):
x = F.relu(self.input_layer(x))
x = F.dropout(F.relu(self.hidden_layer(x)),training=self.training)
x = self.output_layer(x)
return x
关于python - 回归损失函数不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45490265/