简体   繁体   English

TensorFlow中的函数与PyTorch中的expand()相同?

[英]What is the function in TensorFlow that is equivalent to expand() in PyTorch?

Let's say I have a 2 x 3 matrix and I want to create a 6 x 2 x 3 matrix where each element in the first dimension is the original 2 x 3 matrix. 假设我有一个2 x 3矩阵,我想创建一个6 x 2 x 3矩阵,其中第一维中的每个元素都是原始的2 x 3矩阵。

In PyTorch, I can do this: 在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)

What is the equivalent way to do this in TensorFlow? 在TensorFlow中执行此操作的等效方法是什么? I know unsqueeze() is equivalent to tf.expand_dims() but I don't TensorFlow has anything equivalent to expand() . 我知道unsqueeze()相当于tf.expand_dims()但我不TensorFlow有什么相当于expand() I'm thinking of using tf.concat on a list of the 1 x 2 x 3 tensors but am not sure if this is the best way to do it. 我正在考虑在1 x 2 x 3张量列表中使用tf.concat ,但我不确定这是否是最好的方法。

The equivalent function for pytorch expand is tensorflow tf.broadcast_to pytorch expand的等价函数是tensorflow tf.broadcast_to

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

Tensorflow automatically broadcasts, so in general you don't need to do any of this. Tensorflow自动广播,因此通常您不需要执行任何此操作。 Suppose you have a y' of shape 6x2x3 and your x is of shape 2x3 , then you can already do y'*x or y'+x will already behave as if you had expanded it. 假设你有一个y'形状6x2x3而你的x形状是2x3 ,那么你已经可以做y'*xy'+x已经表现得就像你已经展开它一样。 But if for some other reason you really need to do it, then the command in tensorflow is tile : 但是如果由于某些其他原因你真的需要这样做,那么tensorflow中的命令就是tile

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM