如何计算python中两个向量数组的点积? [英] how to calculate the dot product of two arrays of vectors in python?

查看:43
本文介绍了如何计算python中两个向量数组的点积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A 和 B 都是具有 shape(N,3) 的数组.它们每个都包含 N 个向量,使得 A[0] = a0 (vector), A[1] = a1...B[0] = b0, B[1] = b1...

A and B are both arrays with shape(N,3). They each contain N vectors such that A[0] = a0 (vector), A[1] = a1... and B[0] = b0, B[1] = b1...

我想计算 N 对向量 an 和 bn 的点积.换句话说,我想获得一个带有 shape(N,1) 的数组 C,使得 C[i] = np.dot(A[i],B[i]). 在 python 中执行此操作的最有效方法是什么(例如使用矢量化代码)?

I want to calculate the dot product of the N pairs of vectors an and bn. In other words, I want to obtain an array C with shape(N,1) such that C[i] = np.dot(A[i],B[i]). What is the most efficient way of doing this in python (e.g. using vectorized code)?

推荐答案

您可以执行逐元素乘法,然后沿第二个轴求和,就像这样 -

You can perform element-wise multiplication and then sum along the second axis, like so -

C = (A*B).sum(1)

这些乘法和求和运算可以通过 np.einsum,就像这样 -

These multiplication and summation operations can be implemented in one go with np.einsum, like so -

C = np.einsum('ij,ij->i',A,B)

使用 np.matmul/@-operator -

(A[:,None,:] @ B[...,None]).ravel()

这篇关于如何计算python中两个向量数组的点积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆