2014-04-13 78 views
1

我有形狀3X4X4的numpy的阿雷如圖所示:鴻溝陣列的一個陣列的每個項目拍攝

[[[0 0 0 2] 
    [0 0 0 0] 
    [1 0 0 0] 
    [0 0 0 0]] 

[[0 1 0 0] 
    [0 0 0 0] 
    [0 0 0 0] 
    [0 1 1 0]] 

[[0 0 0 0] 
    [0 1 1 0] 
    [0 0 1 0] 
    [0 0 0 0]]] 

我想0.25劃分在我的陣列內的各4 X4矩陣中的每個號碼。 然後我想記錄所有這些值。 (因此,Im將每個數組中的所有值除以.25,然後取該數字的對數) 輸出應該是相同的3x4x4矩陣,只是值會更改。 任何建議

回答

5

你可以簡單地做:

numpy.log(yourNumpyArray/0.25) 

而且numpy的會做正確的事(0.25分每個元素)

瞭解更多:

+1

從過早的微優化部門,'np.log(yourNumpyArray) - np.log(0.25)'給出了相同的結果,但替代價格昂貴的分歧通過廉價的減法。我的系統速度大概快10%。 – Jaime

+0

@Jaime很奇怪,在我的系統中,情況正好相反:>>>%timeit np.log(a/0.25)'給出了'100000個循環,最好每個循環3:8.99μs'和 >>> %timeit np.log(a) - np.log(0.25)'導致: '100000個循環,最好3個:每個循環10.3μs(稍微慢一些) – elias

+0

我在一個大的(1000x1000)陣列上運行它。由於在OP的問題中只有少量內容,對'np.log'的額外調用可能會讓所有的改進都吃光。在我的系統上,交叉發生在陣列中約800個項目。 – Jaime

2
import numpy as np 

arr = np.array([[[0, 0, 0, 2],[0, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], [[0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ,[0, 1, 1, 0]] ,[[0, 0, 0, 0], [0, 1, 1, 0] ,[0, 0, 1, 0] ,[0, 0, 0, 0]]]) 
arr /= 0.25 
arr = np.log(arr) 
3

我看不出有什麼不對這個

>> import numpy as np 
>> a = np.array([[[0, 0, 0, 2],[0, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], [[0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ,[0, 1, 1, 0]] ,[[0, 0, 0, 0], [0, 1, 1, 0] ,[0, 0, 1, 0] ,[0, 0, 0, 0]]]) 
>> a 
[[[0, 0, 0, 2], [0, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], 
[[0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 1, 0]], 
[[0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0, 0]]] 

>> np.log(a/0.25) 

array([[[  -inf,  -inf,  -inf, 2.07944154], 
     [  -inf,  -inf,  -inf,  -inf], 
     [ 1.38629436,  -inf,  -inf,  -inf], 
     [  -inf,  -inf,  -inf,  -inf]], 

     [[  -inf, 1.38629436,  -inf,  -inf], 
     [  -inf,  -inf,  -inf,  -inf], 
     [  -inf,  -inf,  -inf,  -inf], 
     [  -inf, 1.38629436, 1.38629436,  -inf]], 

     [[  -inf,  -inf,  -inf,  -inf], 
     [  -inf, 1.38629436, 1.38629436,  -inf], 
     [  -inf,  -inf, 1.38629436,  -inf], 
     [  -inf,  -inf,  -inf,  -inf]]])