我有以下代码
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, ...的返回值不同。
为什么?
I have the following code
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" )which produces the following output
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) ) ****So the return value of the function barycenter is different from what is obtained with apply_over_axes( barycenter, ....
Why is that so?
最满意答案
结果直接来自doc:
func被称为res = func(a,axis),其中axis是轴的第一个元素。 函数调用的结果res必须具有与一个或更少维度相同的维度。 如果res的尺寸小于a,则在轴之前插入尺寸。 然后对轴中的每个轴重复调用func,其中res作为第一个参数。
您的func将维度减少1,因此apply_over_axes会插入维度。
The result follows directly from the doc:
func is called as res = func(a, axis), where axis is the first element of axes. The result res of the function call must have either the same dimensions as a or one less dimension. If res has one less dimension than a, a dimension is inserted before axis. The call to func is then repeated for each axis in axes, with res as the first argument.
Your func reduces the dimension by 1, so apply_over_axes inserts a dimension.
更多推荐
发布评论