2014-02-25 75 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