gpt4 book ai didi

python - Tensorflow:如何实现累积最大值?

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:05 25 4
gpt4 key购买 nike

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

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]。它创建了一个具有迄今为止最大值的数组。

如有任何提示,我们将不胜感激。

最佳答案

下面是一个 cumulative_max 的实现,它使用一个需要 n=len(x) 迭代的 tensorflow while 循环。作为示例,该代码可在 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 仅调用一次以生成相关的 tensorflow 操作。这两个函数不是在循环中调用。它们返回的操作将在 sess.run 计算期间在 tensorflow 图中循环执行。

关于python - Tensorflow:如何实现累积最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49314186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com