코드를 실행할 축 (axis=1
)을 지정해야하는 np.apply_along_axis
을 사용할 수 있습니다. 다음은 작업 예입니다 : 관련 ufuncs
에 NumPy broadcasting
를 사용
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]]
답변 해 주셔서 감사합니다. 과제를 방송 할 것을 제안했기 때문에 답변을 답장으로 표시했습니다. –