[英]Python, Numpy: Cannot assign the values of a numpy array to a column of a matrix
I'n new to Python, and there is a syntax problem I'm trying to understand. 我是Python的新手,我想了解一个语法问题。 I have a numpy matrix: 我有一个numpy的矩阵:
x = np.array([[1, 2, 3, 6],
[2, 4, 5, 6],
[3, 8, 7, 6]])
An I want to apply a Softmax function to each column of it. 我想将Softmax函数应用于它的每一列。 The code is pretty straightforward. 该代码非常简单。 Without reporting the whole loop, let's say I make it for the first column: 在不报告整个循环的情况下,假设我在第一列中做到了:
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
However, instead of the values of w: array([0.09003057, 0.24472847, 0.66524096])
, only a column of zeros is assigned to the matrix, that returns: 但是,不是将w: array([0.09003057, 0.24472847, 0.66524096])
的值分配给矩阵,而是将零列分配给矩阵,该矩阵返回:
np.array([[0, 2, 3, 6],
[0, 4, 5, 6],
[0, 8, 7, 6]])
Why is that? 这是为什么? How can I correct this problem? 我该如何解决这个问题? Thank you 谢谢
The type of values of your matrix is int
, and at the time of assigning, the softmax values are converted to int
, hence the zeros. 矩阵的值类型为int
,在分配时,softmax值转换为int
,因此为零。
Create your matrix like this: 像这样创建矩阵:
x = np.array([[1, 2, 3, 6],
[2, 4, 5, 6],
[3, 8, 7, 6]]).astype(float)
Now, after assigning softmax values: 现在,在分配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
comes out to be: 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.