Aso*_*ile 6 python grid numpy multidimensional-array
我想知道如何使用numpy mgrid为未知数量的维度(D)创建一个网格(多维数组),每个维度都有一个下限和上限以及二进制数:
n_bins = numpy.array([100 for d in numpy.arrange(D)])
bounds = numpy.array([(0.,1) for d in numpy.arrange(D)])
grid = numpy.mgrid[numpy.linspace[(numpy.linspace(bounds(d)[0], bounds(d)[1], n_bins[d] for d in numpy.arrange(D)]
Run Code Online (Sandbox Code Playgroud)
我猜上面不起作用,因为mgrid创建索引数组而不是值.但是如何使用它来创建值数组.
谢谢
Aso.agile
你可能会用
np.mgrid[[slice(row[0], row[1], n*1j) for row, n in zip(bounds, n_bins)]]
Run Code Online (Sandbox Code Playgroud)
import numpy as np
D = 3
n_bins = 100*np.ones(D)
bounds = np.repeat([(0,1)], D, axis = 0)
result = np.mgrid[[slice(row[0], row[1], n*1j) for row, n in zip(bounds, n_bins)]]
ans = np.mgrid[0:1:100j,0:1:100j,0:1:100j]
assert np.allclose(result, ans)
Run Code Online (Sandbox Code Playgroud)
请注意,np.ogrid可以在许多使用的地方np.mgrid使用,并且由于数组较小,因此需要较少的内存.