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

Python에서 이중 수축을 사용하여 차원이 다른 배열에 대한 텐서 내적 계산

<시간/>

두 개의 텐서, a 및 b와 두 개의 array_like 객체(a_axes,b_axes)를 포함하는 array_like 객체가 주어지면 a_axes 및 b_axes로 지정된 축에 대해 a와 b의 요소(구성 요소)의 곱을 합산합니다. 세 번째 인수는 음이 아닌 단일 정수형 스칼라 N일 수 있습니다. 그렇다면 b의 마지막 N 차원과 b의 처음 N 차원을 합산합니다.

차원이 다른 배열에 대한 텐서 내적을 계산하려면 Python에서 numpy.tensordot() 메서드를 사용합니다. , b 매개변수는 "점"에 대한 텐서입니다. 축 매개변수 integer_like int N이면 b의 마지막 N축과 b의 처음 N축을 순서대로 합산합니다. 해당 축의 크기가 일치해야 합니다. 축 =2는 텐서 이중 수축용입니다.

단계

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

import numpy as np

array() 메서드를 사용하여 차원이 다른 두 개의 numpy 배열 만들기 -

arr1 = np.array(range(1, 9))
arr1.shape = (2, 2, 2)

arr2 = np.array(('p', 'q', 'r', 's'), dtype=object)
arr2.shape = (2, 2)

배열 표시 -

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.tensordot() 메서드 -

를 사용하세요.
print("\nTensor dot product...\n", np.tensordot(arr1, arr2, axes = 2))

예시

import numpy as np

# Creating two numpy arrays with different dimensions using the array() method
arr1 = np.array(range(1, 9))
arr1.shape = (2, 2, 2)
arr2 = np.array(('p', 'q', 'r', 's'), dtype=object)
arr2.shape = (2, 2)

# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

# To compute the tensor dot product for arrays with different dimensions, use the numpy.tensordot() method in Python
print("\nTensor dot product...\n", np.tensordot(arr1, arr2, axes = 2))
에서 numpy.tensordot() 메서드를 사용합니다.

출력

Array1...
[[[1 2]
[3 4]]

[[5 6]
[7 8]]]

Array2...
[['p' 'q']
['r' 's']]

Dimensions of Array1...
3

Dimensions of Array2...
2

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

Shape of Array2...
(2, 2)

Tensor dot product...
['pqqrrrssss' 'pppppqqqqqqrrrrrrrssssssss']