Tensorflow中某些元素的逆序 [英] Reverse order of some elements in Tensorflow
本文介绍了Tensorflow中某些元素的逆序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个形状为(M,N,2)
的张量 DATA
.我还有另一个由零和一组成的(N)形状的张量 IND
.
Say I have a tensor DATA
of shape (M, N, 2)
.
I also have another tensor IND
of shape (N) consisting of zeros and ones.
如果 IND(i)== 1
,则 DATA(:,i,0)
和 DATA(:,i,1)
必须调换.如果 IND(i)== 0
,它们将不会交换.
If IND(i)==1
then DATA(:,i,0)
and DATA(:,i,1)
have to swap. If IND(i)==0
they won't swap.
我该怎么做?我知道可以通过 tf.gather_nd
完成此操作,但是我不知道如何操作.
How can I do this? I know that this can be done via tf.gather_nd
, but I have no idea how.
推荐答案
以下是 tf.equal
, tf.where
, tf.scater_nd_update
, tf.gather_nd
和 tf.reverse_v2
:
Here is one possible solution with tf.equal
, tf.where
, tf.scater_nd_update
, tf.gather_nd
and tf.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]]]
这篇关于Tensorflow中某些元素的逆序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文