两个向量的外积是向量 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 npa = 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 npa = 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 npa = 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中计算给定两个向量的外积的详细内容。