Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 텐서 내적 계산

<시간/>

두 개의 텐서, a 및 b와 두 개의 array_like 객체(a_axes,b_axes)를 포함하는 array_like 객체가 주어지면 a_axes 및 b_axes로 지정된 축에 대해 a와 b의 요소(구성 요소)의 곱을 합산합니다. 세 번째 인수는 음이 아닌 단일 정수형 스칼라 N일 수 있습니다. 그렇다면 b의 마지막 N 차원과 b의 처음 N 차원을 합산합니다.

텐서 내적을 계산하려면 Python에서 numpy.tensordot() 메서드를 사용합니다. b파라미터는 "점"에 대한 텐서입니다. 축 매개변수 integer_like int N인 경우 b의 마지막 Nax와 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.]]