python - 跨多维数组的矢量化 NumPy linspace

标签 python numpy vectorization

假设我有 2 个 numpy 二维数组,mins 和 maxs,它们的维度始终相同。我想创建第三个数组 results,这是将 linspace 应用于最大值和最小值的结果。有没有一些“numpy”/矢量化的方法来做到这一点?下面的示例非矢量化代码显示了我想要的结果。

import numpy as np

mins = np.random.rand(2,2)
maxs = np.random.rand(2,2)

# Number of elements in the linspace
x = 3

m, n = mins.shape
results = np.zeros((m, n, x))

for i in range(m):
    for j in range(n):
        min = mins[i][j]
        max = maxs[i][j]
        results[i][j] = np.linspace(min, max, num=x)

最佳答案

这是一种基于 this post 的矢量化方法覆盖通用的 n-dim 案例 -

def create_ranges_nd(start, stop, N, endpoint=True):
    if endpoint==1:
        divisor = N-1
    else:
        divisor = N
    steps = (1.0/divisor) * (stop - start)
    return start[...,None] + steps[...,None]*np.arange(N)

sample 运行-

In [536]: mins = np.array([[3,5],[2,4]])

In [537]: maxs = np.array([[13,16],[11,12]])

In [538]: create_ranges_nd(mins, maxs, 6)
Out[538]: 
array([[[  3. ,   5. ,   7. ,   9. ,  11. ,  13. ],
        [  5. ,   7.2,   9.4,  11.6,  13.8,  16. ]],

       [[  2. ,   3.8,   5.6,   7.4,   9.2,  11. ],
        [  4. ,   5.6,   7.2,   8.8,  10.4,  12. ]]])

关于python - 跨多维数组的矢量化 NumPy linspace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46694167/

相关文章:

python - 记忆化python函数

matlab - 矢量化和矢量索引

c++ - 使用 SSE/AVX 的整数点积?

python - 如何证明 `fake.unique.ascii_free_email()` 无论运行多少次都不会返回重复的电子邮件地址

python - Sympy 似乎因更高的数字而崩溃

python - skimage.transform.resize 导致系统崩溃

python - numpy fft 对于小素数乘积的长度很快,但是有多小?

python - 矢量化:不是有效的集合

python - 如何将列表列表转换为 NumPy 数组并获取完整大小?

arrays - Numpy:重新排列矩阵以使每一行与其左/右上下文堆叠的最有效方法是什么?