python实现列表的softmax函数计算
目录
python实现列表的softmax函数计算
import numpy as np
def softmax(x):
# 计算每行的最大值
row_max = np.max(x)
# 每行元素都需要减去对应的最大值,否则求exp(x)会溢出,导致inf情况
x = x - row_max
# 计算e的指数次幂
x_exp = np.exp(x)
x_sum = np.sum(x_exp)
s = x_exp / x_sum
return s
s=softmax([1,2,3])
print(s)