赞
踩
softmax计算的概率分布:
p
(
x
i
)
=
e
x
i
∑
j
=
1
V
e
x
j
p\left(x_i\right)=\frac{e^{x_i}}{\sum_{j=1}^V e^{x_j}}
p(xi)=∑j=1Vexjexi
加入温度系数到softmax时:
p
(
x
i
)
=
e
x
i
T
∑
j
=
1
V
e
x
j
T
=
1
∑
j
=
1
V
e
x
j
−
x
i
T
p\left(x_i\right)=\dfrac{e^{\dfrac{x_i}{T}}}{\sum_{j=1}^V e^{\dfrac{x_j}{T}}} \\ =\frac{1}{\sum_{j=1}^V e^{\frac{x_{j}-x_i}{T}}}
p(xi)=∑j=1VeTxjeTxi=∑j=1VeTxj−xi1
简单分析:temperature从0到1的数值,当数值越大,将上式的分子分母同时除以分子,就可以发现temperture越大则总体值越大。
import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt criterion = nn.CrossEntropyLoss() x = torch.Tensor([[1, 2, 3 ,4]]) y = torch.LongTensor([3]) # 折线图横坐标 x_ = [i for i in range(len(x.squeeze(0)))] t = [1, 0.5, 0.1] col = ['red', 'blue', 'green'] for i in range(len(t)): temp = t[i] out = F.softmax(x / temp, dim=1) loss = criterion(out, y) y_ = out.squeeze(0).tolist() plt.plot(x_, y_, color=col[i], linestyle='dashed', linewidth=2, \ marker='o', markerfacecolor='red', markersize=8, label = "temp:" + str(temp)) print("softmax概率值:", out, "\nloss:", loss, "\n") # 图例放在右上角 plt.legend(loc = "upper left") plt.title("diffterent temperature") plt.xlabel("xlabel") plt.ylabel("logits") plt.show()
随着T的减少,softmax输出各类别的概率方差越大,而T越大则越相对平滑,印证了刚才的分析。
[1] 谈谈softmax中常出现的温度系数 T (τ)
[2] LLM Parameters Demystified: Getting The Best Outputs from Language AI
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。