在Python中使用爱因斯坦求和约定进行标量乘法

在Python中使用爱因斯坦求和约定进行标量乘法

要使用爱因斯坦求和约定进行标量乘法,可以在Python中使用numpy.einsum()方法。第一个参数是下标,它指定了用于求和的下标标签的逗号分隔列表。第二个参数是操作数。这些是进行操作的数组。

einsum()方法在操作数上计算爱因斯坦求和约定。使用爱因斯坦求和约定,可以以一种简单的方式表示许多常见的多维线性代数数组操作。在隐式模式下,einsum计算这些值。在显式模式下,einsum提供了进一步的灵活性,可以计算其他可能不被认为是经典的爱因斯坦求和操作的数组操作,通过禁用或强制对指定的下标标签进行求和。

步骤

首先,导入所需的库:

import numpy as np

使用numpy.arange()和reshape()创建一个数组

arr = np.arange(6).reshape(2,3)

val是标量-。

val = 2

显示数组 –

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)

使用爱因斯坦求和约定来进行标量乘法,请使用numpy.einsum()方法−

print("\nResult (scalar multiplication)...\n",np.einsum('..., ...', val, arr))

示例

import numpy as np

# Create an array using the numpy.arange() and reshape()
arr = np.arange(6).reshape(2,3)

# The val is the scalar
val = 2

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

# Check the datatype
print("\nDatatype of Array...\n",arr.dtype)

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

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

# To perform scalar multiplication with Einstein summation convention, use the numpy.einsum() method in Python.
print("\nResult (scalar multiplication)...\n",np.einsum('..., ...', val, arr))

输出

Array...
[[0 1 2]
[3 4 5]]

Datatype of Array...
int64

Dimensions of Array...
2

Shape of Array...
(2, 3)

Result (scalar multiplication)...
[[ 0 2 4]
[ 6 8 10]]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程