用 Python 中的類陣列軸計算具有不同維度的陣列的張量點積


提供兩個張量 a 和 b,以及包含兩個類陣列物件(a_axes、b_axes)的類陣列物件,按照 a_axes 和 b_axes 指定的軸對 a 和 b 的元素(分量)的積求和。第三個引數可以是單個非負整數標量 N;如果這樣,a 的最後 N 個維度和 b 的前 N 個維度進行求和。

步驟

首先,匯入所需的庫 −

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, ((0, 1), (0, 1))))

例子

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, ((0, 1), (0, 1))))

輸出

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...
['pqqqrrrrrsssssss' 'ppqqqqrrrrrrssssssss']

更新時間: 02-Mar-2022

205 次瀏覽

開啟你 職業 生涯

完成本課程獲得認證

入門
廣告
© . All rights reserved.