在numpy中找到子数组的点积 [英] find the dot product of sub-arrays in numpy

查看:150
本文介绍了在numpy中找到子数组的点积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在numpy中,numpy.dot()函数可用于计算两个2D数组的矩阵乘积.我有两个3D数组X和Y(比如说),我想计算矩阵Z,其中所有iZ[i] == numpy.dot(X[i], Y[i]).这可以非迭代地进行吗?

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?

推荐答案

怎么样:

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

例如:

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)

返回True

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

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

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

之所以可行,是因为(作为文档字符串状态)matrix_multiply提供了

This works because (as the docstring states), matrix_multiplyprovides

matrix_multiply(x1,x2 [,out])矩阵

matrix_multiply(x1, x2[, out]) matrix

最后两个维度上的乘法

这篇关于在numpy中找到子数组的点积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆