2014-02-25 74 views
3

我在将NumPy数组转换为1-D时遇到问题。我看到了我在SO上发现的想法,但问题依然存在。NumPy - 将数组重塑为1-D

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 

的代码产生以下输出:

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]] 

你觉得可能是什么问题?我在做什么错误?

编辑:之前是(200,200),d是200.我想要得到一维数组:[-0.0174428 -0.01855013 ... 0.01137508 0.00577147]的大小(200,)。 d为200

EDIT2:也randn是numpy.random(从numpy.random进口randn)

+0

“前”的维度是什么?另外,你还期待什么? – mtrw

+0

之前是(200,200)。我想获得一维数组:[-0.0174428 -0.01855013 ... 0.01137508 0.00577147] – Jacek

+1

你可以为'prior'添加一些代码吗?将它设置为'np.ones([d,d])'会产生你想要的输出。 – Stefan

回答

4

prior是最有可能的一个np.matrix这是ndarray一个子类。 np.matrix s总是2D。所以nunp.matrix,也是2D。

为了让1D,首先将其转换为常规ndarray

nu = np.asarray(nu) 

例如,

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) 

但是,如果你nu的ndarray:

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

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

很好,赶上!我开始疯狂地试图想到一些奇怪的'dtype = object'解释,但它没有发生。 – DSM

+0

就是这样。谢谢。 – Jacek

+0

'np.array'会默认复制数据。除非这真的是你想要的,否则最好是得到一个视图,或者调用'np.asarray'或'np.array(...,copy = False)'。 – Jaime