【问题标题】:Is there a theano operation equivalent to numpy "broadcast_to" method?是否有相当于 numpy“broadcast_to”方法的 theano 操作?
【发布时间】:2016-10-13 07:19:07
【问题描述】:

由于我需要在特定轴上重复,我想尽可能避免不必要的内存重新分配。

例如,给定一个形状为 (3, 4, 5) 的 numpy 数组 A,我想在原始 A 上创建一个形状为 (3, 4, 100, 5) 的名为 B 的视图. A 的第 3 轴重复 100 次。

在numpy中,可以这样实现:

    B=numpy.repeat(A.reshape((3, 4, 1, 5)), repeats=100, axis=2)

或:

    B=numpy.broadcast_to(A.reshape((3, 4, 1, 5)), repeats=100, axis=2)

前者分配一个新内存,然后做一些复制工作,而后者只是在A 上创建一个视图,而不需要额外的内存重新分配。这可以通过答案Size of numpy strided array/broadcast array in memory?中描述的方法来识别。

然而,在 theano 中,theano.tensor.repeat 似乎是唯一的方法,当然它不是更可取的。

我想知道是否有 `numpy.broadcast_to' 之类的 theano 方法可以有效地做到这一点?

【问题讨论】:

    标签: numpy theano broadcast


    【解决方案1】:

    有一个不错的方法 dimshuffle,它可以让 theano 变量在某个维度上广播

    At = theano.tensor.tensor3()
    Bt = At.dimshuffle(0,1,'x',2)
    

    现在你有了一个形状为 (3,4,'x',5) 的张量变量,其中 'x' 表示你要添加的任何维度。

    Ct=theano.tensor.zeros((Bt.shape[0],Bt.shape[1],100,Bt.shape[3]))+Bt
    

    例子

    f=theano.function([At],[Bt,Ct])
    A = np.random.random((3,4,5)).astype(np.float32)
    B,C=f(A)
    print B.shape
    print C.shape
    

    (3, 4, 1, 5)

    (3, 4, 100, 5)

    除非指定,否则最好使用变量 Bt。

    【讨论】:

    • 首先感谢您的回答。但是这样一来,Ct 仍然需要额外的内存来存储那个新创建的零 4d-tensor,并且它的内存效率似乎与 theano.repeat 操作相同。
    猜你喜欢
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多