numpy 张量相关问题
我对 numpy 中的矩阵相乘有一个具体问题。 这是一个例子:
P=np.arange(30).reshape((-1,3))
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21, 22, 23],
[24, 25, 26],
[27, 28, 29]])
我想将每一行与其转置相乘,以获得每一行的 3x3 矩阵, 例如对于第一行:
P[0]*P[0][:,np.newaxis]
array([[0, 0, 0],
[0, 1, 2],
[0, 2, 4]])
并将结果存储在 3-d 矩阵 M 中:
M=np.zeros((10,3,3))
for i in range(10):
M[i] = P[i]*P[i][:,np.newaxis]
我认为可能有一种方法可以在不循环的情况下执行此操作,也许可以使用张量点,但找不到它。
有人有主意吗?
I have a specific issue with multiplying matrices in numpy.
Here is an example:
P=np.arange(30).reshape((-1,3))
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21, 22, 23],
[24, 25, 26],
[27, 28, 29]])
I want to multiply each row by its transpose in order to obtain a 3x3 matrix for each row,
for example for the first row:
P[0]*P[0][:,np.newaxis]
array([[0, 0, 0],
[0, 1, 2],
[0, 2, 4]])
and store the result in a 3-d matrix M:
M=np.zeros((10,3,3))
for i in range(10):
M[i] = P[i]*P[i][:,np.newaxis]
I think there might be a way to do this without looping, maybe with tensor-dot, but cannot find it.
Does someone have an idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就这么简单:
It's just simple like this:
因为我喜欢 stride_tricks,所以我会使用它。我确信还有其他方法。
更改阵列的步长和形状,以便将其扩展为 3D。您可以轻松地对 P 的“转置”版本做同样的事情,但在这里我只是重塑它并让广播规则将其延伸到另一个维度。
我将添加对这篇文章的引用,因为这是对
stride_tricks.as_strided
的详细解释。Since I like stride_tricks, that's what I'd use. I'm sure there are other ways.
Change the stride and shape of the array so that you expand it into 3D. You could easily do the same thing with the "transposed" version of P, but here I just reshape it and let the broadcasting rules stretch it into the other dimension.
I'm going to add a reference to this post because it is a nice detailed explanation of
stride_tricks.as_strided
.这使用
tensordot()
部分解决了问题,T
包含您想要的所有产品(以及更多),这只是提取它们的问题。This partially solves the problem using
tensordot()
,T
contains all the products you want (and more), it's just a question of extracting them.