NumPy - Convert Array to 1-D

I'm having trouble converting a NumPy array to 1-D. I was looking for ideas that 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 displays the following result:

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, maybe the problem? What mistake am I making?

EDIT: previous (200 200), d is 200. I want to get a 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)

+3
source share
1 answer

Your priormost likely a np.matrix, which is a subclass ndarray. np.matrixalways 2D. Thus, nuis np.matrixand is also 2D.

To do this 1D, first convert it to normal ndarray:

nu = np.asarray(nu)

For instance,

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 do nundarray:

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

In [56]: nu.ravel().shape
Out[56]: (200,)
+4
source

All Articles