用于多分類,直接寫标簽序号就可以: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,此時可