在Python中获取两个不同维度数组的克罗内克积


要获取不同维度的两个数组的克罗内克积,可以使用 Python NumPy 中的 numpy.kron() 方法。计算克罗内克积,这是一个由第二个数组的块组成的复合数组,由第一个数组缩放。

该函数假设 a 和 b 的维度数相同,如有必要,则用 1 补充最小的维度。如果 a.shape = (r0,r1,..,rN) 且 b.shape = (s0,s1,...,sN),则克罗内克积的形状为 (r0*s0, r1*s1, ..., rN*SN)。元素是由 a 和 b 中的元素的乘积组成,通过 - 明确组织。

# kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]

步骤

首先,导入所需的库:

import numpy as np

使用 arange() 和 reshape() 方法创建两个不同维度的 NumPy 数组:

arr1 = np.arange(20).reshape((2,5,2)) arr2 = np.arange(6).reshape((2,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)

要获取两个数组的克罗内克积,请在 Python 中使用 numpy.kron() 方法:

print("\nResult (Kronecker product)...\n",np.kron(arr1, arr2))

示例

Open Compiler
import numpy as np # Creating two numpy arrays with different dimensions using the arange() and reshape() method arr1 = np.arange(20).reshape((2,5,2)) arr2 = np.arange(6).reshape((2,3)) # Display the arrays print("Array1...\n",arr1) print("\nArray2...\n",arr2) # Check the Dimensions of both the array print("\nDimensions of Array1...\n",arr1.ndim) print("\nDimensions of Array2...\n",arr2.ndim) # Check the Shape of both the array print("\nShape of Array1...\n",arr1.shape) print("\nShape of Array2...\n",arr2.shape) # To get the Kronecker product of two arrays, use the numpy.kron() method in Python Numpy print("\nResult (Kronecker product)...\n",np.kron(arr1, arr2))

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

Array1...
[[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]]

[[10 11]
[12 13]
[14 15]
[16 17]
[18 19]]]

Array2...
[[0 1 2]
[3 4 5]]

Dimensions of Array1...
3

Dimensions of Array2...
2

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

Shape of Array2...
(2, 3)

Result (Kronecker product)...
[[[ 0 0 0 0 1 2]
[ 0 0 0 3 4 5]
[ 0 2 4 0 3 6]
[ 6 8 10 9 12 15]
[ 0 4 8 0 5 10]
[12 16 20 15 20 25]
[ 0 6 12 0 7 14]
[18 24 30 21 28 35]
[ 0 8 16 0 9 18]
[24 32 40 27 36 45]]

[[ 0 10 20 0 11 22]
[30 40 50 33 44 55]
[ 0 12 24 0 13 26]
[36 48 60 39 52 65]
[ 0 14 28 0 15 30]
[42 56 70 45 60 75]
[ 0 16 32 0 17 34]
[48 64 80 51 68 85]
[ 0 18 36 0 19 38]
[54 72 90 57 76 95]]]

更新于:2022年3月2日

256 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告