在Python中返回多维向量的点积

在Python中返回多维向量的点积

要返回两个多维向量的点积,请使用Python中的numpy.vdot()方法。vdot(a, b)函数处理复数与dot(a, b)不同。如果第一个参数是复数,则使用第一个参数的共轭进行点积计算。vdot处理多维数组与dot不同:它不执行矩阵乘法,而是首先将输入参数展平为1-D向量。因此,它只适用于向量。

该方法返回a和b的点积。根据a和b的类型,可以是int、float或complex。第一个参数是a。如果a是复数,则在计算点乘之前取共轭。b是点积的第二个参数。

步骤

首先,导入所需的库-

import numpy as np

使用array()方法创建两个numpy多维数组 –

arr1 = np.array([[5, 10],[15, 20]])
arr2 = np.array([[3, 6],[9, 12]])

显示数组 –

print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

检查两个数组的尺寸 –

print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

检查两个数组的形状-

print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

要返回两个多维向量的点积,可以在Python中使用numpy.vdot()方法 −

print("\nResult...\n",np.vdot(arr1, arr2))

示例

import numpy as np

# Creating two numpy Multi-Dimensional array using the array() method
arr1 = np.array([[5, 10],[15, 20]])
arr2 = np.array([[3, 6],[9, 12]])

# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

# To return the dot product of two multi-dimensional vectors, use the numpy.vdot() method in Python.
print("\nResult...\n",np.vdot(arr1, arr2))

Output

Array1...
[[ 5 10]
[15 20]]

Array2...
[[ 3 6]
[ 9 12]]

Dimensions of Array1...
2

Dimensions of Array2...
2

Shape of Array1...
(2, 2)

Shape of Array2...
(2, 2)

Result...
450

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程