import torch
import torch.nn as nn
import math
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)
#
# first = [0, 0, 0]
# for i in range(3):
# first[i] = -output[i][label[i]]
# second = [0, 0, 0]
# for i in range(3):
# for j in range(5):
# second[i] += math.exp(output[i][j])
# res = 0
# for i in range(3):
# res += (first[i] + math.log(second[i]))
# print("自己的计算结果:")
# print(res/3)
######################
# labels = torch.tensor([1, 0, 0, 3, 0, 0, 3, 0, 2, 3, 1, 3, 3, 1, 3, 3])
# outputs = torch.tensor([[0.2522, 0.2542, 0.2486, 0.2449],
# [0.2493, 0.2600, 0.2470, 0.2437],
# [0.2512, 0.2558, 0.2482, 0.2448],
# [0.2512, 0.2567, 0.2480, 0.2441],
# [0.2485, 0.2657, 0.2436, 0.2423],
# [0.2501, 0.2662, 0.2442, 0.2395],
# [0.2506, 0.2565, 0.2474, 0.2454],
# [0.2483, 0.2627, 0.2452, 0.2438],
# [0.2509, 0.2570, 0.2482, 0.2440],
# [0.2449, 0.2772, 0.2386, 0.2393],
# [0.2508, 0.2569, 0.2487, 0.2436],
# [0.2520, 0.2547, 0.2481, 0.2452],
# [0.2470, 0.2730, 0.2392, 0.2407],
# [0.2515, 0.2562, 0.2475, 0.2448],
# [0.2475, 0.2714, 0.2430, 0.2381],
# [0.2455, 0.2972, 0.2275, 0.2297]])
# loss = criterion(outputs, labels)
# print(loss)
转载链接:https://blog.csdn.net/ft_sunshine/article/details/92074842