【问题标题】:Define a tensor of constants for tf.while_loop为 tf.while_loop 定义一个常量张量
【发布时间】:2021-12-03 18:29:46
【问题描述】:

我想以某种方式维护tf.while_loop 中可以支持以下功能的常量列表

  1. 我能够在索引处读取和写入(多次)常量值
  2. 我可以在其上运行 tf.cond,方法是检查它在索引处的值与某个常量的对比

TensorArray 在这里不起作用,因为它不支持重写。 我还有什么其他选择?

【问题讨论】:

  • 我建议你迁移到 TensorFlow2,因为大多数会读到你的人可能正在使用 TF2

标签: python tensorflow tensorflow1.15


【解决方案1】:

你可以像这样定义一个普通的Tensor 并用tf.tensor_scatter_nd_update 更新它:

%tensorflow_version 1.x

import tensorflow as tf

data = tf.constant([1, 1, 1, 0, 1, 0, 1, 1, 0, 0], dtype=tf.float32)
data_tensor = tf.zeros_like(data)
tensor_size = data_tensor.shape[0]

init_state = (0, data_tensor)
condition = lambda i, _: i < tensor_size

def custom_body(i, tensor):
  special_index = 3 # index for which a value should be changed
  new_value = 8
  tensor = tf.where(tf.equal(i, special_index), 
                    tf.tensor_scatter_nd_update(tensor, [[special_index]], [new_value]),
                    tf.tensor_scatter_nd_update(tensor, [[i]], [data[i]*2]))

  return i + 1, tensor


body = lambda i, tensor: (custom_body(i, tensor))
_, final_result = tf.while_loop(condition, body, init_state)

with tf.Session() as sess:
  final_result_values = final_result.eval()

print(final_result_values)
[2. 2. 2. 8. 2. 0. 2. 2. 0. 0.]

【讨论】:

    猜你喜欢
    • 2019-01-12
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 2017-04-28
    • 2016-11-01
    相关资源
    最近更新 更多