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

Python NumPy로 주어진 차수의 Pseudo-Vandermonde 행렬 생성하는 방법

Python NumPy에서 주어진 차수의 Pseudo-Vandermonde(유사 반데르몽드) 행렬을 생성하려면 polynomial.polyvander2d() 함수를 사용합니다. 이 메서드는 지정된 차수(deg)와 샘플 포인트 (x, y)에 대한 유사 반데르몽드 행렬을 반환합니다.

polyvander2d() 함수의 주요 매개변수

x, y: 점(point) 좌표를 담고 있는 배열로, 두 배열은 모두 동일한 shape을 가져야 합니다. 요소 중 하나라도 복소수가 포함되어 있으면 dtype은 complex128로, 그렇지 않으면 float64로 자동 변환됩니다. 스칼라 값은 1차원 배열로 변환됩니다.

deg: [x_deg, y_deg] 형태의 최대 차수 리스트입니다. 예를 들어 [2, 3]은 x 방향 최대 차수 2, y 방향 최대 차수 3을 의미합니다.

구현 단계

1단계: 필요한 라이브러리 임포트

import numpy as np
from numpy.polynomial.polynomial import polyvander2d

2단계: 점 좌표 배열 생성

numpy.array() 메서드를 사용하여 동일한 shape을 가진 x, y 좌표 배열을 생성합니다.

x = np.array([1, 2])
y = np.array([3, 4])

3단계: 배열 정보 확인

생성된 배열과 각 배열의 데이터 타입, 차원(ndim), 형태(shape)를 출력하여 확인합니다.

print("Array1...\n", x)
print("\nArray2...\n", y)

print("\nArray1 datatype...\n", x.dtype)
print("\nArray2 datatype...\n", y.dtype)

print("\nDimensions of Array1...\n", x.ndim)
print("\nDimensions of Array2...\n", y.ndim)

print("\nShape of Array1...\n", x.shape)
print("\nShape of Array2...\n", y.shape)

4단계: Pseudo-Vandermonde 행렬 생성

x 방향 차수를 2, y 방향 차수를 3으로 설정하고 polyvander2d()를 호출합니다.

x_deg, y_deg = 2, 3
print("\nResult...\n", polyvander2d(x, y, [x_deg, y_deg]))

전체 예제 코드

import numpy as np
from numpy.polynomial.polynomial import polyvander2d

# numpy.array() 메서드로 동일한 shape의 점 좌표 배열 생성
x = np.array([1, 2])
y = np.array([3, 4])

# 배열 출력
print("Array1...\n", x)
print("\nArray2...\n", y)

# 데이터 타입 출력
print("\nArray1 datatype...\n", x.dtype)
print("\nArray2 datatype...\n", y.dtype)

# 두 배열의 차원 확인
print("\nDimensions of Array1...\n", x.ndim)
print("\nDimensions of Array2...\n", y.ndim)

# 두 배열의 형태(shape) 확인
print("\nShape of Array1...\n", x.shape)
print("\nShape of Array2...\n", y.shape)

# 주어진 차수의 Pseudo-Vandermonde 행렬 생성
# 이 메서드는 deg 차수와 샘플 포인트 (x, y)에 대한 행렬을 반환합니다.
x_deg, y_deg = 2, 3
print("\nResult...\n", polyvander2d(x, y, [x_deg, y_deg]))

실행 결과

Array1...
    [1 2]

Array2...
    [3 4]

Array1 datatype...
int64

Array2 datatype...
int64

Dimensions of Array1...
1

Dimensions of Array2...
1

Shape of Array1...
(2,)

Shape of Array2...
(2,)

Result...
    [[ 1.  3.  9. 27.  1.  3.  9. 27.  1.  3.  9. 27.]
     [ 1.  4. 16. 64.  2.  8. 32. 128.  4. 16. 64. 256.]]

결과 해석

출력된 행렬의 각 열은 x와 y의 거듭제곱 항들을 나타냅니다. 차수가 [2, 3]이므로 x⁰y⁰부터 x²y³까지 총 (2+1)×(3+1) = 12개의 열이 생성됩니다. 예를 들어 첫 번째 샘플 포인트 (1, 3)의 경우 x=1이므로 모든 x 거듭제곱이 1이 되고, y값인 3의 거듭제곱(3⁰=1, 3¹=3, 3²=9, 3³=27)이 반복되어 나타납니다. 이러한 유사 반데르몽드 행렬은 2변수 다항식의 최소제곱 피팅(least squares fitting) 등에 활용됩니다.