假设我有 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/