Python 是否以编程方式无堆栈矩阵?

Python 是否以编程方式无堆栈矩阵?,python,theano,Python,Theano,我有下面的代码,它将两个矩阵堆叠成一个3D张量 import theano import theano.tensor as T A = T.matrix("A") B = theano.tensor.stack(A, A) f = theano.function(inputs=[A], outputs=B) print f([range(10)]*2) 但是,我不知道我需要提前堆叠矩阵多少次。例如,第四行代码可以是: B = theano.tensor.stack(A, A, A) B = t

我有下面的代码,它将两个矩阵堆叠成一个3D张量

import theano
import theano.tensor as T
A = T.matrix("A")
B = theano.tensor.stack(A, A)
f = theano.function(inputs=[A], outputs=B)
print f([range(10)]*2)
但是,我不知道我需要提前堆叠矩阵多少次。例如,第四行代码可以是:

B = theano.tensor.stack(A, A, A)
B = theano.tensor.stack(A, A, A, A)
etc...
是否有theano函数将矩阵复制n次:

theano.some_function(A, 3) = theano.tensor.stack(A, A, A)

然后我可以把3作为参数传递给theano函数f。这可能吗?我研究了广播,但广播并没有显式地改变维度/堆栈。

我不知道theano,但您可以使用列表理解和解包参数列表来完成这一点:

n = 5
B = theano.tensor.stack(*[A for dummy in range(n)])
这相当于:

B = theano.tensor.stack(A, A, A, A, A)
import theano
import theano.tensor as T
A = T.matrix("A")
B = theano.tensor.stack(A, A, A)
f = theano.function(inputs=[A], outputs=B)
print f([range(10)]*2)

这样做的目的是,它首先用
a
n
副本构建一个列表,然后将该列表解压为单独的参数(请参见)。

在深入阅读theano文档后,我找到了解决方案:

import theano
import theano.tensor as T
A = T.matrix("A")
B = [A]
C = theano.tensor.extra_ops.repeat(B, 3, axis=0)
f = theano.function(inputs=[A], outputs=C)
print f([range(10)]*2)
相当于:

B = theano.tensor.stack(A, A, A, A, A)
import theano
import theano.tensor as T
A = T.matrix("A")
B = theano.tensor.stack(A, A, A)
f = theano.function(inputs=[A], outputs=B)
print f([range(10)]*2)

除了我们现在可以通过编程选择重复次数作为:theano.tensor.extra_ops.repeat的第二个参数这里是一个使用广播的示例

import theano
import theano.tensor as T
import numpy as np

A = T.fmatrix()
n = T.iscalar()

ones = T.ones((n, 1, 1))

stackedA = ones * A[np.newaxis, :, :]

f = theano.function([A, n], stackedA)

a = np.arange(30).reshape(5, 6).astype('float32')
nn = 3

r = f(a, nn)

print r.shape  # outputs (3, 4, 5)
print (r == a[np.newaxis]).all()  # outputs True

这种方法可以帮助编译器避免平铺,如果它可以优化它的话。

谢谢,这对一般函数有效,但theano有点不同:f=theano.function(inputs=[a],outputs=B)创建一个theano函数,理想的语法应该是这样的:f=theano.function(inputs=[a,5],outputs=B)@applecider我试过这个,在你的例子中也很有效。但既然你已经有了另一个解决方案,那就没关系了。你确定你需要这个吗?你想解决什么问题?大多数情况下,当出现矩阵复制时,问题可以用不同的方式表述,避免它。我将使用广播发布一个答案,只是为了完成图片,但您想要进行的实际更改取决于问题。