在 Python 中計算張量點積
給定兩個張量 a 和 b,以及一個包含兩個類陣列物件的類陣列物件 (a_axes, b_axes),在由 a_axes 和 b_axes 指定的軸上對 a 和 b 的元素(分量)的乘積求和。第三個引數可以是單個非負整數型別的標量 N;如果是這樣,則對 a 的最後 N 維和 b 的前 N 維求和。
要計算張量點積,請在 Python 中使用 numpy.tensordot() 方法。引數 a、b 是要“點乘”的張量。引數 axes,整數型別 如果是整數 N,則按順序對 a 的最後 N 個軸和 b 的前 N 個軸求和。對應軸的大小必須匹配。
步驟
首先,匯入所需的庫:
import numpy as np
使用 array() 方法建立兩個 NumPy 3D 陣列:
arr1 = np.arange(60.).reshape(3,4,5) arr2 = np.arange(24.).reshape(4,3,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() 方法。引數 a、b 是要“點乘”的張量:
print("\nTensor dot product...\n", np.tensordot(arr1,arr2, axes=([1,0],[0,1])))
示例
import numpy as np
# Creating two numpy 3D arrays using the array() method
arr1 = np.arange(60.).reshape(3,4,5)
arr2 = np.arange(24.).reshape(4,3,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, use the numpy.tensordot() method in Python
# The a, b parameters are Tensors to “dot”.
print("\nTensor dot product...\n", np.tensordot(arr1,arr2, axes=([1,0],[0,1])))輸出
Array1... [[[ 0. 1. 2. 3. 4.] [ 5. 6. 7. 8. 9.] [10. 11. 12. 13. 14.] [15. 16. 17. 18. 19.]] [[20. 21. 22. 23. 24.] [25. 26. 27. 28. 29.] [30. 31. 32. 33. 34.] [35. 36. 37. 38. 39.]] [[40. 41. 42. 43. 44.] [45. 46. 47. 48. 49.] [50. 51. 52. 53. 54.] [55. 56. 57. 58. 59.]]] Array2... [[[ 0. 1.] [ 2. 3.] [ 4. 5.]] [[ 6. 7.] [ 8. 9.] [10. 11.]] [[12. 13.] [14. 15.] [16. 17.]] [[18. 19.] [20. 21.] [22. 23.]]] Dimensions of Array1... 3 Dimensions of Array2... 3 Shape of Array1... (3, 4, 5) Shape of Array2... (4, 3, 2) Tensor dot product... [[4400. 4730.] [4532. 4874.] [4664. 5018.] [4796. 5162.] [4928. 5306.]]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP