numpy 如何使用向量化或数组广播来摆脱这个for循环?

0wi1tuuw  于 2023-03-23  发布在  其他
关注(0)|答案(1)|浏览(166)

有没有办法使用np.vectorize或numpy数组广播来摆脱这个for循环?

xs = np.random.uniform(-2,2,size=(3,2))

Qs = np.array([
    [
        [4,2],
        [2,2]
    ],
    [
        [1,1],
        [1,1]
    ],
    [
        [2,2],
        [2,2]
    ]
])
rs = np.array([
    [1,-1],
    [1,1],
    [-1,1]
])

g = lambda Q, r, x: 0.5*x.T @ Q @ x + r @ x

# loop over all of the elements of Qs, rs, and xs 
# evaluating g at each point
results = []
for Q, r, x in zip(Qs, rs, xs):
    results.append(g(Q, r, x))
print(np.array(results))

我试过使用数组广播:

results = g(Qs, rs, xs)

但上面说

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 3)

我试着把函数向量化:

g_vec = np.vectorize(g)
results = g_vec(Qs, rs, xs)
print(results)

但它给出了这个误差:

TypeError: unsupported operand type(s) for @: 'numpy.float64' and 'numpy.int32'

并且似乎不会在每个Q,r和x np上循环。

3npbholx

3npbholx1#

您需要向向量化函数添加签名,以正确地乘以矩阵:

g_vec = np.vectorize(g, signature='(n,n),(n),(n)->()')
results = g_vec(Qs, rs, xs)
print(results)

More on signatures.

相关问题