softmax函数注意事项及代码实现

import numpy as np

def softmax(x):
    """ softmax function """
    
    # assert(len(x.shape) > 1, "dimension must be larger than 1")
    # print(np.max(x, axis = 1, keepdims = True)) # axis = 1, 行
    
    x -= np.max(x, axis = 1, keepdims = True) #为了稳定地计算softmax概率, 一般会减掉最大的那个元素
    
    print("减去行最大值 :\n", x)
    
    x = np.exp(x) / np.sum(np.exp(x), axis = 1, keepdims = True)
    
    return x
    
x = np.random.randint(low = 1, high = 5, size = (2, 3)) #生成一个2x3的矩阵,取值范围在1-5之间
print("原始 :\n", x)

x_ = softmax(x)
print("变换后 :\n", x_)


softmax(x)_i = \frac{e^{x_i}}{\sum_j e^{x_j}}

需要注意的地方是:

  1. 为了稳定地计算softmax概率, 一般会减掉最大的那个元素
  2. numpy里面axis = 1指的是行,axis = 0才是列
  3. np.exp(x)对矩阵或者更高维运算的话,会对矩阵内每个值直接取指数

结果如下:

猜你喜欢

转载自blog.csdn.net/yyhhlancelot/article/details/83142255
今日推荐