天天看点

nn.CrossEntropyLoss()

用于多分类,直接写标签序号就可以:0,1,2.

预测需要维度与标签长度一致。

import torch
import torch.nn as nn
import math
criterion = nn.CrossEntropyLoss()
output = torch.randn(3, 5, requires_grad=True)
label = torch.empty(3, dtype=torch.long).random_(5)
loss = criterion(output, label)

print("网络输出为3个5类:")
print(output)
print("要计算loss的类别:")
print(label)
print("计算loss的结果:")
print(loss)
           

预测代码:log_softmax好像没有归一化,要不要好像没区别

output = model(img_arr)
        score = m_func.log_softmax(output, dim=1)
        _, match = torch.max(score.data, 1)


        index=match.item()
           
import torch
import torch.nn as nn
x_input=torch.randn(3,3)#随机生成输入 
print('x_input:\n',x_input) 
y_target=torch.tensor([1,2,0])#设置输出具体值 print('y_target\n',y_target)

#计算输入softmax,此时可