pytorch“ log_softmax_lastdim_kernel_impl”未针对“ torch.LongTensor”实现

时间:2019-08-21 11:34:15

标签: python pytorch

我正在尝试使用自己的数据集根据https://github.com/bentrevett/pytorch-sentiment-analysis/blob/master/5%20-%20Multi-class%20Sentiment%20Analysis.ipynb对文本进行分类。我的数据集是句子的csv和与之相关的类。有6种不同的类别:

sent                      class
'the fox is brown'        animal
'the house is big'        object
'one water is drinkable'  water
...

运行时:

N_EPOCHS = 5

best_valid_loss = float('inf')

for epoch in range(N_EPOCHS):

    start_time = time.time()
    print(start_time)
    train_loss, train_acc = train(model, train_iterator, optimizer, criterion)
    print(train_loss.type())
    print(train_acc.type())
    valid_loss, valid_acc = evaluate(model, valid_iterator, criterion)

    end_time = time.time()

    epoch_mins, epoch_secs = epoch_time(start_time, end_time)

    if valid_loss < best_valid_loss:
        best_valid_loss = valid_loss
        torch.save(model.state_dict(), 'tut5-model.pt')

    print(f'Epoch: {epoch+1:02} | Epoch Time: {epoch_mins}m {epoch_secs}s')
    print(f'\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}%')
    print(f'\t Val. Loss: {valid_loss:.3f} |  Val. Acc: {valid_acc*100:.2f}%')

,我收到以下错误消息

RuntimeError: "log_softmax_lastdim_kernel_impl" not implemented for 'torch.LongTensor'

指向:

<ipython-input-38-9c6cff70d2aa> in train(model, iterator, optimizer, criterion)
     14         print('pred'+ predictions.type())
     15         #batch.label = batch.label.type(torch.LongTensor)
---> 16         loss = criterion(predictions.long(), batch.label)**

此处https://github.com/pytorch/pytorch/issues/14224发布的解决方案建议我需要使用long / int。

我必须在.long()行添加**才能解决此较早的错误:

RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target'

具体的代码行是:

  def train(model, iterator, optimizer, criterion):
    epoch_loss = 0
    epoch_acc = 0

    model.train()

    for batch in iterator:

        optimizer.zero_grad()

        predictions = model(batch.text)
        print('pred'+ predictions.type())
        #batch.label = batch.label.type(torch.LongTensor)
        loss = criterion(predictions.long(), batch.label)**

        acc = categorical_accuracy(predictions, batch.label)

        loss.backward()

        optimizer.step()

        epoch_loss += loss.item()
        epoch_acc += acc.item()

    return epoch_loss / len(iterator), epoch_acc / len(iterator)

请注意,**最初是loss = criterion(predictions, batch.label)

还有其他解决此问题的建议吗?

2 个答案:

答案 0 :(得分:1)

criterion在您的notebook中定义为torch.nn.CrossEntropyLoss()。如CrossEntropyLoss的文档中所述,它期望模型为每个“ K”类返回概率值,并为地面标签提供相应的值作为输入。现在,概率值是浮点张量,而地面真相标签应该是代表一个类的长张量(类不能是浮点,例如2.3不能代表一个类)。因此:

loss = criterion(predictions, batch.label.long())

应该工作。

答案 1 :(得分:0)

如果使用gpu,而不是在损失标准下定义long类型,则可能应该在使用cuda之前定义它。我遇到同样的错误。解决了以下问题:

 # move data to GPU, if available
    if train_on_gpu:
        inp = inp.cuda()
        target = target.long()
        target=target.cuda()
    h = tuple([each.data for each in hidden])
    # perform backpropagation and optimization

    #zero accumulated gradient
    rnn.zero_grad()

    #getting out_put from model
    output,h = rnn(inp,h)
    #calculating loss and performing back_propagation

    loss = criterion(output.squeeze(), target)