具有多个值的 Tensor 的 bool 值不明确

bool value of Tensor with more than one value is ambiguous

我正在编写一个神经网络来进行回归,这是我的代码:

class Model(nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super().__init__()
        self.h1 = nn.Linear(input_size, hidden_size)
        self.h2 = nn.Linear(hidden_size, hidden_size)
        self.h3 = nn.Linear(hidden_size, num_classes)

    def forward(self, x):
        x = self.h1(x)
        x = Fuc.tanh(x)
        x = self.h2(x)
        x = Fuc.relu(x)
        x = self.h3(x)
        return x

model = Model(input_size=input_size, hidden_size=hidden_size, num_classes=num_classes)
opt = optim.Adam(params=model.parameters(), lr=learning_rate)


for epoch in range(1000):
    out = model(data)
    print('target', target)
    print('pred', out)
    loss = torch.nn.MSELoss(out, target)
    print('loss', loss)

    model.zero_grad()
    loss.backward()
    opt.step()

我的输入的形状为 (numberOfSample X 2),输出的形式为 [[2],[3],...],即列表列表,其中每个内部列表包含一个数字。

好的,现在我训练神经网络并得到这个错误:

       ...
       [-0.1753],
        [-0.1753],
        [-0.1753]], grad_fn=<AddmmBackward>)
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:1340: UserWarning: nn.functional.tanh is deprecated. Use torch.tanh instead.
  warnings.warn("nn.functional.tanh is deprecated. Use torch.tanh instead.")
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-26-38e8026bfe54> in <module>()
     68     print('target', target)
     69     print('pred', out)
---> 70     loss = torch.nn.MSELoss(out, target)
     71     print('loss', loss)
     72 

2 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/_reduction.py in legacy_get_string(size_average, reduce, emit_warning)
     34         reduce = True
     35 
---> 36     if size_average and reduce:
     37         ret = 'mean'
     38     elif reduce:

RuntimeError: bool value of Tensor with more than one value is ambiguous

问题源于调用 torch.nn.MSELoss(out, target),它是 MSELoss 的构造函数,它接受 size_averagereduce 作为第一个和第二个可选位置参数。

loss = torch.nn.MSELoss(out, target)

相反,您需要先创建一个 MSELoss 对象,然后将 outtarget 传递给该对象。

criterion = torch.nn.MSELoss()

for epoch in range(1000):
    out = model(data)
    loss = criterion(out, target)
    loss.backward()