我正在编写一个神经网络来进行回归,这是我的代码:
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_average
和reduce
作为第一和第二个可选位置参数。
loss = torch.nn.MSELoss(out, target)
相反,您需要先创建一个MSELoss
对象,然后将out
和target
传递给该对象。
criterion = torch.nn.MSELoss()
for epoch in range(1000):
out = model(data)
loss = criterion(out, target)
loss.backward()