I'm new to python and numpy/scipy. The design of Numpy array and the broadcasting rule in numpy/scipy is sometime quite helpful while remaining a lot of pain to me.
I read something like
Numpy tries to keep the array in the lowest dimension.
somewhere.
Here are some situations.
I would like to receive a matrix and calculate its eigenvalues and do some stuff. There will be a moment that a 1d array(e.g, array(1.0) - that comes from a result of a numpy operation), namely a scale pass to this function. I need to write something like
if (A.ndim < 2): A = sp.array([[A]])to prevent
scipy.linalg.eigshowingValueError: expected square matrix
When doing some machine learning problem, I write thing like
n_samples, n_features = X.shape if X.ndim > 1 else (1, X.shape[0])I just need to write extra code to gain the number of samples and features and prevent
IndexError: tuple index out of range
Or sometimes I only need the number of features when the row of a matrix represents a sample, and the column of a matrix represents a feature. I need to write something like
n_features = X.shape[1] if X.ndim > 2 else X.shape[0]or do some preprocessing like
if (X.ndim < 2): X = X[np.newaxis, :]to keep things go well.
Sometimes I write thing like
sp.dot(weight.T, X.T - mu[:, sp.newaxis])Everything seems fine until I find that
muwill possibly be a 1d array or a int scaler ! Then the exceptionTypeError: 'int' object is not subscriptable or
IndexError: too many indices for array
almost make me crazy.
There are even more cases like this ... All of this seems come from the rule mentioned as the fisrt quote, e.g, when I am expecting a matrix even a 1x1 one, numpy tries to reduce it into a 0-dim array(namely, array(1.0)).
I'm used to be a matlab user and now get into Numpy/Scipy. Beyond the simple and math-friendly matlab syntax, there still less pain in matlab.
I read some code in the source of sklearn package, there also be lots of code worrying 'is this thing a vector or matrix ?', 'shall we add a new axis to it?'.
What is the best way to reduce the pain of writing this ?