在Python中获取两个数组的内积

在Python中获取两个数组的内积

要获取两个数组的内积,使用Python中的numpy.inner()方法。对于1-D数组的普通内积,在更高的维度上,它是最后一个轴上的乘积求和。参数分别为1和b,即两个向量。如果a和b不是标量,它们的最后一个维度必须匹配。

步骤

首先,导入所需的库−

import numpy as np

使用array()方法创建两个numpy一维数组:

arr1 = np.array([5, 10, 15])
arr2 = np.array([20, 25, 30])

显示数组 –

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)

要获取两个数组的内积,请使用numpy.inner()方法 –

print("\nResult (Inner Product)...\n",np.inner(arr1, arr2))

示例

import numpy as np

# Creating two numpy One-Dimensional array using the array() method
arr1 = np.array([5, 10, 15])
arr2 = np.array([20, 25, 30])

# 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 get the Inner product of two arrays, use the numpy.inner() method in Python
print("\nResult (Inner Product)...\n",np.inner(arr1, arr2))

输出

Array1...
[ 5 10 15]

Array2...
[20 25 30]

Dimensions of Array1...
1

Dimensions of Array2...
1

Shape of Array1...
(3,)

Shape of Array2...
(3,)

Result (Inner Product)...
800

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程