我想在pytorch中创建模型,但是我不能 计算损失。 总是返回张量的布尔值 一个值不明确 实际上,我运行示例代码,它可以工作。
loss = CrossEntropyLoss()
input = torch.randn(8, 5)
input
target = torch.empty(8,dtype=torch.long).random_(5)
target
output = loss(input, target)
这是我的代码,
################################################################################
##
##
import torch
from torch.nn import Conv2d, MaxPool2d, Linear, CrossEntropyLoss, MultiLabelSoftMarginLoss
from torch.nn.functional import relu, conv2d, max_pool2d, linear, softmax
from torch.optim import adadelta
##
##
## Train
Train = {}
Train["Image"] = torch.rand(2000, 3, 76, 76)
Train["Variable"] = torch.rand(2000, 6)
Train["Label"] = torch.empty(2000, dtype=torch.long).random_(2)
##
##
## Valid
Valid = {}
Valid["Image"] = torch.rand(150, 3, 76, 76)
Valid["Variable"] = torch.rand(150, 6)
Valid["Label"] = torch.empty(150, dtype=torch.long).random_(2)
################################################################################
##
##
## Model
ImageTerm = Train["Image"]
VariableTerm = Train["Variable"]
Pip = Conv2d(in_channels=3, out_channels=32, kernel_size=(3,3), stride=1, padding=0)(ImageTerm)
Pip = MaxPool2d(kernel_size=(2,2), stride=None, padding=0)(Pip)
Pip = Conv2d(in_channels=32, out_channels=64, kernel_size=(3,3), stride=1, padding=0)(Pip)
Pip = MaxPool2d(kernel_size=(2,2), stride=None, padding=0)(Pip)
Pip = Pip.view(2000, -1)
Pip = torch.cat([Pip, VariableTerm], 1)
Pip = Linear(in_features=18502, out_features=1000 , bias=True)(Pip)
Pip = Linear(in_features=1000, out_features=2 , bias=True)(Pip)
##
##
## Loss
Loss = CrossEntropyLoss(Pip, Train["Label"])
错误在于 Loss = CrossEntropyLoss(Pip,Train [“ Label”]), 谢谢。
答案 0 :(得分:5)
在最小的示例中,您将创建类“ CrossEntropyLoss”的对象“损失”。该对象能够将您的损失计算为
loss(input, target)
但是,在实际代码中,您尝试创建对象“ Loss”,同时将Pip和标签传递给“ CrossEntropyLoss”类构造函数。 相反,请尝试以下操作:
loss = CrossEntropyLoss()
loss(Pip, Train["Label"])
答案 1 :(得分:1)
您不能直接使用类CrossEntropyLoss
。您应该在使用它之前实例化该类。
原始代码:
loss = CrossEntropyLoss(Pip, Train["Label"])
应替换为:
loss = CrossEntropyLoss()
loss(Pip, Train["Label"])
答案 2 :(得分:1)
第一次实例化损失
L = CrossEntropyLoss()
然后计算损失
L(y_pred, y_true)
这将修复错误。