Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 Einstein 합산 규칙을 ​​사용하여 행렬의 추적 가져오기

<시간/>

einsum() 메서드는 피연산자에 대한 Einstein 합산 규칙을 ​​평가합니다. 아인슈타인 합산 규칙을 ​​사용하여 많은 일반적인 다차원 선형 대수 배열 연산을 간단한 방식으로 나타낼 수 있습니다. 암시적 모드에서 einsum은 이러한 값을 계산합니다.

명시적 모드에서 einsum은 합산을 과도하게 지정한 첨자 레이블을 비활성화하거나 강제 적용하여 고전적인 Einstein 합산 연산으로 간주되지 않을 수 있는 다른 배열 연산을 계산할 수 있는 유연성을 제공합니다.

Einstein 합산 규칙을 ​​사용하여 행렬의 자취를 얻으려면 Python에서 numpy.einsum() 메서드를 사용하십시오. 첫 번째 매개변수는 첨자입니다. 아래 첨자 레이블의 쉼표로 구분된 목록으로 합계를 위한 아래 첨자를 지정합니다. 두 번째 매개변수는 피연산자입니다. 작업을 위한 배열입니다.

단계

먼저 필요한 라이브러리를 가져옵니다 -

import numpy as np

arange() 및 reshape() 메서드를 사용하여 numpy 배열 만들기 -

arr = np.arange(16).reshape(4,4)

배열 표시 -

print("Our Array...\n",arr)

치수 확인 -

print("\nDimensions of our Array...\n",arr.ndim)

데이터 유형 가져오기 -

print("\nDatatype of our Array object...\n",arr.dtype)

모양 가져오기 -

print("\nShape of our Array object...\n",arr.shape)

Einstein 합산 규칙을 ​​사용하여 행렬의 추적을 얻으려면 numpy.einsum() 메서드 inPython −

를 사용하세요.
print("\nResult (trace)...\n",np.einsum('ii', arr))

예시

import numpy as np

# Creating a numpy array using the arange() and reshape() method
arr = np.arange(16).reshape(4,4)

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# Get the Shape
print("\nShape of our Array object...\n",arr.shape)

# To get the trace of a matrix with Einstein summation convention, use the numpy.einsum() method in Python.
print("\nResult (trace)...\n",np.einsum('ii', arr))

출력

Our Array...
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]

Dimensions of our Array...
2

Datatype of our Array object...
int64

Shape of our Array object...
(4, 4)

Result (trace)...
30