使用Python中的双收缩计算具有不同维度的张量点积

使用Python中的双收缩计算具有不同维度的张量点积

给定两个张量a和b,以及一个包含两个数组对象(a_axes,b_axes)的array_like对象,在由a_axes和b_axes指定的轴上求出a和b的元素(分量)的乘积之和。第三个参数可以是一个单个非负整数标量N;如果是这样的话,则对a的最后N个维度和b的前N个维度进行求和。

要计算具有不同维度的数组的张量点积,请使用Python中的numpy.tensordot()方法。a、b参数是要进行“点积”的张量。axes参数是整数标量,如果是一个整数N,则按顺序对a的最后N个轴和b的前N个轴进行求和。相应轴的大小必须匹配。axes = 2用于张量的双收缩。

步骤

首先,导入所需的库−

import numpy as np

使用array()方法创建具有不同维度的两个numpy数组 −

arr1 = np.array(range(1, 9))
arr1.shape = (2, 2, 2)

arr2 = np.array(('p', 'q', 'r', 's'), dtype=object)
arr2.shape = (2, 2)

显示数组 –

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.tensordot()方法−

print("\nTensor dot product...\n", np.tensordot(arr1, arr2, axes = 2))

示例

import numpy as np

# Creating two numpy arrays with different dimensions using the array() method
arr1 = np.array(range(1, 9))
arr1.shape = (2, 2, 2)
arr2 = np.array(('p', 'q', 'r', 's'), dtype=object)
arr2.shape = (2, 2)

# 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 compute the tensor dot product for arrays with different dimensions, use the numpy.tensordot() method in Python
print("\nTensor dot product...\n", np.tensordot(arr1, arr2, axes = 2))

输出

Array1...
[[[1 2]
[3 4]]

[[5 6]
[7 8]]]

Array2...
[['p' 'q']
['r' 's']]

Dimensions of Array1...
3

Dimensions of Array2...
2

Shape of Array1...
(2, 2, 2)

Shape of Array2...
(2, 2)

Tensor dot product...
['pqqrrrssss' 'pppppqqqqqqrrrrrrrssssssss']

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程