두 개의 텐서 a와 b, 그리고 두 개의 배열류 객체(a_axes, b_axes)를 담은 배열류 객체가 주어졌을 때, 지정된 축을 따라 a와 b의 요소(성분)들의 곱을 합산하는 것이 텐서 내적(tensor dot product)입니다. 세 번째 인자는 음수가 아닌 단일 정수형 스칼라 N일 수도 있는데, 이 경우에는 a의 마지막 N개 차원과 b의 첫 N개 차원이 합산됩니다.
차원이 서로 다른 배열에 대해 텐서 내적을 계산하려면 Python에서 numpy.tensordot() 메서드를 사용하면 됩니다. 여기서 매개변수 a와 b는 "내적"할 텐서를 의미합니다.
axes 매개변수가 정수(int) N이라면, a의 마지막 N개 축과 b의 첫 N개 축을 순서대로 합산합니다. 이때 서로 대응되는 축들의 크기는 반드시 일치해야 합니다.
단계별 진행 과정
먼저 필요한 라이브러리를 임포트합니다.
import numpy as np
array() 메서드를 사용하여 차원이 서로 다른 두 개의 NumPy 배열을 생성합니다.
arr1 = np.array(range(1, 9))
arr1.shape = (2, 2, 2)
arr2 = np.array(('p', 'q', 'r', 's'), dtype=object)
arr2.shape = (2, 2)생성한 배열을 화면에 출력합니다.
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)두 배열의 차원(ndim)을 확인합니다.
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)두 배열의 형태(shape)를 확인합니다.
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)차원이 다른 배열에 대해 텐서 내적을 계산하기 위해 numpy.tensordot() 메서드를 사용합니다.
print("\nTensor dot product...\n", np.tensordot(arr1, arr2, axes = 1))
전체 예제 코드
import numpy as np
# array() 메서드를 사용하여 차원이 다른 두 개의 NumPy 배열 생성
arr1 = np.array(range(1, 9))
arr1.shape = (2, 2, 2)
arr2 = np.array(('p', 'q', 'r', 's'), dtype=object)
arr2.shape = (2, 2)
# 배열 출력
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)
# 두 배열의 차원 확인
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)
# 두 배열의 형태(shape) 확인
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)
# 차원이 다른 배열에 대한 텐서 내적 계산을 위해 numpy.tensordot() 메서드 사용
# a, b 매개변수는 "내적"할 텐서입니다.
print("\nTensor dot product...\n", np.tensordot(arr1, arr2, axes = 1))실행 결과
Array1... [[[1 2] [3 4]] [[5 6] [7 8]]] Array2... [['p' 'q'] ['r' 's']] Dimensions of Array1... 3 Dimensions of Array2... 2 Shape of Array1... (2, 2, 2) Shape of Array2... (2, 2) Tensor dot product... [[['prr' 'qss'] ['ppprrrr' 'qqqssss']] [['ppppprrrrrr' 'qqqqqssssss'] ['ppppppprrrrrrrr' 'qqqqqqqssssssss']]]