【问题标题】:Vectoring for loop in Python [duplicate]在 Python 中向量化 for 循环 [重复]
【发布时间】: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]。不知道如何在一行中做到这一点。

第二个循环比第一个更难。任何帮助深表感谢。

【问题讨论】:

标签: python numpy for-loop vectorization


【解决方案1】:

第一个循环出现为

out = np.zeros((N, d))
dir_int = np.random.randint(0, d, N)
out[np.arange(N), dir_int] = 1

并且第二个帮助有点困难,因为 bx 未定义,我不确定我是否可视化所需的输出。但是您应该能够使用 dir_int 索引到 bMax 以一次更新整个 N-length 列。

【讨论】:

    猜你喜欢
    • 2019-07-07
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    相关资源
    最近更新 更多