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

파이썬 NumPy outer() 함수로 두 다차원 배열의 외적 구하는 방법

파이썬에서 두 개의 다차원 배열의 외적(Outer Product)을 구하려면 numpy.outer() 메서드를 사용하면 됩니다. 이 함수는 입력된 벡터들을 자동으로 평탄화한 뒤 모든 요소 쌍의 곱을 행렬 형태로 반환합니다.

numpy.outer()의 주요 매개변수는 다음과 같습니다.

  • a : 첫 번째 입력 벡터. 1차원이 아닌 경우 자동으로 평탄화(flatten)됩니다.
  • b : 두 번째 입력 벡터. 역시 1차원이 아니면 평탄화되어 처리됩니다.
  • out : 결과를 저장할 위치(선택 사항).

두 벡터 a = [a0, a1, ..., aM]과 b = [b0, b1, ..., bN]가 주어졌을 때, 외적 결과는 다음과 같은 형태의 행렬이 됩니다.

[[a0*b0   a0*b1   ...   a0*bN ]
 [a1*b0    .       .      .    ]
 [ ...     .       .      .    ]
 [aM*b0    .       .    aM*bN ]]

구현 단계

먼저 필요한 라이브러리를 임포트합니다.

import numpy as np

array() 메서드를 사용해 두 개의 2차원 넘파이 배열을 생성합니다.

arr1 = np.array([[5, 10], [15, 20]])
arr2 = np.array([[6, 12], [18, 24]])

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

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.outer() 메서드를 호출하여 두 배열의 외적을 계산합니다.

print("\nResult (Outer Product)...\n", np.outer(arr1, arr2))

전체 예제 코드

import numpy as np

# array() 메서드로 두 개의 2차원 넘파이 배열 생성
arr1 = np.array([[5, 10], [15, 20]])
arr2 = np.array([[6, 12], [18, 24]])

# 배열 출력
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.outer() 메서드로 두 다차원 배열의 외적 계산
print("\nResult (Outer Product)...\n", np.outer(arr1, arr2))

실행 결과

Array1...
[[ 5 10]
 [15 20]]

Array2...
[[ 6 12]
 [18 24]]

Dimensions of Array1...
2

Dimensions of Array2...
2

Shape of Array1...
(2, 2)

Shape of Array2...
(2, 2)

Result (Outer Product)...
[[ 30  60  90 120]
 [ 60 120 180 240]
 [ 90 180 270 360]
 [120 240 360 480]]

실행 결과를 보면 각 (2, 2) 크기의 2차원 배열이 내부적으로 4개의 요소를 가진 1차원 벡터로 평탄화된 후, 두 벡터의 모든 요소 쌍에 대한 곱이 담긴 4×4 크기의 외적 행렬이 반환되는 것을 확인할 수 있습니다.