【问题标题】:How to create multidimensional array with numpy.mgrid如何使用 numpy.mgrid 创建多维数组
【发布时间】:2012-11-24 14:59:12
【问题描述】:

我想知道如何使用 numpy mgrid 为未知数量的维度 (D) 创建一个网格(多维数组),每个维度都有一个下限和上限以及 bin 数:

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)]

我猜上面是行不通的,因为 mgrid 创建的是索引数组而不是值。但是如何使用它来创建值数组。

谢谢

Aso.agile

【问题讨论】:

  • numpy.arange(“数组范围”),而不是numpy.arrange

标签: python multidimensional-array numpy grid


【解决方案1】:

你可能会使用

np.mgrid[[slice(row[0], row[1], n*1j) for row, n in zip(bounds, n_bins)]]

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)

请注意,np.ogrid 可以在许多使用np.mgrid 的地方使用,并且由于数组更小,它需要更少的内存。

【讨论】:

  • 感谢@unutbu,它运行良好。现在如何将此网格转换为 D 维点,即 100**D x D 形状?
  • reshape 确实给出了 100D 个 D 向量,但令人惊讶的是它们并不是唯一的,这也意味着并非所有可能的向量都存在。在网格中获得所有 D 点的方法是什么?我实际上把它想象成一个 100D 表,并且不知道如何处理 mgrid 给出的附加维度。
  • @LevLevitsky:要在网格中获得分数,请使用result.reshape(D, -1).T-1 将被替换为使用数组中所有值所需的任何数字。感谢您的提问,这可能更像是 AsoAgile 所寻找的。​​span>
  • @LevLevitsky:假设你有一个像def f(x): return x[0]**2+x[1] 这样的函数。然后grid = np.mgrid[0:5,0:5] 完美设置为评估f(grid),它为网格上的每个点计算f(x)。请注意,np.ogrid 通过利用广播返回较小的数组,这些数组也可以在这里工作。
  • @LevLevitsky:确实,您不能将这个“技巧”与任何功能一起使用。计算必须在 numpy 数组方面有意义。如果您的计算不能用数组来表示,那么您就只能使用速度慢得多的vectorizefrompyfunc 函数。
猜你喜欢
  • 2011-11-24
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多