Trouble Multiplying Columns of a Numpy Matrix

Question:

I am trying to multiply columns of a numpy matrix together. I have followed the code given in this question.

Here is what the column looks like:

enter image description here

Here is what happens when I try to multiply two columns of the matrix together.

enter image description here

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.

Asked By: goldisfine

||

Answers:

Well in the answer it uses numpy.dot to multiply n*n with n…works for me!

Answered By: wormhole spacetime

With np.matrix, the * operator does matrix multiplication rather than element-wise multiplication, which is what I assume you’re trying to do.

You get a ValueError because the two column vectors are not properly aligned for matrix multiplication. Their inner dimensions don’t match, since their shapes are (N, 1) and (N, 1) respectively. 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.

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:

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. With np.array the * operator does element-wise multiplication, and the np.dot() function (or the .dot() method of the array) does matrix multiplication.

Answered By: ali_m

new_train_data is evidently a matrix (subclass of ndarray). Its * is defined as matrix multiplication (like the np.dot), not the element by element multiplication of regular numpy arrays. Hence the ‘alignment’ error message.

Answered By: hpaulj
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.