【发布时间】:2023-02-16 21:19:15
【问题描述】:
我在对 Python 中的以下 for 循环进行矢量化时遇到困难。
out = np.zeros((N, d))
dir_int = []
for i in range(N):
dir_int.append(np.random.randint(low=0, high = d))
out[i,dir_int[i]] = 1
#where:
# direct_int has shape (N, )
# u has shape (N, d)
# x has the same shape as u
# A has shape (2d, d) = [I,-I]^T, I the dxd identity
# b has shape (2d, )
bmAx = b - np.concatenate((x,-x), axis=1) #This is b-Ax has shape N x 2d
upper = np.copy(x)
lower = np.copy(x)
temp = np.zeros(2)
for i in range(len(dir_int)):
temp[0] = bmAx[i, dir_int[i]]
temp[1] = -bmAx[i, d + dir_int[i]]
upper[i, dir_int[i]] += np.amax(temp)
lower[i, dir_int[i]] += np.amin(temp)
对于第一个循环,dir_int 可以创建为 dir_int = np.random.randint(low=0, high = d, size = N)。然后对于 out 的每一“行”,其中一列应该是 1;此专栏是dir_int[row]。不知道如何在一行中做到这一点。
第二个循环比第一个更难。任何帮助深表感谢。
【问题讨论】:
-
@PranavHosangadi 非常感谢您的评论。是的,
np.put_along_axis就是我要找的。
标签: python numpy for-loop vectorization