简体   繁体   English

麻烦乘以Numpy矩阵的列

[英]Trouble Multiplying Columns of a Numpy Matrix

I am trying to multiply columns of a numpy matrix together. 我试图将numpy矩阵的列相乘。 I have followed the code given in this question . 我已经遵循了这个问题中给出的代码。

Here is what the column looks like: 这是列的样子:

在此输入图像描述

Here is what happens when I try to multiply two columns of the matrix together. 当我尝试将矩阵的两列相乘时,会出现这种情况。

在此输入图像描述

Maybe the issue is that the column is stored differently? 也许问题是列的存储方式不同? Some of the printouts in the other questions do not have the numbers stored in separate lists. 其他问题中的某些打印输出没有将数字存储在单独的列表中。

With np.matrix , the * operator does matrix multiplication rather than element-wise multiplication, which is what I assume you're trying to do. 使用np.matrix*运算符执行矩阵乘法而不是逐元素乘法,这是我假设你要做的。

You get a ValueError because the two column vectors are not properly aligned for matrix multiplication. 您得到一个ValueError因为两个列向量没有正确对齐矩阵乘法。 Their inner dimensions don't match, since their shapes are (N, 1) and (N, 1) respectively. 它们的内部尺寸不匹配,因为它们的形状分别是(N, 1)(N, 1) They would need to be either (1, N) , (N, 1) (for the inner product) or (N, 1) , (1, N) (for the outer product) in order for matrix multiplication to work. 它们需要是(1, N)(N, 1) (对于内积)或(N, 1)(1, N) (对于外积),以便矩阵乘法起作用。

If you choose to stick to using np.matrix to hold your data, you could use the np.multiply() function to do element-wise multiplication: 如果您选择坚持使用np.matrix来保存数据,则可以使用np.multiply()函数进行np.multiply()元素乘法:

result = np.multiply(new_train_data[:, 0], new_train_data[:, 1])

However, I would recommend that you use np.array instead of np.matrix in future. 但是,我建议您将来使用np.array而不是np.matrix With np.array the * operator does element-wise multiplication, and the np.dot() function (or the .dot() method of the array) does matrix multiplication. 使用np.array*运算符执行np.array元素乘法,并且np.dot()函数(或数组的.dot()方法)执行矩阵乘法。

new_train_data is evidently a matrix (subclass of ndarray ). new_train_data显然是一个matrixndarray子类)。 Its * is defined as matrix multiplication (like the np.dot ), not the element by element multiplication of regular numpy arrays. 它的*被定义为矩阵乘法(如np.dot ),而不是常规numpy数组的元素乘法元素。 Hence the 'alignment' error message. 因此'对齐'错误消息。

在答案中,它使用numpy.dot将n * n乘以n ...对我有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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