1. softmax

softmax 公式

softmax(xi)=exi∑j(exj)softmax(x_i) = \frac{e^{x_i}}{\sum_j(e^{x_j})}softmax(xi)=j(exj)exi

代码

import numpy as np
 
def softmax(x, axis = 1):
    assert (len(x.shape) > 1, "dimension must be larger than 1")
    x -= np.max(x, axis=axis, keepdims=True)
    x = np.exp(x) / np.sum(np.exp(x), axis=axis, keepdims=True)
    return x

注意:

为了稳定的计算softmax概率,防止exe^xex过大,出现nannannan的情况,会选择减去其最大值。

Logo

一站式 AI 云服务平台

更多推荐