softmax 原理
斯坦福大学CS224n课程中softmax的解释:
代码知识点
1、NumPy数组是一个多维数组对象,称为ndarray。数组的下标从0开始,同一个NumPy数组中所有元素的类型必须是相同的。
2、数组
数组(Array)是有序的元素序列。
若将有限个类型相同的变量的集合命名,那么这个名称为数组名。组成数组的各个变量称为数组的分量,也称为数组的元素,有时也称为下标变量。用于区分数组的各个元素的数字编号称为下标。
数组是在程序设计中,为了处理方便, 把具有相同类型的若干元素按有序的形式组织起来的一种形式。
这些有序排列的同类数据元素的集合称为数组。
3、数组与矩阵
矩阵(Matrix)是一个按照长方阵列排列的复数或实数集合,最早来自于方程组的系数及常数所构成的方阵。
矩阵是二维数据组成的
4、数组与矩阵的区别
矩阵中的元素只能是数字,而数组中的元素可以是字符或者字符串
矩阵是二维的,数组可以是一维的、多维的
矩阵显示时,元素之间无逗号;数组显示时,元素之间用逗号隔开
代码实现
import numpy
import math
def softmax(inMatrix):
m,n = numpy.shape(inMatrix) #m行,n列
outMatrix = numpy.mat(numpy.zeros((m,n))) #创建输出矩阵 通过numpy.mat
soft_sum = 0 #分母
for idx in range(0,n):
outMatrix[0,idx] = math.exp(inMatrix[0,idx])
soft_sum += outMatrix[0,idx]
for idx in range(0,n): #分子
outMatrix[0,idx] = outMatrix[0,idx] / soft_sum
return outMatrix
a = numpy.array([[0.2,0.5,0.1,0.1,0.1]]) #1x5的数组
a_softmax_output = softmax(a)
print(a_softmax_output)
输出结果
[[0.19745789 0.26654027 0.17866728 0.17866728 0.17866728]]
代码参考 Tensorflow 2.0深度学习从零开始学 王晓华著
其他参考
https://blog.csdn.net/lz_peter/article/details/84574716
https://blog.csdn.net/github_36669230/article/details/78038756
https://blog.csdn.net/weixin_44515978/article/details/107889672