python3实现softmax+函数曲线绘制绘制softmax函数曲线 + python3实现
import numpy as np
# 实现⽅法1
def softmax(x):
p(x)/np.p(x), axis=0)
# 是想⽅法2
def softmax2(x):
"""Compute softmax values for each sets of scores in x."""
x = np.array(x)
x = np.exp(x)
if x.ndim ==1:
sumcol =sum(x)
for i in range(x.size):
x[i]= x[i]/float(sumcol)
if 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
data1 =[1]
data2 =[0]
data3 =[1,2,3,4]
data4 =[[1,5,7,3],[2,3,4,5]]
data5 =[[[1,2],[5,3]],[[9,18],[4,22]]]
print(softmax(data1),"\n")
print(softmax(data2),"\n")
print(softmax(data3),"\n")
print(softmax(data4),"\n")
print(softmax(data5),"\n")
print(softmax2(data1),"\n")
print(softmax2(data2),"\n")
print(softmax2(data3),"\n")
print(softmax2(data4),"\n")
print(softmax2(data5),"\n")
输出
[ 1.]
[ 1.]
[ 0.0320586 0.08714432 0.23688282 0.64391426]
[[ 0.26894142 0.88079708 0.95257413 0.11920292]
[ 0.73105858 0.11920292 0.04742587 0.88079708]]
[[[ 3.35350130e-04 1.12535162e-07]
[ 7.31058579e-01 5.60279641e-09]]
[[ 9.99664650e-01 9.99999887e-01]
[ 2.68941421e-01 9.99999994e-01]]]
[ 1.]
[ 1.]
[ 0.0320586 0.08714432 0.23688282 0.64391426]
[[ 0.26894142 0.88079708 0.95257413 0.11920292]
[ 0.73105858 0.11920292 0.04742587 0.88079708]]
Traceback (most recent call last):
File "/Users/hupeng/Documents/mlNotes/softmax.py", line 41, in <module>
print(softmax2(data5) ,"\n")
File "/Users/hupeng/Documents/mlNotes/softmax.py", line 21, in softmax2
row[i] = row[i]/float(sumcol[i])
TypeError: only length-1 arrays can be converted to Python scalars
最后⼀⾏报错了, 因为⽅法数组越界了
softmax 是将⼀些列数据归⼀化到0-1之间, 所以运⽤场景中必定会是⼀维数据或是变向的⼀维数据
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-10,10,200)
y = softmax(x)
print(x,y)
plt.plot(x,y)
linspace函数pythonplt.show()
绘制⼀下曲线,结果如图
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论