繁体   English   中英

Python,Numpy:无法将numpy数组的值分配给矩阵的列

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM