Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python NumPy로 차원이 다른 두 배열의 크로네커(Kronecker) 곱 구하기

차원이 서로 다른 두 배열의 크로네커 곱(Kronecker product)을 구하려면 Python NumPy의 numpy.kron() 메서드를 사용하면 됩니다. 크로네커 곱은 첫 번째 배열의 각 요소로 두 번째 배열 전체를 스케일링한 블록들로 구성된 복합 배열입니다.

numpy.kron() 함수는 두 배열 a와 b의 차원 수가 같다고 가정합니다. 만약 차원 수가 다르다면, 더 작은 쪽 배열의 앞쪽에 크기가 1인 축을 자동으로 추가하여 맞춰줍니다. 예를 들어 a.shape = (r0, r1, ..., rN)이고 b.shape = (s0, s1, ..., sN)이라면, 크로네커 곱의 결과 shape은 (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

arange()와 reshape() 메서드를 사용해 서로 다른 차원을 가진 두 개의 NumPy 배열을 생성합니다.

arr1 = np.arange(20).reshape((2,5,2))
arr2 = np.arange(6).reshape((2,3))

생성된 두 배열을 화면에 출력합니다.

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

# arange()와 reshape() 메서드로 서로 다른 차원의 두 배열 생성
arr1 = np.arange(20).reshape((2,5,2))
arr2 = np.arange(6).reshape((2,3))

# 배열 출력
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.kron() 메서드로 크로네커 곱 계산
print("\nResult (Kronecker product)...\n",np.kron(arr1, arr2))

실행 결과

Array1...
[[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]]

[[10 11]
[12 13]
[14 15]
[16 17]
[18 19]]]

Array2...
[[0 1 2]
[3 4 5]]

Dimensions of Array1...
3

Dimensions of Array2...
2

Shape of Array1...
(2, 5, 2)

Shape of Array2...
(2, 3)

Result (Kronecker product)...
[[[ 0 0 0 0 1 2]
[ 0 0 0 3 4 5]
[ 0 2 4 0 3 6]
[ 6 8 10 9 12 15]
[ 0 4 8 0 5 10]
[12 16 20 15 20 25]
[ 0 6 12 0 7 14]
[18 24 30 21 28 35]
[ 0 8 16 0 9 18]
[24 32 40 27 36 45]]

[[ 0 10 20 0 11 22]
[30 40 50 33 44 55]
[ 0 12 24 0 13 26]
[36 48 60 39 52 65]
[ 0 14 28 0 15 30]
[42 56 70 45 60 75]
[ 0 16 32 0 17 34]
[48 64 80 51 68 85]
[ 0 18 36 0 19 38]
[54 72 90 57 76 95]]]

위 실행 결과를 보면, 3차원 배열 arr1(shape: (2, 5, 2))과 2차원 배열 arr2(shape: (2, 3))의 크로네커 곱 결과는 자동으로 3차원 배열이 되며, 각 축의 크기는 해당 축 크기의 곱인 (2*2, 5*2, 2*3) = (2, 10, 6)으로 계산됩니다. 이처럼 numpy.kron()은 차원이 다른 배열도 자동으로 처리해 주므로 매우 편리합니다.