Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy - reshaping an array to 1-D

I am having problems converting a NumPy array into a 1-D. I looked into ideas I found on SO, but the problem persists.

nu = np.reshape(np.dot(prior.T, randn(d)), -1)
print 'nu1', str(nu.shape)
print nu
nu = nu.ravel()
print 'nu2', str(nu.shape)
print nu
nu = nu.flatten()
print 'nu3', str(nu.shape)
print nu
nu = nu.reshape(d)
print 'nu4', str(nu.shape)
print nu

The code produces the following output:

nu1 (1, 200)
[[-0.0174428  -0.01855013 ... 0.01137508  0.00577147]]
nu2 (1, 200)
[[-0.0174428  -0.01855013 ... 0.01137508  0.00577147]]
nu3 (1, 200)
[[-0.0174428  -0.01855013 ... 0.01137508  0.00577147]]
nu4 (1, 200)
[[-0.0174428  -0.01855013 ... 0.01137508  0.00577147]]

What do you think might be the problem? What mistake I am doing?

EDIT: prior is (200,200), d is 200. I want to get 1-D array: [-0.0174428 -0.01855013 ... 0.01137508 0.00577147] of size (200,). d is 200.

EDIT2: Also randn is from numpy.random (from numpy.random import randn)

like image 575
Jacek Avatar asked Apr 12 '26 07:04

Jacek


1 Answers

Your prior is most likely a np.matrix which is a subclass of ndarray. np.matrixs are always 2D. So nu is a np.matrix and is 2D as well.

To make it 1D, first convert it to a regular ndarray:

nu = np.asarray(nu)

For example,

In [47]: prior = np.matrix(np.random.random((200,200)))

In [48]: d = 200

In [49]: nu = np.reshape(np.dot(prior.T, randn(d)), -1)

In [50]: type(nu)
Out[50]: numpy.matrixlib.defmatrix.matrix

In [51]: nu.shape
Out[51]: (1, 200)

In [52]: nu.ravel().shape
Out[52]: (1, 200)

But if you make nu an ndarray:

In [55]: nu = np.asarray(nu)

In [56]: nu.ravel().shape
Out[56]: (200,)
like image 155
unutbu Avatar answered Apr 13 '26 22:04

unutbu