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

Python NumPy outer() 함수로 문자 벡터와 배열의 외적(Outer Product) 구하기

두 개의 벡터 a = [a0, a1, ..., aM]과 b = [b0, b1, ..., bN]가 주어졌을 때, 외적(Outer Product)은 다음과 같이 계산됩니다.

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

문자(letter)로 이루어진 벡터와 배열의 외적을 구하려면 Python의 numpy.outer() 메서드를 사용하면 됩니다.

numpy.outer()의 매개변수

  • a: 첫 번째 입력 벡터입니다. 입력이 1차원이 아니면 자동으로 평탄화(flatten)됩니다.
  • b: 두 번째 입력 벡터입니다. 마찬가지로 1차원이 아니면 자동으로 평탄화됩니다.
  • out: 결과를 저장할 위치를 지정하는 선택적 매개변수입니다.

단계별 구현 방법

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

import numpy as np

array() 메서드를 사용해 두 개의 1차원 NumPy 배열을 생성합니다. 첫 번째 배열은 문자로 이루어진 벡터이고, 두 번째 배열은 정수 배열입니다.

arr1 = np.array(['p', 'q', 'r', 's'], dtype=object)
arr2 = np.array([2, 3, 1, 3])

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

print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

두 배열의 차원(dimension)을 확인합니다.

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() 메서드로 두 개의 1차원 NumPy 배열 생성
# 첫 번째 배열은 문자 벡터
# 두 번째 배열은 정수 배열
arr1 = np.array(['p', 'q', 'r', 's'], dtype=object)
arr2 = np.array([2, 3, 1, 3])

# 배열 출력
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...
['p' 'q' 'r' 's']

Array2...
[2 3 1 3]

Dimensions of Array1...
1

Dimensions of Array2...
1

Shape of Array1...
(4,)

Shape of Array2...
(4,)

Result (Outer Product)...
[['pp' 'ppp' 'p' 'ppp']
 ['qq' 'qqq' 'q' 'qqq']
 ['rr' 'rrr' 'r' 'rrr']
 ['ss' 'sss' 's' 'sss']]

위 결과에서 볼 수 있듯이, dtype=object로 지정된 문자 배열과 정수 배열의 외적은 각 요소가 반복된 문자열 형태로 반환됩니다. 예를 들어 'p' × 3은 'ppp'가 되는 식입니다. 이처럼 numpy.outer()는 숫자뿐만 아니라 객체 타입 배열에도 적용할 수 있어 다양한 활용이 가능합니다.