损失函数中的点张量不存在的不存在的pytorch梯度

时间:2019-07-01 15:57:10

标签: python machine-learning neural-network pytorch autograd

出于本MWE的目的,我尝试使用具有多个项的自定义损失函数来拟合线性回归。但是,在尝试通过用损失乘以权重向量来加权损失函数中的不同项时,我遇到了奇怪的行为。仅将损失相加即可达到预期效果;但是,当权重和损失点均出现时,反向传播会以某种方式破坏,并且损失函数不会减少。

我尝试在两个张量上启用和禁用require_grad,但是无法复制预期的行为。

import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt


# Hyper-parameters
input_size = 1
output_size = 1
num_epochs = 60
learning_rate = 0.001

# Toy dataset
x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168], 
                    [9.779], [6.182], [7.59], [2.167], [7.042], 
                    [10.791], [5.313], [7.997], [3.1]], dtype=np.float32)

y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573], 
                    [3.366], [2.596], [2.53], [1.221], [2.827], 
                    [3.465], [1.65], [2.904], [1.3]], dtype=np.float32)

# Linear regression model
model = nn.Linear(input_size, output_size)

# Loss and optimizer
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)  

def loss_fn(outputs, targets):
    l1loss = torch.norm(outputs - targets, 1)
    l2loss = torch.norm(outputs - targets, 2)

    # This works as expected
    # loss = 1 * l1loss + 1 * l2loss
    # Loss never changes, no matter what combination of
    # requires_grad I set
    loss = torch.dot(torch.tensor([1.0, 1.0], requires_grad=False),
            torch.tensor([l1loss, l2loss], requires_grad=True))
    return loss

# Train the model
for epoch in range(num_epochs):
    # Convert numpy arrays to torch tensors
    inputs = torch.from_numpy(x_train)
    targets = torch.from_numpy(y_train)

    # Forward pass
    outputs = model(inputs)
    loss = loss_fn(outputs, targets)

    # Backward and optimize
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if (epoch+1) % 5 == 0:
        print ('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))

# Plot the graph
predicted = model(torch.from_numpy(x_train)).detach().numpy()
plt.plot(x_train, y_train, 'ro', label='Original data')
plt.plot(x_train, predicted, label='Fitted line')
plt.legend()
plt.show()

预期结果:损失函数减小,并且线性回归拟合(请参见下面的输出)

Epoch [5/60], Loss: 7.9943
Epoch [10/60], Loss: 7.7597
Epoch [15/60], Loss: 7.6619
Epoch [20/60], Loss: 7.6102
Epoch [25/60], Loss: 7.4971
Epoch [30/60], Loss: 7.4106
Epoch [35/60], Loss: 7.3942
Epoch [40/60], Loss: 7.2438
Epoch [45/60], Loss: 7.2322
Epoch [50/60], Loss: 7.1012
Epoch [55/60], Loss: 7.0701
Epoch [60/60], Loss: 6.9612

实际结果:损失函数没有变化

Epoch [5/60], Loss: 73.7473
Epoch [10/60], Loss: 73.7473
Epoch [15/60], Loss: 73.7473
Epoch [20/60], Loss: 73.7473
Epoch [25/60], Loss: 73.7473
Epoch [30/60], Loss: 73.7473
Epoch [35/60], Loss: 73.7473
Epoch [40/60], Loss: 73.7473
Epoch [45/60], Loss: 73.7473
Epoch [50/60], Loss: 73.7473
Epoch [55/60], Loss: 73.7473
Epoch [60/60], Loss: 73.7473

我对为什么这样一个简单的操作打破了反向传播梯度感到困惑,如果有人对为什么这种方法不起作用有任何见解,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用torch.cat((loss1, loss2)),您是根据现有的破坏图表的张量创建新的Tensor。

无论如何,除非您试图概括损失函数,否则您不应该这样做,这是非常难以理解的。简单添加会更好