简体   繁体   English

NumPy - 将阵列重塑为1-D

[英]NumPy - reshaping an array to 1-D

I am having problems converting a NumPy array into a 1-D. 我在将NumPy阵列转换为1-D时遇到问题。 I looked into ideas I found on SO, but the problem persists. 我查看了我在SO上发现的想法,但问题仍然存在。

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,). 编辑:先前是(200,200),d是200.我想获得1-D数组:[-0.0174428 -0.01855013 ... 0.01137508 0.00577147]大小(200,)。 d is 200. d是200。

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

Your prior is most likely a np.matrix which is a subclass of ndarray . prior是最有可能是np.matrix是的子类ndarray np.matrix s are always 2D. np.matrix总是2D。 So nu is a np.matrix and is 2D as well. 所以nu是一个np.matrix ,也是2D。

To make it 1D , first convert it to a regular ndarray : 要使它成为1D ,首先将其转换为常规的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: 但是如果你让nu成为一个ndarray:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM