在Python中计算张量的点积
给定两个张量a和b,以及包含两个array_like对象(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
创建两个numpy的3D数组,使用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)
要计算张量的点积,可以使用Python中的numpy.tensordot()方法。参数a、b是要“dot”的张量 −
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.]]
极客笔记