Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass from numpy matrix to numpy array?

I am new to Python and Numpy so maybe the title of my question is wrong.

I load some data from a matlab file

data=scipy.io.loadmat("data.mat")
x=data['x']
y=data['y']
>>> x.shape
(2194, 12276)
>>> y.shape
(2194, 1)

y is a vector and I would like to have y.shape = (2194,).

I do not the difference between (2194,) and (2194,1) but seems that sklearn.linear_model.LassoCV encounter an error if you try to load y such that y.shape=(2194,1).

So how can I change my y vector in order to have y.shape=(2194,)??

like image 375
Donbeo Avatar asked Nov 13 '13 15:11

Donbeo


People also ask

Is NumPy array and matrix same?

The NumPy ndarray class is used to represent both matrices and vectors. A vector is an array with a single dimension (there's no difference between row and column vectors), while a matrix refers to an array with two dimensions. For 3-D or higher dimensional arrays, the term tensor is also commonly used.

How do you turn a matrix into a list?

Conversion of a matrix into a list in Column-major order. The as. list() is an inbuilt function that takes an R language object as an argument and converts the object into a list. We have used this function to convert our matrix to a list.

How do you copy a matrix in NumPy?

If you wish to copy a matrix, then instead of using numpy. copy , use the copy method on matrix . Another alternative is to use numpy. array(x, copy=True, subok=True) .


1 Answers

First convert to an array, then squeeze to remove extra dimensions:

y = y.A.squeeze()

In steps:

In [217]: y = np.matrix([1,2,3]).T

In [218]: y
Out[218]: 
matrix([[1],
        [2],
        [3]])

In [219]: y.shape
Out[219]: (3, 1)

In [220]: y = y.A

In [221]: y
Out[221]: 
array([[1],
       [2],
       [3]])

In [222]: y.shape
Out[222]: (3, 1)

In [223]: y.squeeze()
Out[223]: array([1, 2, 3])

In [224]: y = y.squeeze()

In [225]: y.shape
Out[225]: (3,)
like image 54
askewchan Avatar answered Nov 01 '22 11:11

askewchan