我使用numpy实现了softmax函数。如您在代码中所见,我们有一个矩阵,我们想要计算每行的softmax。例如,第一行的softmax是通过将np.sum(np.exp([1,3,6,-3,1]))除以1,3,5,-3,1来计算的。第二行的softmax是通过计算np.sum(np.exp([5,2,1,4,3]))的softmax来实现的。我应该如何做呢?
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,) >
回答:
这里的问题是sum(exp(x), axis=1)
返回一个一维的numpy数组。将其更改为sum(esp(x), axis=1, keepdims=True)
可以避免numpy自动丢弃一个维度。
def softmax(x): return np.exp(x)/np.sum(np.exp(x),axis=1, keepdims=True)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])}")