两个向量的外积是向量 A 的每个元素与向量 B 的每个元素相乘得到的矩阵。向量 a 和 b 的外积为 a ⊗ b。以下是计算外积的数学公式。
a ⊗ b = [a[0] * b, a[1] * b, ..., a[m-1] * b]
哪里,
a, b 是向量。
-
表示两个向量的逐元素乘法。
外积的输出是一个矩阵,其中i和j是矩阵的元素,其中第i行是通过将向量‘a’的第i个元素乘以向量‘b’的第i个元素得到的向量。
使用Numpy计算外积
在Numpy中,我们有一个名为outer()的函数,用于计算两个向量的外积。
语法
下面是outer()函数的语法 -
np.outer(array1, array2)
哪里,
外部是函数。
array1和array2是输入数组。
示例
在下面的示例中,我们尝试使用outer()函数计算两个numpy数组的外积 -
import numpy as np a = np.array([34,23,90,34]) b = np.array([90,34,43,23]) print("The input arrays:",a,b) outer_product = np.outer(a,b) print("The Outer product of the given input arrays:",outer_product)
输出
The input arrays: [34 23 90 34] [90 34 43 23] The Outer product of the given input arrays: [[3060 1156 1462 782] [2070 782 989 529] [8100 3060 3870 2070] [3060 1156 1462 782]]
示例
让我们看另一个例子,其中我们使用outer()函数计算二维数组的外积 -
import numpy as np a = np.array([[34,23],[90,34]]) b = np.array([[90,34],[43,23]]) print("The input arrays:",a,b) outer_product = np.outer(a,b) print("The Outer product of the given input arrays:",outer_product)
输出
以下是两个数组的外积的输出。
The input arrays: [[34 23] [90 34]] [[90 34] [43 23]] The Outer product of the given input arrays: [[3060 1156 1462 782] [2070 782 989 529] [8100 3060 3870 2070] [3060 1156 1462 782]]
示例
现在,让我们尝试计算 3D 数组的外积。
import numpy as np a = np.array([[[34,23],[90,34]],[[12,5],[14,5]]]) b = np.array([[[90,34],[43,23]],[[1,22],[7,2]]]) print("The input arrays:",a,b) outer_product = np.outer(a,b) print("The Outer product of the given input arrays:",outer_product)
输出
The input arrays: [[[34 23] [90 34]] [[12 5] [14 5]]] [[[90 34] [43 23]] [[ 1 22] [ 7 2]]] The Outer product of the given input arrays: [[3060 1156 1462 782 34 748 238 68] [2070 782 989 529 23 506 161 46] [8100 3060 3870 2070 90 1980 630 180] [3060 1156 1462 782 34 748 238 68] [1080 408 516 276 12 264 84 24] [ 450 170 215 115 5 110 35 10] [1260 476 602 322 14 308 98 28] [ 450 170 215 115 5 110 35 10]]
以上就是使用NumPy在Python中计算给定两个向量的外积的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。