在 Python 中計算不同維度陣列的張量點積
給定兩個張量 a 和 b,以及一個包含兩個類陣列物件的類陣列物件 (a_axes, b_axes),在由 a_axes 和 b_axes 指定的軸上對 a 和 b 的元素(分量)的乘積求和。第三個引數可以是一個單一的非負整數類標量 N;如果是這樣,則對 a 的最後 N 維和 b 的前 N 維求和。
要計算不同維度陣列的張量點積,請使用 numpy.tensordot() 方法。引數 a、b 是要“點積”的張量。引數 axes,整數類如果是一個整數 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)要計算不同維度陣列的張量點積,請在 Python 中使用 numpy.tensordot() 方法 -
print("\nTensor dot product...\n", np.tensordot(arr1, arr2))
示例
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))輸出
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']
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP