使用numpy的逐元素矩阵乘法(Hadamard乘积)

时间:2019-07-14 08:16:43

标签: python numpy

因此,假设我有两个元素为矩阵的numpy ndarrays。对于这两个数组,我需要逐个元素进行乘法,但是,两个矩阵元素之间应该存在矩阵乘法。当然,我可以使用for循环实现此功能,但是我一直在寻求解决此问题而无需使用显式的for循环。我该如何实现?

编辑:此for循环执行我想做的事情。我正在使用python 2.7

n = np.arange(8).reshape(2,2,1,2)
l = np.arange(1,9).reshape(2,2,2,1)
k = np.zeros((2,2))
for i in range(len(n)):
    for j in range(len(n[i])):
        k[i][j] =  np.asscalar(n[i][j].dot(l[i][j]))
print k

2 个答案:

答案 0 :(得分:3)

假设您的矩阵数组为n+2维数组AB。您想要实现的只是C = A@B

示例

outer_dims = 2,3,4
inner_dims = 4,5,6

A = np.random.randint(0,10,(*outer_dims, *inner_dims[:2]))
B = np.random.randint(0,10,(*outer_dims, *inner_dims[1:]))

C = A@B

# check
for I in np.ndindex(outer_dims):
    assert (C[I] == A[I]@B[I]).all()

更新:Py2版本;谢谢@ hpaulj,Divakar

A = np.random.randint(0,10, outer_dims + inner_dims[:2])
B = np.random.randint(0,10, outer_dims + inner_dims[1:])

C = np.matmul(A,B)

# check
for I in np.ndindex(outer_dims):
    assert (C[I] == np.matmul(A[I],B[I])).all()

答案 1 :(得分:0)

如果我理解正确,则可能可行:

import numpy as np

a = np.array([[1,1],[1,0]])
b = np.array([[3,4],[5,4]])

x = np.array([[a,b],[b,a]])
y = np.array([[a,a],[b,b]])

result = np.array([_x @ _y for _x, _y in zip(x,y)])