【问题标题】:What is the function in TensorFlow that is equivalent to expand() in PyTorch?TensorFlow中相当于PyTorch中expand()的函数是什么?
【发布时间】:2018-06-21 21:55:35
【问题描述】:

假设我有一个 2 x 3 矩阵,我想创建一个 6 x 2 x 3 矩阵,其中第一维中的每个元素都是原始的 2 x 3 矩阵。

在 PyTorch 中,我可以这样做:

import torch
from torch.autograd import Variable
import numpy as np

x = np.array([[1, 2, 3], [4, 5, 6]])
x = Variable(torch.from_numpy(x))

# y is the desired result
y = x.unsqueeze(0).expand(6, 2, 3)

在 TensorFlow 中执行此操作的等效方法是什么?我知道unsqueeze() 等同于tf.expand_dims(),但我不知道TensorFlow 有任何等同于expand() 的东西。我正在考虑在 1 x 2 x 3 张量列表上使用 tf.concat,但不确定这是否是最好的方法。

【问题讨论】:

    标签: python tensorflow pytorch


    【解决方案1】:

    Tensorflow 会自动广播,因此一般情况下您无需执行任何此操作。假设您有一个形状为 6x2x3 的 y' 并且您的 x 的形状为 2x3,那么您已经可以执行 y'*xy'+x 的行为,就好像您已经扩展了它一样。但是如果因为某些其他原因你真的需要这样做,那么 tensorflow 中的命令是tile:

    y = tf.tile(tf.reshape(x, (1,2,3)), multiples=(6,1,1))
    

    文档:https://www.tensorflow.org/api_docs/python/tf/tile

    【讨论】:

      【解决方案2】:

      pytorch expand 的等效函数是 tensorflow tf.broadcast_to

      文档:https://www.tensorflow.org/api_docs/python/tf/broadcast_to

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-04
        • 2021-12-17
        • 1970-01-01
        • 2021-11-11
        • 2021-02-02
        • 2017-12-07
        • 2021-11-07
        • 1970-01-01
        相关资源
        最近更新 更多