softmax函数用来解决概率计算中概率结果大占绝对优势的问题。比如:函数计算结果中有两个值a和b,假如a>b,如果以大小进行取值的话,那么a将永远被选用,而b则永远不会被选用。但是实际中,小概率事件有时也是会被选用的,只是可能性比较小罢了,softmax函数则解决了这个问题。
import numpy as np
import math
# 编写一个计算softmax的函数
def softmax(inmatrix):
m, n = np.shape(inmatrix)
outmatrix = np.mat(np.zeros((m, n)))
soft_sum = 0
for idx in range(n):
outmatrix[0, idx] = math.exp(inmatrix[0, idx])
soft_sum += outmatrix[0, idx]
for idx in range(n):
outmatrix[0, idx] = outmatrix[0, idx] / soft_sum
return outmatrix
a = np.array([[1, 2, 1, 2, 1, 1, 3]])
softmax(a)