【发布时间】:2021-04-03 23:05:15
【问题描述】:
我用 numpy 实现了 softmax。 正如您在代码中看到的,我们有一个矩阵,我们想要获得该行的 softmax。 例如,第 1 行的软最大值是通过将 np.sum(np.exp([1,3,6,-3,1]) 除以 1,3,5,-3,1 来计算的 第 2 行的软最大值是找到 np.sum(np.exp([5,2,1,4,3]) 的软最大值。我该怎么做?
def softmax(x):
return np.exp(x)/np.sum(np.exp(x),axis=1)
x = np.array([[1,3,6,-3,1],
[5,2,1,4,3]])
print(softmax(x))
print(f"1:{softmax(x)[0]} sum : {np.sum(softmax(x)[0])}")
print(f"2:{softmax(x)[1]} sum : {np.sum(softmax(x)[1])}")
ValueError Traceback (most recent call last)
<ipython-input-261-eb8c9feae03f> in <module>
5
6
----> 7 print(softmax(x))
8 print(f"1:{softmax(x)[0]} sum : {np.sum(softmax(x)[0])}")
9 print(f"2:{softmax(x)[1]} sum : {np.sum(softmax(x)[1])}")
<ipython-input-261-eb8c9feae03f> in softmax(x)
1 def softmax(x):
----> 2 return np.exp(x)/np.sum(np.exp(x),axis=1)
3 x = np.array([[1,3,6,-3,1],
4 [5,2,1,4,3]])
5
ValueError: operands could not be broadcast together with shapes (2,5) (2,)
>
【问题讨论】:
-
仅供参考:SciPy 自 1.2.0 版起具有
softmax功能:scipy.special.softmax
标签: python-3.x numpy machine-learning deep-learning