【问题标题】:How to create a new array of tensors from old one如何从旧张量创建新的张量数组
【发布时间】:2018-01-23 14:06:35
【问题描述】:

我有一个尺寸为 9 X 1536 的张量 [a, b, c, d, e, f, g, h, i]。我需要创建一个新的张量,它类似于尺寸为 [8 x 2 x 1536] 的 [(a,b), (a,c), (a,d), (a,e),(a,f),(a,g), (a,h), (a,i)]。我怎么能用 tensorflow 做到这一点? 我试过这样

x = tf.zeros((9x1536)) 
x_new = tf.stack([(x[0],x[1]),
                  (x[0], x[2]),
                  (x[0], x[3]),
                  (x[0], x[4]),
                  (x[0], x[5]),
                  (x[0], x[6]),
                  (x[0], x[7]),
                  (x[0], x[8])])

这似乎可行,但我想知道是否有更好的解决方案或方法可以代替它

【问题讨论】:

  • 是错字还是有原因导致您在预期结果中没有(a,f)
  • 对不起。它是一个错字。我已经编辑了它
  • 这似乎是 TensorFlow 文档中已经回答的问题。虽然我不是专家,但您可能需要查看 API 文档 (tensorflow.org/api_docs)
  • @EdOrsi 这种张量杂耍不在文档中,但有类似的问题可以为他指明正确的方向(例如:stackoverflow.com/questions/35361467/…
  • @AshwinRaju 编辑了我的答案以适应您的数据布局

标签: tensorflow


【解决方案1】:

您可以通过tf.concattf.tiletf.expand_dims 的组合获得所需的输出:

import tensorflow as tf
import numpy as np

_in = tf.constant(np.random.randint(0,10,(9,1536)))

tile_shape = [(_in.shape[0]-1).value] + [1]*len(_in.shape[1:].as_list())

_out = tf.concat([
    tf.expand_dims(
        tf.tile(
            [_in[0]],
            tile_shape
        )
        ,
        1),
    tf.expand_dims(_in[1:], 1)
    ],
    1
    )

tf.tile 重复_in 的第一个元素,创建一个长度为len(_in)-1 的张量(我单独计算平铺的形状,因为我们只想平铺在第一个维度上)。

tf.expand_dims 添加了一个维度,然后我们可以对其进行连接

最后,tf.concat 将两个张量缝合在一起,得到所需的结果。

编辑:重写以适应具有多维张量的 OP 的实际用例。

【讨论】:

  • 按预期工作:)
猜你喜欢
  • 1970-01-01
  • 2021-06-27
  • 2020-06-27
  • 2021-04-04
  • 2021-02-26
  • 2021-09-11
  • 2018-05-28
  • 2021-06-27
  • 2020-07-15
相关资源
最近更新 更多