我有以下代码
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, ...
获得的值不同。
为什么会这样?
答案 0 :(得分:1)
结果直接来自doc:
func被称为res = func(a,axis),其中axis是第一个元素 轴。函数调用的结果res必须相同 尺寸为一个或一个以下的尺寸。如果res的维度少一个 比a,在轴之前插入尺寸。然后调用func 对轴中的每个轴重复,以res作为第一个参数。
您的func将维度减少1,因此apply_over_axes会插入维度。