gpt4 book ai didi

python - 向量化三个嵌套循环 - NumPy

转载 作者:太空宇宙 更新时间:2023-11-03 16:20:59 29 4
gpt4 key购买 nike

我有两个数组 x.dim = (N,4)y.dim = (M, M, 2) 和一个函数 f( a, b),分别以KL维向量作为参数。我想获得一个数组 res.dim = (N, M, M) 这样

for n in range(N):
for i in range(M):
for j in range(M):
res[n, i, j] = f(x[n], y[i, j])

在这种情况下无法了解如何使用apply。预先感谢您的帮助!

def f(a, b):
return max(0, 1 - np.sum(np.square(np.divide(np.subtract(b, a[0:2]), a[2:4]))))

最佳答案

这是使用 NumPy broadcasting 处理列出的函数的矢量化方法和切片 -

# Slice out relevant cols from x
x_slice1 = x[:,None,None,:2]
x_slice2 = x[:,None,None,2:4]

# Perform operations using those slices to correspond to iterative operations
out = np.maximum(0,1-(np.divide(y-x_slice1,x_slice2)**2).sum(3))

关于python - 向量化三个嵌套循环 - NumPy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38461464/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com