Tensorflow:如何实现累积最大值? [英] Tensorflow: How to implement cumulative maximum?
问题描述
我正在尝试使用以下格式的代码为我的损失函数实现最大回撤:
I am trying to implement max drawdown for my loss function using code with the format of:
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]
.它创建了一个迄今为止最大值的数组.
But I'm stuck on how to calculate cumulative maximum of x
in Tensorflow. For example: given an array [0,2,5,3,8,1,7]
, the cumulative maximum of that array would be [0,2,5,5,8,8,8]
. It creates an array with the max value so far.
任何提示将不胜感激.
推荐答案
这里是 cumulative_max
的一个实现,使用了一个 tensorflow while 循环,它需要 n=len(x)
次迭代.作为示例,代码是可复制粘贴运行的.
Here's an implementation of cumulative_max
using a tensorflow while loop which takes n=len(x)
iterations. The code is copy-paste runnable as an example.
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)
z = tf.maximum(x, y)
return z, 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, x.shape[0]))
with tf.Session() as sess:
print(sess.run(cumulative_max))
结果:
[0 2 5 5 8 8 8]
注意:如果您有一个很大的向量要计算并且不需要反向传播,那么在 tf.while_loop
中包含 back_prop=False
可能是值得的.
Note: If you have a large vector to compute and you don't need backprop, it's probably worthwhile to include back_prop=False
in the tf.while_loop
.
理解 TF while 循环的关键是了解基于 Python 的函数 tf_while_condition
和 tf_while_body
仅被调用一次以生成相关的 tensorflow 操作.这两个函数在循环中NOT 调用.它们返回的操作将在 sess.run
计算期间在张量流图中的循环中执行.
A key to understanding TF while loops is to understand that your python based functions, tf_while_condition
and tf_while_body
, are only called once to produce the relevant tensorflow operations. Those two functions are NOT called in a loop. The operations they return will be executed in a loop within the tensorflow graph during sess.run
computations.
这篇关于Tensorflow:如何实现累积最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!