2016-09-12 22 views
0

我有以下代碼numpy apply_over_axes強制keepdims = True?

import numpy as np 
import sys 

def barycenter(arr, axis=0) : 
    bc = np.mean(arr, axis, keepdims=False) 
    print("src shape:", arr.shape, ", **** trg shape:", bc.shape, "****") 
    sys.stdout.flush() 
    return bc 

a = np.array([[[0.1, 0.2, 0.3], [0.2, 0.3, 0.4]], 
       [[0.4, 0.4, 0.4], [0.7, 0.6, 0.8]]], np.float) 

e = barycenter(a, 2) 
print("direct application =", e, "**** (trg shape =", e.shape, ") ****\n") 
f = np.apply_over_axes(barycenter, a, 2) 
print("application through apply_over_axes =", f, "**** (trg shape =", f.shape, ") ****\n") 

產生以下輸出

src shape: (2, 2, 3) , **** trg shape: (2, 2) **** 
direct application = [[ 0.2 0.3] 
[ 0.4 0.7]] **** (trg shape = (2, 2)) **** 

src shape: (2, 2, 3) , **** trg shape: (2, 2) **** 
application through apply_over_axes = [[[ 0.2] 
    [ 0.3]] 

[[ 0.4] 
    [ 0.7]]] **** (trg shape = (2, 2, 1)) **** 

因此函數barycenter的返回值是從什麼與apply_over_axes(barycenter, ...獲得的不同。

這是爲什麼?

回答

1

結果直接從DOC如下:

func被稱爲解析度= FUNC(A,軸),其中軸是軸的第一元件 。函數調用的結果res必須具有相同的尺寸作爲一個維度或一個維度。如果res比a小一個維數 ,則在軸之前插入一個維度。然後對函數的調用 對軸中的每個軸重複,res爲第一個參數。

您的func將尺寸減1,所以apply_over_axes插入一個尺寸。

+0

準確。我從文檔中錯過了這一部分。然後我又去了,發現它......我正要消除這個問題。 –

相關問題