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))
如何交换张量中的元素?
解决方案
您可以使用 TensorFlow分散函数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]
推荐阅读
- image - 在 Embarcadero C++Builder 中反转位图
- excel - 在 WebBrowser1 中查看图像并调整其大小
- javascript - 当用户从他们打开的另一个选项卡中注销时,如何将用户发送到登录页面?
- android - androidx.navigation 菜单项的多个目的地
- amazon-ec2 - ModuleNotFoundError:没有名为“wtforms_json”的模块
- flutter - 如何将我的提供商转变为服务?
- r - 闪亮的应用服务器不加载“* .rds”对象
- java - 两个独立服务中是否存在数据同步模式?
- c++ - 如何在 C++ 中正确实现 addObject() 函数?
- javascript - 记录来自 API 调用的函数结果 - Javascript