![](/img/trans.png)
[英]Difference between tf.clip_by_value and tf.clip_by_global_norm for RNN's and how to decide max value to clip on?
[英]How to use tf.clip_by_value() on sliced tensor in tensorflow?
我使用RNN根据过去24小时的湿度和温度值预测下一小时的湿度和温度。 为了训练模型,我的输入和输出张量的形状为[24,2],如下所示:
[[23, 78],
[24, 79],
[25, 78],
[23, 81],
.......
[27, 82],
[21, 87],
[28, 88],
[23, 90]]
在这里,我想将仅湿度列(秒)的值剪切在0到100之间,因为它不能超越它。
我为此目的使用的代码是
.....
outputs[:,1] = tf.clip_by_value(outputs[:,1], 0, 100)
.....
并收到以下错误:
'Tensor' object does not support item assignment
将tf.clip_by_value()仅用于一列的正确方法是什么?
我认为最简单(但可能不是最优)的方法是使用tf.split
沿第二维分割outputs
,然后应用裁剪并连接回来(如果需要)。
temperature, humidity = tf.split(output, 2, axis=1)
humidity = tf.clip_by_value(humidity, 0, 100)
# optional concat
clipped_output = tf.concat([temperature, humidity], axis=1)
如果outputs
是变量,则可以使用tf.assign
:
tf.assign(outputs[:,1], tf.clip_by_value(outputs[:,1], 0, 100))
import tensorflow as tf
a = tf.Variable([[23, 78],
[24, 79],
[25, 78],
[23, 81],
[27, 82],
[21, 87],
[28, 88],
[23, 90]])
with tf.Session() as sess:
tf.global_variables_initializer().run()
clipped_value = tf.clip_by_value(a[:,1], 80, 85)
sess.run(tf.assign(a[:,1], clipped_value))
print(sess.run(a))
#[[23 80]
# [24 80]
# [25 80]
# [23 81]
# [27 82]
# [21 85]
# [28 85]
# [23 85]]
手册页https://www.tensorflow.org/api_docs/python/tf/clip_by_value中未记录以下内容,但在我的测试中似乎有效:clip_by_value应支持广播。 如果是这样,最简单的方法(如:不创建临时张量)进行此剪辑的方法如下:
outputs = tf.clip_by_value(outputs, [[-2147483647, 0]], [[2147483647, 100]])
在这里,我假设您正在使用tf.int32
,因此您不想剪切的字段的最小值和最大值。 不可否认,它不是超级好看,它看起来更好,你可以使用-numpy.inf
和numpy.inf
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.