numpy apply

编程入门 行业动态 更新时间:2024-10-27 05:36:02
numpy apply_over_axes强制keepdims = True?(numpy apply_over_axes forcing keepdims=True?) python

我有以下代码

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.

更多推荐

本文发布于:2023-07-31 00:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340428.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:numpy   apply

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!