简体   繁体   English

如何计算 numpy 中数组中最近邻居的平均值

[英]How to calculate average of closest neighbours in an array in numpy

Given an arbitrary array with real numbers as entries, I want to return an array with the same shape, whose entries are the average over the closest neighbours of the original array.给定一个以实数作为条目的任意数组,我想返回一个具有相同形状的数组,其条目是原始数组最近邻居的平均值。

What I mean by this in the case of a given array of dimension 2, is that if the array has shape (n,m) with entries a_{i,j}, then on the entry (i,j) the value of the new array should be:在给定维数为 2 的数组的情况下,我的意思是,如果数组的形状 (n,m) 带有条目 a_{i,j},那么在条目 (i,j) 上的值新数组应该是:

average(i,j)=1/4 (a_{i+1,j} + a_{i-1,j} + a_{i,j+1} + a_{i,j-1}),平均(i,j)=1/4 (a_{i+1,j} + a_{i-1,j} + a_{i,j+1} + a_{i,j-1}),

where the first index is taken mod n and the second mod m.其中第一个索引取 mod n,第二个取 mod m。

I would like to create a function whose argument is an arbitrary array, and returns an array of the same shape and entries the averages over the entries on the closest neighbours of the given array (for a d-dimensional array there are 2d closest neighbours, obtained by summing +1 and -1 on each index)我想创建一个 function ,其参数是任意数组,并返回一个形状相同的数组,并输入给定数组最近邻居上的条目的平均值(对于 d 维数组,有 2d 最近的邻居,通过对每个索引求和 +1 和 -1 获得)

I know how to do this for a fixed dimension d (just generalising the above equation), using d nested for loops, but I don't know how to do it when the dimensions are not fixed.我知道如何使用 d 嵌套的 for 循环对固定维度 d 执行此操作(只是推广上述等式),但我不知道在维度不固定时如何执行此操作。

Scipy has a scipy.ndimage.convolve function, which can do exactly this. Scipy 有一个 scipy.ndimage.convolve function,它可以做到这一点。 it takes the array, and a matrix of values to multiply the neighbors with.它需要数组和一个值矩阵来与邻居相乘。 It should work for any number of dimensions.它应该适用于任意数量的维度。

However if you are trying to write this function manually, I'd suggest trying an iterative or recursive approach, where each iteration or layer of recursion handles a dimension.但是,如果您尝试手动编写此 function,我建议尝试迭代或递归方法,其中每个迭代或递归层处理一个维度。 In a 3D case, you would first handle the first dimension, and have the one sixth of the value of the neighbors in that dimension.在 3D 案例中,您将首先处理第一个维度,并获得该维度中邻居值的六分之一。 The next iteration would do the same for dimension 2, etc.下一次迭代将对维度 2 执行相同的操作,依此类推。

The factor to multiply each neighbor with is 1/(2n), since each entry has 2 neighbors in each dimension.与每个邻居相乘的因子是 1/(2n),因为每个条目在每个维度上都有 2 个邻居。 This should scale up to any arbitrary number of dimensions.这应该扩展到任意数量的维度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM