Tensorflow:如何实现累积最大值



我正在尝试使用格式为以下格式的代码实现损失函数的最大回撤:

x = cumulative product of returns tensor
z = cumulative max of x
g = minimum of z / x

但是我坚持如何计算 Tensorflow 中 x 的累积最大值。例如:给定一个数组[0,2,5,3,8,1,7],该数组的累积最大值将为 [0,2,5,5,8,8,8] 。它创建一个具有到目前为止最大值的数组。

任何提示将不胜感激。

这是使用张量流 while 循环进行cumulative_max的实现,它需要n=len(x)次迭代。例如,该代码可在 TF 2.x 上运行复制粘贴。

import tensorflow as tf
def tf_while_condition(x, loop_counter):
  return tf.not_equal(loop_counter, 0)
def tf_while_body(x, loop_counter):
  loop_counter -= 1
  y = tf.concat(([x[0]], x[:-1]), axis=0)
  new_x = tf.maximum(x, y)
  return new_x, loop_counter
x = tf.constant([0,2,5,3,8,1,7])
cumulative_max, _ = tf.while_loop(cond=tf_while_condition, 
                                  body=tf_while_body, 
                                  loop_vars=(x, tf.shape(x)[0]))
print(cumulative_max)

结果:

[0 2 5 5 8 8 8]

注意:如果要计算较大的向量并且不需要反向传播,则在tf.while_loop中包含back_prop=False可能是值得的。

理解 TF while 循环的关键是理解基于 python 的函数,tf_while_conditiontf_while_body ,只调用一次以产生相关的张量流操作。这两个函数不是在循环中调用的。它们返回的操作将在sess.run计算期间在张量流图内的循环中执行。

tf.scan op 允许您进行各种累积操作,更好的解决方案可能是以下(使用 TF 2.8.0 进行测试(

tensor = tf.constant([0, 2, 5, 3, 8, 1, 7])
cumulative_max = tf.scan(lambda a, b: tf.maximum(a, b), tensor, initializer=tf.reduce_min(tensor))
# Result: [0, 2, 5, 5, 8, 8, 8]

最新更新