กำหนดเมตริกซ์สองตัว a และ b และอ็อบเจ็กต์ array_like ที่มีอ็อบเจ็กต์ array_like สองตัว (a_axes,b_axes) รวมผลคูณขององค์ประกอบ a และ b (ส่วนประกอบ) เหนือแกนที่ระบุโดย a_axes และ b_axes อาร์กิวเมนต์ที่สามสามารถเป็นสเกลาร์ integer_like ที่ไม่ใช่ค่าลบเดียว N; ถ้าเป็นเช่นนั้น มิติ N สุดท้ายของ a และ N แรกของ b จะถูกรวมเข้าด้วยกัน
ในการคำนวณผลิตภัณฑ์เทนเซอร์ดอท ให้ใช้เมธอด numpy.tensordot() ใน Python พารามิเตอร์ a, b คือเทนเซอร์ถึง "จุด" พารามิเตอร์แกน integer_like หากเป็น int N ให้รวมค่า Naxes สุดท้ายของ a และ N แกนแรกของ b ตามลำดับ ขนาดของแกนที่เกี่ยวข้องต้องตรงกัน
ขั้นตอน
ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import numpy as np
การสร้างอาร์เรย์ 3 มิติจำนวน 2 ชุดโดยใช้เมธอด array() -
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)
ในการคำนวณผลิตภัณฑ์เทนเซอร์ดอท ให้ใช้เมธอด numpy.tensordot() ใน Python พารามิเตอร์ 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.]]