假设我有一个(4*n)*(4*n)
块矩阵,我想将(n*n)
的每个块与相应的(4*4)
矩阵的不同系数相乘-在NumPy中如何做到这一点?
例如:
>>> mat
matrix([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
>>> x
array([[1, 2],
[3, 4]])
请求的结果应该是这样的:
>>> result
array([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 3, 4, 4],
[3, 3, 4, 4]])
一种方法是从x
:
result = np.multiply(mat, np.kron(x, np.ones((n,n))))
这是使用NumPy broadcasting
-
m1,n1 = x.shape
m2,n2 = mat.shape
out = (mat.reshape(m1,m2//m1,n1,n2//n1)*x[:,None,:,None]).reshape(m2,n2)
示例运行-
In [41]: mat
Out[41]:
array([[8, 8, 7, 2, 3, 4],
[2, 4, 7, 5, 4, 8],
[7, 2, 4, 5, 6, 5],
[4, 3, 3, 6, 5, 3],
[7, 3, 5, 8, 7, 7],
[2, 5, 2, 4, 2, 7]])
In [42]: x
Out[42]:
array([[1, 2],
[3, 4]])
In [43]: out
Out[43]:
array([[ 8, 8, 7, 4, 6, 8],
[ 2, 4, 7, 10, 8, 16],
[ 7, 2, 4, 10, 12, 10],
[12, 9, 9, 24, 20, 12],
[21, 9, 15, 32, 28, 28],
[ 6, 15, 6, 16, 8, 28]])
我认为@Tim Fuchs
的帖子中建议的np.kron
将是这里最安全的选择,而不需要摆弄输入数组的大小。为了提高性能,下面是比较kron
和broadcasting-based
方法在适当大小的输入数组上的一些计时——
In [56]: mat = np.random.randint(2,9,(100,100))
In [57]: x = np.random.randint(2,9,(50,50))
In [58]: n = 2
In [59]: m1,n1 = x.shape # Ignoring timings from these as negligible
...: m2,n2 = mat.shape
...:
In [60]: %timeit np.multiply(mat, np.kron(x, np.ones((n,n))))
1000 loops, best of 3: 312 µs per loop
In [61]: %timeit (mat.reshape(m1,m2//m1,n1,n2//n1)*x[:,None,:,None]).reshape(m2,n2)
10000 loops, best of 3: 83.7 µs per loop