使用Einstein求和约定在Python中进行向量内积

使用Einstein求和约定在Python中进行向量内积

要使用Einstein求和约定计算向量的内积,请在Python中使用numpy.einsum()方法。第一个参数是下标。它指定求和的下标作为逗号分隔的下标标签列表。第二个参数是操作数。这些是用于操作的数组。

einsum()方法对操作数进行Einstein求和约定的评估。使用Einstein求和约定,许多常见的多维线性代数数组操作可以以简单的方式表示。在隐式模式下,einsum计算这些值。

在显式模式下,einsum提供了进一步的灵活性,以计算可能不被视为经典Einstein求和操作的其他数组操作,通过禁用或强制对指定的下标标签进行求和。

步骤

首先,导入所需的库 –

import numpy as np

使用arange()和reshape()方法创建一个numpy数组:

arr = np.arange(4)

显示数组 –

print("Our Array...\n",arr)

检查尺寸 –

print("\nDimensions of our Array...\n",arr.ndim)

获取数据类型 −

print("\nDatatype of our Array object...\n",arr.dtype)

获取形状−

print("\nShape of our Array object...\n",arr.shape)

使用Einstein求和约定计算向量的内积,可以使用numpy.einsum()方法−

print("\nResult (inner product)...\n",np.einsum('i,i', arr, arr))

示例

import numpy as np

# Creating a numpy array using the arange() and reshape() method
arr = np.arange(4)

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# Get the Shape
print("\nShape of our Array object...\n",arr.shape)

# To compute inner product of vectors with Einstein summation convention, use the numpy.einsum() method in Python.
print("\nResult (inner product)...\n",np.einsum('i,i', arr, arr))

输出

Our Array...
[0 1 2 3]

Dimensions of our Array...
1

Datatype of our Array object...
int64

Shape of our Array object...
(4,)

Result (inner product)...
14

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程