张量流中张量的交换元素

时间:2018-08-06 19:22:38

标签: python tensorflow

我很难交换一个长度可变的张量的元素。据我了解,仅对变量支持切片分配,因此在运行以下代码时,出现错误ValueError: Sliced assignment is only supported for variables

def add_noise(tensor):
  length = tf.size(tensor)

  i = tf.random_uniform((), 0, length-2, dtype=tf.int32)
  aux = tensor[i]
  tensor = tensor[i].assign(tensor[i+1])
  tensor = tensor[i+1].assign(aux)

  return tensor

with tf.Session() as sess:
  tensor = tf.convert_to_tensor([0, 1, 2, 3, 4, 5, 6], dtype=tf.int32)
  print sess.run(add_noise(tensor))

如何交换张量中的元素?

2 个答案:

答案 0 :(得分:0)

张量一旦定义便是不可变的,另一方面,变量是可变的。您需要一个TensorFlow变量。您应该更改以下行:

tensor = tf.convert_to_tensor(l, dtype=tf.int32)

至以下。

tensor = tf.Variable(l, dtype=tf.int32, name='my_variable')

答案 1 :(得分:0)

您可以使用TensorFlow scatter 功能scatter_nd来交换tensor元素。您还可以通过单个scatter操作来实现多次交换。

tensor = tf.convert_to_tensor([0, 1, 2, 3, 4, 5, 6], dtype=tf.int32)  # input
# let's swap 1st and 4th elements, and also 5th and 6th elements (in terms of 0-based indexing)
indices = tf.constant([[0], [4], [2], [3], [1], [5], [6]])  # indices mentioning the swapping pattern
shape = tf.shape(tensor)  # shape of the scattered_tensor, zeros will be injected if output shape is greater than input shape
scattered_tensor = tf.scatter_nd(indices, tensor, shape)

with tf.Session() as sess:
  print sess.run(scattered_tensor)
  # [0 4 2 3 1 6 5]
相关问题