2016-08-04 108 views
0

我試圖執行一些函數來從一組衛星圖像中獲取一些結果(在示例中我正在執行相似函數)。我首先打算同時遍歷所有像素,每個像素包含4個數字,然後根據這些數字計算每個像素的值,然後將其寫入數組,例如scipy.spatial.distance.correlation(pixels_0,pixels_1)。對兩個3D數組中的數據進行迭代python

我遇到的問題是當我運行這個循環時,我遇到了問題,將它保存到數組1000x1000,併爲每個像素賦予一個值。

array_0 = # some array with dimensions(1000, 1000, 4) 
array_1 = # some array with dimensions(1000, 1000, 4) 

result_array = [] 

for rows_0, rows_1 in itertools.izip(array_0, array_1): 
    for pixels_0, pixels_1 in itertools.izip(rows_0, rows_1): 
     results = some_function(pixels_0, pixels_1) 
     print results 
     >>> # successfully prints desired results 
     results_array.append(results) 
     >>> # unsuccessful in creating the desired array 

我得到我想要得到印刷向下運行窗口中的結果,但我不知道怎麼把它恢復到一個數組,我可以以類似的莊園操縱。我的for循環的問題,或者這是一個簡單的問題,將其附加到數組?任何關於加速它的解釋也會很棒,因爲我對python和編程都很陌生。

a = np.random.rand(10, 10, 4) 
b = np.random.rand(10, 10, 4) 

def dotprod(T0, T1): 
    return np.dot(T0, T1)/(np.linalg.norm(T0)*np.linalg.norm(T1)) 

results =dotprod(a.flatten(), b.flatten()) 
results = results.reshape(a.shape) 

這現在造成ValueError異常:新的數組的總大小必須保持不變, 和印刷第一結果值時,收到只有一個號碼。這是我自己構造不好的功能或我如何使用numpy的錯?

回答

0

最好的辦法是使用Numpy爲你的任務。你應該考慮向量。你應該寫你的some_function()以矢量化的方式工作。這裏是一個例子:

array_0 = np.random.rand(1000,1000,4) 
array_1 = np.random.rand(1000,1000,4) 
results = some_function(array_0.flatten(), array_1.flatten()) ## this will be (1000*1000*4 X 1) 
results = results.reshape(array_0.shape) ## reshaping to make it the way you want it. 
+0

我喜歡矢量思維方式,因爲其中一個操作是找到兩個矢量之間的角度:我爲它寫了一個簡單函數def'dotprod(T0,T1):' 'return np.dot(T0,T1 )/(np.linalg.norm(T0)* np.linalg.norm(T1))'並替換'some_function',但輸出是單個數字而不是數組。這是關於重做的功能,而不是你通過數據集中的數字的方式? – nhawkins

0

在投入更多精力進行編程之前,請先看看numpy包。它會快很多倍!

關於你的代碼:不應該你的結果數組也是多維的?因此,在內部(每行)循環中,您應該追加到一行,然後在外部循環附加到結果矩陣。

數據少量嘗試(例如,10×10×4)學習,但開關後,只要你能numpy的...

+0

是的我打算有一個1000x1000的所有值後,我的功能perforation。這可能聽起來像一個愚蠢的問題,但是當你提到切換到numpy時,你的意思是什麼?我相信我的數據目前在numpy數組中,我將如何構造它以儘可能地從numpy中受益? – nhawkins