首先,简单介绍一下softmax函数。sofamax函数又称为归一化指数函数,它是常用的归一化处理的方式之一。与其他归一化方式不同的地方在于,softmax函数实际上是有限项离散概率分布的梯度对数归一化。其作用在于,它能将一个含任意实数的K维向量Z"压缩“”至另一个K维实向量α(z)中,使得数据集中的每一个元素的值都变换至(0,1)之间,而且变换后的所有元素的和等于1。了解更多可以点击这里
softmax函数的通常形式为:
下面通过python语言来编程实现softmax函数
import numpy as np
import math
'''
定义softmax函数实现对列表元素的归一化处理
'''
def softmax(inputMatrix):
r, c = np.shape(inputMatrix)
outputMatrix = np.mat(np.zeros((r, c)))
soft_sum = 0
for idx in range(0, c):
outputMatrix[0, idx] = math.exp(inputMatrix[0, idx])
soft_sum += outputMatrix[0, idx]
for idx in range(0, c):
outputMatrix[0, idx] = outputMatrix[0, idx]/soft_sum
return outputMatrix
a = np.array([[11, 22, 17, 28, 12, 19, 37, 48, 52, 63, 69, 75, 27, 56, 98]])
print(a)
print(softmax(a))
- 运行结果如下: