python | 实现带Temperature的SoftMax(knowledge distillation)

写在前面

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

在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一些;

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容