在 Python 中计算张量点积

pythonnumpyserver side programmingprogramming更新于 2024/5/14 9:48:17

给定两个张量 a 和 b,以及一个包含两个 array_like 对象的 array_like 对象 (a_axes,b_axes),将 a 和 b 元素 (分量) 在 a_axes 和 b_axes 指定的轴上的乘积相加。第三个参数可以是单个非负的 integer_like 标量 N;如果是,则将 a 的最后 N 个维度和 b 的前 N ​​个维度相加。

要计算张量点积,请使用 Python 中的 numpy.tensordot() 方法。a、b 参数是"点"的张量。axes 参数 integer_like 如果是 int 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

# 使用 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])))

输出

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.]]


相关文章


有用资源