RuntimeError:/pytorch/aten/src/THCUNN/generic/ClassNLLCriterion.cu:15____ 不支持多目标
Posted
技术标签:
【中文标题】RuntimeError:/pytorch/aten/src/THCUNN/generic/ClassNLLCriterion.cu:15____ 不支持多目标【英文标题】:RuntimeError: multi-target not supported at /pytorch/aten/src/THCUNN/generic/ClassNLLCriterion.cu:15____ 【发布时间】:2021-05-03 17:37:33 【问题描述】:我面临这个错误
我的输入是340的二进制向量,目标是8的二进制向量,对于'"
loss = criterion(outputs, stat_batch)
,我得到了outputs.shape
= [64,8] 和stat_batch.shape
=[64,8]
这是模型
class MMP(nn.Module):
def __init__(self, M=1):
super(MMP, self).__init__()
# input layer
self.layer1 = nn.Sequential(
nn.Conv1d(340, 256, kernel_size=1, stride=1, padding=0),
nn.ReLU())
self.layer2 = nn.Sequential(
nn.Conv1d(256, 128, kernel_size=1, stride=1, padding=0),
nn.ReLU())
self.layer3 = nn.Sequential(
nn.Conv1d(128, 64, kernel_size=1, stride=1, padding=0),
nn.ReLU())
self.drop1 = nn.Sequential(nn.Dropout())
self.batch1 = nn.BatchNorm1d(128)
# LSTM
self.lstm1=nn.Sequential(nn.LSTM(
input_size=64,
hidden_size=128,
num_layers=2,
bidirectional=True,
batch_first= True))
self.fc1 = nn.Linear(128*2,8)
self.sof = nn.Softmax(dim=-1)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = self.layer3(out)
out = self.drop1(out)
out = out.squeeze()
out = out.unsqueeze(0)
#out = out.batch1(out)
out,_ = self.lstm1(out)
print("lstm",out.shape)
out = self.fc1(out)
out =out.squeeze()
#out = out.squeeze()
out = self.sof(out)
return out
#traiin_model
criterion = nn.CrossEntropyLoss()
if CUDA:
criterion = criterion.cuda()
optimizer = optim.SGD(model.parameters(), lr=LEARNING_RATE, momentum=0.9)
for epoch in range(N_EPOCHES):
tot_loss=0
# Training
for i, (seq_batch, stat_batch) in enumerate(training_generator):
# Transfer to GPU
seq_batch, stat_batch = seq_batch.to(device), stat_batch.to(device)
print(i)
print(seq_batch)
print(stat_batch)
optimizer.zero_grad()
# Model computation
seq_batch = seq_batch.unsqueeze(-1)
outputs = model(seq_batch)
if CUDA:
loss = criterion(outputs, stat_batch).float().cuda()
else:
loss = criterion(outputs.view(-1), stat_batch.view(-1))
print(f"Epoch: epoch,number: i, loss:loss.item()...\n\n")
tot_loss += loss.item(print(f"Epoch: epoch,file_number: i, loss:loss.item()...\n\n"))
loss.backward()
optimizer.step()
【问题讨论】:
【参考方案1】:您的目标stat_batch
的形状必须为(64,)
,因为nn.CrossEntropyLoss
接受类索引,不是单热编码。
要么适当地构造你的标签张量,要么改用stat_batch.argmax(axis=1)
。
【讨论】:
标签已经是长张量,我尝试了 stat_batch.argmax(axis=1) 但给了我一个错误,说 ''' loss = criteria(outputs, stat_batch.argmax(axis=1)) TypeError : argmax() 得到了一个意外的关键字参数 'axis'''' “标签已经是长张量” 没关系,它需要是一维的,而不是多维的。您必须运行旧版本的 PyTorch:尝试stat_batch.argmax(dim=1)
,或者只是 stat_batch.argmax(1)
。
非常感谢。是的,它有效,但它仍然具有形状(64,8)。我在 1.99 附近也有很高的损失。你能告诉我绿色复选标记在哪里吗?以上是关于RuntimeError:/pytorch/aten/src/THCUNN/generic/ClassNLLCriterion.cu:15____ 不支持多目标的主要内容,如果未能解决你的问题,请参考以下文章
RuntimeError: tf.placeholder() 与急切执行不兼容
RuntimeError:预期的标量类型 Double 但发现 Float
multiprocessing进程开发RuntimeError