Python NumPy에서 두 개의 1차원 배열의 크로네커 곱(Kronecker product)을 구하려면 numpy.kron() 메서드를 사용합니다. 크로네커 곱은 첫 번째 배열의 각 요소로 두 번째 배열을 스케일링한 블록들로 구성된 복합 배열입니다.
크로네커 곱의 동작 원리
이 함수는 a와 b의 차원 수가 같다고 가정하며, 필요한 경우 차원이 더 작은 배열 앞에 1을 추가해 차원을 맞춥니다. 예를 들어 a.shape = (r0, r1, ..., rN)이고 b.shape = (s0, s1, ..., sN)이라면, 크로네커 곱의 결과 배열 형태는 (r0*s0, r1*s1, ..., rN*sN)이 됩니다. 결과의 각 요소는 a와 b의 요소들을 곱한 값으로, 다음 수식처럼 명시적으로 배치됩니다.
kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
구현 단계
먼저 필요한 라이브러리를 임포트합니다.
import numpy as np
array() 메서드를 사용해 두 개의 1차원 NumPy 배열을 생성합니다.
arr1 = np.array([1, 10, 100]) arr2 = np.array([5, 6, 7])
생성한 배열을 화면에 출력합니다.
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.kron() 메서드를 호출해 두 배열의 크로네커 곱을 계산하고 출력합니다.
print("\nResult (Kronecker product)...\n", np.kron(arr1, arr2))전체 예제 코드
import numpy as np
# array() 메서드로 두 개의 1차원 NumPy 배열 생성
arr1 = np.array([1, 10, 100])
arr2 = np.array([5, 6, 7])
# 배열 출력
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.kron() 메서드로 크로네커 곱 계산
print("\nResult (Kronecker product)...\n", np.kron(arr1, arr2))실행 결과
Array1... [ 1 10 100] Array2... [5 6 7] Dimensions of Array1... 1 Dimensions of Array2... 1 Shape of Array1... (3,) Shape of Array2... (3,) Result (Kronecker product)... [ 5 6 7 50 60 70 500 600 700]
실행 결과를 보면 길이가 3인 두 배열의 크로네커 곱은 길이가 9(=3×3)인 배열이 되며, 첫 번째 배열의 각 요소에 두 번째 배열 전체가 순서대로 스케일링되어 배치되는 것을 확인할 수 있습니다.