Nub*_*eet 3 python vectorization tensorflow
我正在尝试使用以下格式的代码为我的损失函数实现最大回撤:
x = cumulative product of returns tensor
z = cumulative max of x
g = minimum of z / x
Run Code Online (Sandbox Code Playgroud)
但我对如何计算 Tensorflow 中的累积最大值感到困惑x。例如:给定一个数组[0,2,5,3,8,1,7],该数组的累积最大值将为[0,2,5,5,8,8,8]。它创建一个具有迄今为止最大值的数组。
任何提示将非常感谢。
cumulative_max这是使用需要迭代的张量流 while 循环的实现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)
Run Code Online (Sandbox Code Playgroud)
结果:
[0 2 5 5 8 8 8]
Run Code Online (Sandbox Code Playgroud)
注意:如果您有一个大向量要计算并且不需要反向传播,则可能值得将back_prop=False其包含在tf.while_loop.
理解 TF while 循环的关键是了解基于 Python 的函数tf_while_condition和tf_while_body,仅被调用一次以产生相关的张量流操作。这两个函数不是在循环中调用的。它们返回的操作将在计算期间在张量流图中循环执行sess.run。
| 归档时间: |
|
| 查看次数: |
1904 次 |
| 最近记录: |