Python 如何向量化多维矩阵的Softmax概率
我正试图通过斯坦福cs244n课程的考试。问题1b强烈建议对Softmax功能进行优化。我设法得到了N维向量的Softmax。我还得到了MxN维矩阵的Softmax,但在列中使用了for循环。我有以下代码:Python 如何向量化多维矩阵的Softmax概率,python,performance,numpy,vectorization,softmax,Python,Performance,Numpy,Vectorization,Softmax,我正试图通过斯坦福cs244n课程的考试。问题1b强烈建议对Softmax功能进行优化。我设法得到了N维向量的Softmax。我还得到了MxN维矩阵的Softmax,但在列中使用了for循环。我有以下代码: def softmax(x): orig_shape = x.shape # Matrix if len(x.shape) > 1: softmax = np.zeros(orig_shape) for i,col in enu
def softmax(x):
orig_shape = x.shape
# Matrix
if len(x.shape) > 1:
softmax = np.zeros(orig_shape)
for i,col in enumerate(x):
softmax[i] = np.exp(col - np.max(col))/np.sum(np.exp(col - np.max(col)))
# Vector
else:
softmax = np.exp(x - np.max(x))/np.sum(np.exp(x - np.max(x)))
return softmax
我可以实现一个更优化的矩阵实现吗?您可以尝试使用
np。沿轴应用,\u
,您必须指定要执行代码的轴(在您的情况下,轴=1
)。
下面是一个工作示例:
In [1]: import numpy as np
In [2]: def softmax(x):
...: orig_shape = x.shape
...:
...: # Matrix
...: if len(x.shape) > 1:
...: softmax = np.zeros(orig_shape)
...: for i,col in enumerate(x):
...: softmax[i] = np.exp(col - np.max(col))/np.sum(np.exp(col - np.max(col)))
...: # Vector
...: else:
...: softmax = np.exp(x - np.max(x))/np.sum(np.exp(x - np.max(x)))
...: return softmax
...:
In [3]: def softmax_vectorize(x):
...: return np.exp(x - np.max(x))/np.sum(np.exp(x - np.max(x)))
...:
In [4]: X = np.array([[1, 0, 0, 4, 5, 0, 7],
...: [1, 0, 0, 4, 5, 0, 7],
...: [1, 0, 0, 4, 5, 0, 7]])
In [5]: print softmax(X)
[[ 2.08239574e-03 7.66070581e-04 7.66070581e-04 4.18260365e-02
1.13694955e-01 7.66070581e-04 8.40098401e-01]
[ 2.08239574e-03 7.66070581e-04 7.66070581e-04 4.18260365e-02
1.13694955e-01 7.66070581e-04 8.40098401e-01]
[ 2.08239574e-03 7.66070581e-04 7.66070581e-04 4.18260365e-02
1.13694955e-01 7.66070581e-04 8.40098401e-01]]
In [6]: print np.apply_along_axis(softmax_vecorize, axis=1, arr=X)
[[ 2.08239574e-03 7.66070581e-04 7.66070581e-04 4.18260365e-02
1.13694955e-01 7.66070581e-04 8.40098401e-01]
[ 2.08239574e-03 7.66070581e-04 7.66070581e-04 4.18260365e-02
1.13694955e-01 7.66070581e-04 8.40098401e-01]
[ 2.08239574e-03 7.66070581e-04 7.66070581e-04 4.18260365e-02
1.13694955e-01 7.66070581e-04 8.40098401e-01]]
用于相关的,包括通用尺寸数的N阵列-
exp_max = np.exp(x - np.max(x,axis=-1,keepdims=True))
out = exp_max/np.sum(exp_max,axis=-1,keepdims=True)
谢谢你的回答。我把你的回答标记为答案,因为作业建议看广播。