美文网首页
python | 实现带Temperature的SoftMax(

python | 实现带Temperature的SoftMax(

作者: 与阳光共进早餐 | 来源:发表于2019-02-15 19:43 被阅读0次

写在前面

未经允许,不得转载,谢谢~~

在Hiton大佬的知识蒸馏文章中提出用带T(Temperature)的softmax,来达到在各个类上的概率分布更加soft的效果。

这里主要是简单实现了一下。

一 具体实现

  • 参照from sklearn.utils.extmath import softmax中的实现方法;
  • 其实就是对每个输入中的x都除以T即可。
  • 具体代码:
def softmax_T(X, T=1,copy=True):
    """
    Calculate the softmax function (Tempoarl T).

    The softmax function is calculated by
    np.exp(X/T) / np.sum(np.exp(X/T), axis=1)

    This will cause overflow when large values are exponentiated.
    Hence the largest value in each row is subtracted from each data
    point to prevent this.

    Parameters
    ----------
    X : array-like, shape (M, N)
        Argument to the logistic function

    copy : bool, optional
        Copy X or not.

    Returns
    -------
    out : array, shape (M, N)
        Softmax function evaluated at every point in x
    """
    X = X/T
    if copy:
        X = np.copy(X)
    max_prob = np.max(X, axis=1).reshape((-1, 1))
    X -= max_prob
    np.exp(X, X)
    sum_prob = np.sum(X, axis=1).reshape((-1, 1))
    X /= sum_prob
    return X

二 实验验证

  • 代码:
inputs = np.array([[3.0,4,20,6],[1,2,3,4]])
print(inputs.shape)
output1 = softmax(inputs)
print (output1)
output2 = softmax_T(inputs,T=1)
print (output2)
output3 = softmax_T(inputs,T=4)
print (output3)
  • 结果:


  • 可以看到T取值为1的情况下与原来的softmax得到的结果无异;

  • T取4的情况下,获取到的概率分布会更加soft一些;

比较简单,就当记录一下吧~~

相关文章

网友评论

      本文标题:python | 实现带Temperature的SoftMax(

      本文链接:https://www.haomeiwen.com/subject/hsgmeqtx.html