矩阵出来的NumPy Tensor/Kronecker乘积矩阵 [英] NumPy Tensor / Kronecker product of matrices coming out shuffled

查看:334
本文介绍了矩阵出来的NumPy Tensor/Kronecker乘积矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算张量积(更新:我想要的实际上叫做 Kronecker ,这种命名混乱是为什么我找不到多个矩阵的np.kron)的原因,因此我可以将变换应用于本身为张量的向量多个向量的乘积.我在正确展平结果方面遇到麻烦.

I'm trying to compute the tensor product (update: what I wanted was actually called the Kronecker product, and this naming confusion was why I couldn't find np.kron) of multiple matrices, so that I can apply transformations to vectors that are themselves the tensor product of multiple vectors. I'm running into trouble with flattening the result correctly.

例如,假设我要针对自身计算[[0,1],[1,0]]的张量积.结果应该是这样的:

For example, say I want to compute the tensor product of [[0,1],[1,0]] against itself. The result should be something like:

| 0*|0,1|   1*|0,1| |
|   |1,0|     |1,0| |
|                   |
| 1*|0,1|   0*|0,1| |
|   |1,0|     |1,0| |

然后我想将其压平:

| 0 0 0 1 |
| 0 0 1 0 |
| 0 1 0 0 |
| 1 0 0 0 |

不幸的是,我尝试做的所有事情都不能使矩阵变平或使其变平太多或对条目进行置换,以使某些列为空.更具体地说,python程序的输出:

Unfortunately, the things I try all either fail to flatten the matrix or flatten it too much or permute the entries so that some columns are empty. More specifically, the output of the python program:

import numpy as np
flip = np.matrix([[0, 1], [1, 0]])
print np.tensordot(flip, flip, axes=0)
print np.reshape(np.tensordot(flip, flip, axes=0), (4, 4))

[[[[0 0]
   [0 0]]
  [[0 1]
   [1 0]]]
 [[[0 1]
   [1 0]]
  [[0 0]
   [0 0]]]]

[[0 0 0 0]
 [0 1 1 0]
 [0 1 1 0]
 [0 0 0 0]]

我都不想要.

还有很多其他与此问题类似的问题,但是其中提出的建议没有用(或者我错过了那些有用的方法).也许张量积"的含义与我所想的略有不同.但是上面的示例应该清楚.

There are a lot of other questions similar to this one, but the things suggested in them haven't worked (or maybe I missed the ones that work). Maybe "tensor product" means something slightly different than I thought; but the example above should make it clear.

推荐答案

从答案到这个问题,我了解到您想要的被称为"

From the answers to this and this question, I learned what you want is called the "Kronecker product". It's actually built into Numpy, so just do:

np.kron(flip, flip)

但是,如果要使reshape方法起作用,请首先重新排列张量中的行:

But if you want to make the reshape approach work, first rearrange the rows in the tensor:

flip = [[0,1],[1,0]]
tensor4d = np.tensordot(flip, flip, axes=0)
print tensor4d.swapaxes(2, 1).reshape((4,4))

这篇关于矩阵出来的NumPy Tensor/Kronecker乘积矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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