假设我有一个函数f,它可以将坐标作为参数并返回一个整数(在本例中为f(x))。坐标可以是多维的,并且采用列表的形式。我的目标是用两个坐标之间的所有值填充一个numpy数组。我试着列出所有可能的索引,并将其用作向量化函数的输入。
这是我的二维坐标代码:
import itertools
import numpy
def index_array(lower_corner, upper_corner):
x_range = range(lower_corner[0], upper_corner[0])
y_range = range(lower_corner[1], upper_corner[1])
return numpy.array(list(itertools.product(x_range, y_range)))
print(index_array([2, -2], [5, 3]))
这将返回预期的索引列表:
[[ 2 -2]
[ 2 -1]
[ 2 0]
[ 2 1]
[ 2 2]
[ 3 -2]
[ 3 -1]
[ 3 0]
[ 3 1]
[ 3 2]
[ 4 -2]
[ 4 -1]
[ 4 0]
[ 4 1]
[ 4 2]]
这是我对n维的尝试:
import itertools
import numpy
def f(x):
# dummy function
return x + 5
def index_array(lower_corner, upper_corner):
# returns all indices between two n-dimensional points
range_list = []
for n in range(len(lower_corner)):
range_list.append(range(lower_corner[n], upper_corner[n]))
return numpy.array(list(itertools.product(*range_list)))
lower_corner = numpy.array([2, -2])
upper_corner = numpy.array([5, 3])
indices = index_array(lower_corner, upper_corner)
vect_func = numpy.vectorize(f)
results = vect_func(indices)
print(results)
虽然这工作,它相当慢,需要大量的内存。有没有可能用一种更有效的方式来写呢?我可以考虑用numpy。但是我不知道如何使用它
确实,np.meshgrid
将是一些stacking
的一种方法,如下所示-
def ndim_grid(start,stop):
# Set number of dimensions
ndims = len(start)
# List of ranges across all dimensions
L = [np.arange(start[i],stop[i]) for i in range(ndims)]
# Finally use meshgrid to form all combinations corresponding to all
# dimensions and stack them as M x ndims array
return np.hstack((np.meshgrid(*L))).swapaxes(0,1).reshape(ndims,-1).T
样本运行1) 2D
Case:
In [97]: ndim_grid([2, -2],[5, 3])
Out[97]:
array([[ 2, -2],
[ 2, -1],
[ 2, 0],
[ 2, 1],
[ 2, 2],
[ 3, -2],
[ 3, -1],
[ 3, 0],
[ 3, 1],
[ 3, 2],
[ 4, -2],
[ 4, -1],
[ 4, 0],
[ 4, 1],
[ 4, 2]])
2) 3D
Case:
In [98]: ndim_grid([2, -2, 4],[5, 3, 6])
Out[98]:
array([[ 2, -2, 4],
[ 2, -2, 5],
[ 2, -1, 4],
[ 2, -1, 5],
[ 2, 0, 4],
[ 2, 0, 5],
[ 2, 1, 4],
[ 2, 1, 5],
[ 2, 2, 4],
[ 2, 2, 5],
[ 3, -2, 4],
[ 3, -2, 5],
[ 3, -1, 4],
[ 3, -1, 5],
[ 3, 0, 4],
[ 3, 0, 5],
[ 3, 1, 4],
[ 3, 1, 5],
[ 3, 2, 4],
[ 3, 2, 5],
[ 4, -2, 4],
[ 4, -2, 5],
[ 4, -1, 4],
[ 4, -1, 5],
[ 4, 0, 4],
[ 4, 0, 5],
[ 4, 1, 4],
[ 4, 1, 5],
[ 4, 2, 4],
[ 4, 2, 5]])
另一个选择是使用itertools
中的product
,这也适用于角高于2D
:
import itertools as it
lower_corner = [2, -2]
upper_corner = [5, 3]
[coord for coord in it.product(*[range(r[0], r[1]) for r in zip(lower_corner, upper_corner)])]
[(2, -2),
(2, -1),
(2, 0),
(2, 1),
(2, 2),
(3, -2),
(3, -1),
(3, 0),
(3, 1),
(3, 2),
(4, -2),
(4, -1),
(4, 0),
(4, 1),
(4, 2)]