我试图通过一个实际的例子来理解 CrossEntropyLoss 中的权重是如何工作的。所以我首先运行标准 PyTorch 代码,然后手动运行。但损失并不相同。
from torch import nn
import torch
softmax=nn.Softmax()
sc=torch.tensor([0.4,0.36])
loss = nn.CrossEntropyLoss(weight=sc)
input = torch.tensor([[3.0,4.0],[6.0,9.0]])
target = torch.tensor([1,0])
output = loss(input, target)
print(output)
>>1.7529
Run Code Online (Sandbox Code Playgroud)
现在进行手动计算,首先对输入进行 softmax:
print(softmax(input))
>>
tensor([[0.2689, 0.7311],
[0.0474, 0.9526]])
Run Code Online (Sandbox Code Playgroud)
然后正确类别概率的负对数并乘以各自的权重:
((-math.log(0.7311)*0.36) - (math.log(0.0474)*0.4))/2
>>
0.6662
Run Code Online (Sandbox Code Playgroud)
我在这里缺少什么?
我有一系列令牌,每个令牌都有一个注意力权重。现在,我想使用特定颜色的阴影来可视化令牌。例如,蓝色的阴影,根据权重从最浅到最深。
我知道可以绘制一条线或曲线来创建阴影。但是,如何显示/打印令牌/单词?