【问题标题】:Reverse order of some elements in TensorflowTensorflow中某些元素的逆序
【发布时间】:2019-01-24 00:56:31
【问题描述】:

假设我有一个形状为(M, N, 2) 的张量DATA。 我还有另一个张量IND,形状为 (N),由零和一组成。

如果 IND(i)==1DATA(:,i,0)DATA(:,i,1) 必须交换。如果IND(i)==0 他们不会交换。

我该怎么做?我知道这可以通过tf.gather_nd 完成,但我不知道怎么做。

【问题讨论】:

    标签: python tensorflow matrix indexing tensor


    【解决方案1】:

    这是tf.equaltf.wheretf.scater_nd_updatetf.gather_ndtf.reverse_v2 的一种可能解决方案:

    data = tf.Variable([[[1, 2],
                         [2, 3],
                         [3, 4],
                         [4, 5],
                         [5, 6]]])  # shape=(1,5,2)
    
    # reverse elements where ind is 1
    ind = tf.constant([1, 0, 1, 0, 1])  # shape(5,)
    
    cond = tf.where(tf.equal([ind], 1))
    match_data = tf.gather_nd(data, cond)
    rev_match_data = tf.reverse_v2(match_data, axis=[-1])
    data = tf.scatter_nd_update(data, cond, rev_match_data)
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        print(sess.run(data))
        #[[[2 1]
        # [2 3]
        # [4 3]
        # [4 5]
        # [6 5]]]
    

    【讨论】:

      【解决方案2】:

      不使用 tf.gather_ind 的一种方式如下。这个想法是构建 DATA1,它是具有所有可能交换的 DATA(即,如果 IND 是 1 的向量,则交换的结果),并使用掩码从 Data 或 Data1 中选择正确的值,具体取决于是否需要交换或不。

      DATA1 = tf.concat([tf.reshape(DATA[:,:,1], [M, N, 1]), tf.reshape(DATA[:,:,0], [M, N, 1])], axis = 2)
      
      Mask1 = tf.cast(tf.reshape(IND, [1, N, 1]), tf.float64)
      Mask0 = 1 - Mask1
      
      Res = tf.multiply(Mask0, DATA) + tf.multiply(Mask1, DATA1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-18
        • 2018-07-01
        • 1970-01-01
        • 2020-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-23
        相关资源
        最近更新 更多