softmax计算公式:
Softmax是机器学习中一个非常重要的工具,他可以兼容 logistics 算法、可以独立作为机器学习的模型进行建模训练、还可以作为深度 学习的激励函数。
softmax的作用简单的说就计算一组数值中每个值的占比,公式一般性描述为:
设一共有个用数值表示的分类
,其中
表示分类的个数。那么softmax
公式softmax的代码实现:
import numpy as np import math def softmax(inMatrix): """ softmax计算公式函数 :param inMatrix: 矩阵数据 :return: """ m,n = np.shape(inMatrix) #得到m,n(行,列) outMatrix = np.mat(np.zeros((m,n))) #mat生成数组 soft_sum = 0 for idx in range(0,n): outMatrix[0,idx] = math.exp(inMatrix[0,idx]) #求幂运算,取e为底的指数计算变成非负 soft_sum +=outMatrix[0,idx] #求和运算 for idx in range(0,n): outMatrix[0,idx] = outMatrix[0,idx] /soft_sum #然后除以所有项之后进行归一化 return outMatrix a = np.array([[1,2,1,2,1,1,3]]) print(softmax(a))
输出结果如下:
[[0.05943317 0.16155612 0.05943317 0.16155612 0.05943317 0.05943317
0.43915506]]
原文:https://www.cnblogs.com/gary-li/p/10878659.html