Skip to main content
 首页 » 编程设计

python之使用 meshgrid 和 vectorize 在未知维度的格上评估函数

2024年10月25日12qq78292959

当您提前知道晶格的维数时,可以直接使用 meshgrid 在网格上计算函数。

from pylab import * 
 
lattice_points = linspace(0,3,4) 
xs,ys = meshgrid(lattice_points,lattice_points) 
zs = xs+ys # <- stand-in function, to be replaced by something more interesting 
print(zs) 

生产

[[ 0.  1.  2.  3.] 
 [ 1.  2.  3.  4.] 
 [ 2.  3.  4.  5.] 
 [ 3.  4.  5.  6.]] 

但我想要一个类似的版本,其维数在运行时确定,或作为参数传递。

from pylab import * 
 
@np.vectorize 
def fn(listOfVars) : 
    return sum(listOfVars) # <- stand-in function, to be replaced  
                           # by something more interesting 
 
n_vars = 2 
lattice_points = linspace(0,3,4) 
indices = meshgrid(*(n_vars*[lattice_points])) # this works fine 
 
zs = fn(indices) # <-- this line is wrong, but I don't  
                 #     know what would work instead 
print(zs) 

产生

[[[ 0.  1.  2.  3.] 
  [ 0.  1.  2.  3.] 
  [ 0.  1.  2.  3.] 
  [ 0.  1.  2.  3.]] 
 
 [[ 0.  0.  0.  0.] 
  [ 1.  1.  1.  1.] 
  [ 2.  2.  2.  2.] 
  [ 3.  3.  3.  3.]]] 

但我希望它产生与上面相同的结果。

可能有一个解决方案,您可以找到每个维度的索引并使用 itertools.product 生成所有可能的索引组合等等,但是没有一个很好的 pythonic如何做到这一点?

请您参考如下方法:

Joe Kington 和 user2357112 帮助我发现了我的方法中的错误。对于那些希望看到完整解决方案的人:

from pylab import * 
 
## 2D "preknown case" (for testing / to compare output) 
lattice_points = linspace(0,3,4) 
xs,ys = meshgrid(lattice_points,lattice_points) 
zs = xs+ys 
print('2-D Case') 
print(zs) 
 
## 3D "preknown case" (for testing / to compare output) 
lattice_points = linspace(0,3,4) 
ws,xs,ys = meshgrid(lattice_points,lattice_points,lattice_points) 
zs = ws+xs+ys 
print('3-D Case') 
print(zs) 
 
## Solution, thanks to comments from Joe Kington and user2357112  
def fn(listOfVars) : 
    return sum(listOfVars) 
 
n_vars = 3 ## can change to 2 or 3 to compare to example cases above 
lattice_points = linspace(0,3,4) 
indices = meshgrid(*(n_vars*[lattice_points])) 
 
zs = np.apply_along_axis(fn,0,indices) 
print('adaptable n-D Case') 
print(zs)