[英]Python, Numpy: Cannot assign the values of a numpy array to a column of a matrix
我是Python的新手,我想了解一個語法問題。 我有一個numpy的矩陣:
x = np.array([[1, 2, 3, 6],
[2, 4, 5, 6],
[3, 8, 7, 6]])
我想將Softmax函數應用於它的每一列。 該代碼非常簡單。 在不報告整個循環的情況下,假設我在第一列中做到了:
w = x[:,0] # select a column
w = np.exp(w) # compute softmax in two steps
w = w/sum(w)
x[:,0] = w # reassign the values to the original matrix
但是,不是將w: array([0.09003057, 0.24472847, 0.66524096])
的值分配給矩陣,而是將零列分配給矩陣,該矩陣返回:
np.array([[0, 2, 3, 6],
[0, 4, 5, 6],
[0, 8, 7, 6]])
這是為什么? 我該如何解決這個問題? 謝謝
矩陣的值類型為int
,在分配時,softmax值轉換為int
,因此為零。
像這樣創建矩陣:
x = np.array([[1, 2, 3, 6],
[2, 4, 5, 6],
[3, 8, 7, 6]]).astype(float)
現在,在分配softmax值之后:
w = x[:,0] # select a column
w = np.exp(w) # compute softmax in two steps
w = w/sum(w)
x[:,0] = w # reassign the values to the original matrix
x
出來是:
array([[0.09003057, 2., 3., 6.],
[0.24472847, 4., 5., 6.],
[0.66524096, 8., 7., 6.]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.