【问题标题】:Tensorflow: How to tile a tensor that duplicate in certain order? [duplicate]Tensorflow:如何平铺以特定顺序重复的张量? [复制]
【发布时间】:2018-08-13 12:18:45
【问题描述】:

例如,我有一个张量 A = tf.Variable([a, b, c, d, e]) 并通过 tf.tile(),它可以给出像[a, b, c, d, e, a, b, c, d, e]这样的张量

但我想将A 改造成类似:[a, a, b, b, c, c, d, d, e],其中元素在原始位置重复。

实现这一目标的最有效的方法(更少的操作)是什么(通过不同的操作)?

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    您可以通过添加维度、沿该维度平铺并移除它来实现:

    import tensorflow as tf
    
    A = tf.constant([1, 2, 3, 4, 5])
    
    B = tf.expand_dims(A, axis=-1)
    C = tf.tile(B, multiples=[1,2])
    D = tf.reshape(C, shape=[-1])
    
    with tf.Session() as sess:
        print('A:\n{}'.format(A.eval()))
        print('B:\n{}'.format(B.eval()))
        print('C:\n{}'.format(C.eval()))
        print('D:\n{}'.format(D.eval()))
    

    给予

    A:
    [1 2 3 4 5]
    B: # Add inner dimension
    [[1]
     [2]
     [3]
     [4]
     [5]]
    C: # Tile along inner dimension
    [[1 1]
     [2 2]
     [3 3]
     [4 4]
     [5 5]]
    D: # Remove innermost dimension
    [1 1 2 2 3 3 4 4 5 5]
    

    编辑:正如 cmets 中所指出的,使用 tf.stack 允许在旅途中指定附加维度:

    F = tf.stack([A, A], axis=1)
    F = tf.reshape(F, shape=[-1])
    
    with tf.Session() as sess:
        print(F.eval())
    
    [1 1 2 2 3 3 4 4 5 5]
    

    【讨论】:

    • 感谢您的回答,但是当我测试渐变g = tf.gradients(3*D, A) 时,为什么它返回[None]
    • 为了简单起见,我在示例中使用了tf.constant,而不是tf.Variable。不过,同样的逻辑也适用于变量。
    • 还有一些讨论here关于奇偶位置和交错很有趣。A = tf.Variable(['a', 'b', 'c', 'd', 'e']) print(sess.run(A[0::2])) print(sess.run(A[1::2]))
    • @sdcbr 很奇怪,我在我的电脑上测试了那个代码,返回的渐变很好,但是在google colab中,它返回None
    • @MohanRadhakrishnan,感谢您的参考,这实际上可以用更少的代码来完成,我已经更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多