Nick Nick - 11 months ago 52
Python Question

Matlab to Python numpy indexing and multiplication issue

I have the following line of code in MATLAB which I am trying to convert to Python


pred = traindata(:,2:257)*beta;

In Python, I have:

pred = traindata[ : , 1:257]*beta

is a 256 x 1 array.


size(pred) = 1389 x 1

But in Python,

pred.shape = (1389L, 256L)

So, I found out that multiplying by the
array is producing the difference between the two arrays.

How do I write the original Python line, so that the size of
is 1389 x 1, like it is in MATLAB when I multiply by my beta array?

Answer Source

I suspect that beta is in fact a 1D numpy array. In numpy, 1D arrays are not row or column vectors where MATLAB clearly makes this distinction. These are simply 1D arrays agnostic of any shape. If you must, you need to manually introduce a new singleton dimension to the beta vector to facilitate the multiplication. On top of this, the * operator actually performs element-wise multiplication. To perform matrix-vector or matrix-matrix multiplication, you must use numpy's dot function to do so.

Therefore, you must do something like this:

import numpy as np # Just in case

pred =[:, 1:257], beta[:,None])

beta[:,None] will create a 2D numpy array where the elements from the 1D array are populated along the rows, effectively making a column vector (i.e. 256 x 1). However, if you have already done this on beta, then you don't need to introduce the new singleton dimension. Just use dot normally:

pred =[:, 1:257], beta)