gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:36:55 24 4
gpt4 key购买 nike

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

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()

关于pytorch - 具有多个值的 Tensor 的 bool 值不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61334483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com