在numpy中找到子数组的点积

时间:2022-11-24 21:25:18

In numpy, the numpy.dot() function can be used to calculate the matrix product of two 2D arrays. I have two 3D arrays X and Y (say), and I'd like to calculate the matrix Z where Z[i] == numpy.dot(X[i], Y[i]) for all i. Is this possible to do non-iteratively?

在numpy中,可以使用numpy.dot()函数计算两个二维数组的矩阵乘积。我有两个3D数组X和Y(比方说),我想计算Z[I] = numpy的矩阵Z。点(X[i], Y[i])表示所有的i,是否可以用非迭代的方法?

1 个解决方案

#1


7  

How about:

如何:

from numpy.core.umath_tests import inner1d
Z = inner1d(X,Y)

For example:

例如:

X = np.random.normal(size=(10,5))
Y = np.random.normal(size=(10,5))
Z1 = inner1d(X,Y)
Z2 = [np.dot(X[k],Y[k]) for k in range(10)]
print np.allclose(Z1,Z2)

returns True

返回True

Edit Correction since I didn't see the 3D part of the question

编辑修正,因为我没有看到问题的3D部分

from numpy.core.umath_tests import matrix_multiply
X = np.random.normal(size=(10,5,3))
Y = np.random.normal(size=(10,3,5))
Z1 = matrix_multiply(X,Y)
Z2 = np.array([np.dot(X[k],Y[k]) for k in range(10)])
np.allclose(Z1,Z2)  # <== returns True

This works because (as the docstring states), matrix_multiplyprovides

这是因为(作为docstring状态),matrix_multiplyprovides

matrix_multiply(x1, x2[, out]) matrix

matrix_multiply(x1,x2[,])矩阵

multiplication on last two dimensions

最后二维乘法

#1


7  

How about:

如何:

from numpy.core.umath_tests import inner1d
Z = inner1d(X,Y)

For example:

例如:

X = np.random.normal(size=(10,5))
Y = np.random.normal(size=(10,5))
Z1 = inner1d(X,Y)
Z2 = [np.dot(X[k],Y[k]) for k in range(10)]
print np.allclose(Z1,Z2)

returns True

返回True

Edit Correction since I didn't see the 3D part of the question

编辑修正,因为我没有看到问题的3D部分

from numpy.core.umath_tests import matrix_multiply
X = np.random.normal(size=(10,5,3))
Y = np.random.normal(size=(10,3,5))
Z1 = matrix_multiply(X,Y)
Z2 = np.array([np.dot(X[k],Y[k]) for k in range(10)])
np.allclose(Z1,Z2)  # <== returns True

This works because (as the docstring states), matrix_multiplyprovides

这是因为(作为docstring状态),matrix_multiplyprovides

matrix_multiply(x1, x2[, out]) matrix

matrix_multiply(x1,x2[,])矩阵

multiplication on last two dimensions

最后二维乘法