python - (Numpy 或 PyTorch)对给定的 bin 求和数组元素
问题描述
我希望使用 PyTorch 张量来解决这个问题。如果 torch 中没有有效的解决方案,请随意提出一个 numpy 解决方案。
让a
是一维张量(或 numpy 数组),并且是 0 和排除bin_indices
之间的整数的张量(np 数组) 。n
我想计算bins
位置处的数组i
包含元素的总和a[bins_indices == i]
。
n = 3
a = [1, 4, 3, -2, 5] # Values
bins_indices = [0, 0, 1, 2, 0] # Correspondent bin indices
bins = [10, 3, -2] # bins[0] = 1 + 4 + 5 etc. bins has 3 elements since n=3
如果您还可以提供一种批量处理这项工作的方法,我将非常感谢您!
解决方案
不确定这是否是最好的方法,但这是另一种解决方案:
>>> bins = torch.unique(bins_indices)
>>> vfunc = np.vectorize( lambda x: torch.sum( a[ bins_indices == x ] ) )
>>> vfunc( bins )
array([10, 3, -2])
推荐阅读
- regex - 匹配第一个实例的正则表达式
- python - Windows:Numpy mkl_intel_thread.dll
- r - 仅当打印输入变量时,闪亮的反应式才有效
- javascript - 有什么方法/工作库可以将我的 React 表导出到可下载的 excel 表(xls 或 xlsx,csv 不起作用) - React
- android - 有什么方法可以根据 Android 中 RecyclerView 的项目文本长度为每一行设置不同的“spanCount”
- c++ - 生成自动灰显的makefile - eclipse
- angular - Chrome Angular Unchecked runtime.lastError:消息端口在收到响应之前关闭
- angular - Angular Material Tree 不显示填充了数组的子元素
- c# - 如何对两个列表/数组正确执行算术运算
- java - 是否可以在注释处理期间使用 Mirror API 递归检查注释