In [22]:
import numpy as np
import matplotlib.pyplot as plt
def softmax(x):
#转换成numpy数组
x=np.array(x)
#求e的x次幂
x=np.exp(x)
print("e的x次幂是",x)
print("x的维度是",x.ndim)
if x.ndim==1:
sumcol=sum(x)
for i in range(x.size):
x[i] = x[i]/float(sumcol)
elif x.ndim>1:
sumcol = x.sum(axis = 0)
for row in x:
for i in range(row.size):
row[i] = row[i]/float(sumcol[i])
return x
#测试数据
scores = [3.0,1.0, 0.2]
print("测试结果是",softmax(scores))
#图像化展示
softmax_inputs = np.arange(-10,10)
print("softmax函数输入是{}".format(softmax_inputs))
softmax_outputs=softmax(softmax_inputs)
print("softmax函数输出是{}".format(softmax_outputs))
#将输入和输出绘制出来
plt.plot(softmax_inputs,softmax_outputs)
plt.xlabel("softmax_inputs")
plt.ylabel("softmax_outputs")
plt.show()
In [24]:
#实现方式2
import numpy as np
def softmax(x):
return np.exp(x)/np.sum(np.exp(x),axis=0)
#测试结果
scores = [3.0,1.0, 0.2]
print(softmax(scores))