[英]How to use tf.clip_by_value() on sliced tensor in tensorflow?
I am using RNN to predict Humidity and Temperature for next hour based on the Humidity and Temperature values for last 24 hours. 我使用RNN根据过去24小时的湿度和温度值预测下一小时的湿度和温度。 To train the model my input and output tensors are in shape of [24, 2] as shown below:
为了训练模型,我的输入和输出张量的形状为[24,2],如下所示:
[[23, 78],
[24, 79],
[25, 78],
[23, 81],
.......
[27, 82],
[21, 87],
[28, 88],
[23, 90]]
Here I want to clip the values of only Humidity column(second) between 0 and 100 as it cant go beyond that. 在这里,我想将仅湿度列(秒)的值剪切在0到100之间,因为它不能超越它。
The code I am using for that purpose is 我为此目的使用的代码是
.....
outputs[:,1] = tf.clip_by_value(outputs[:,1], 0, 100)
.....
And getting the following error: 并收到以下错误:
'Tensor' object does not support item assignment
What should be right way to use tf.clip_by_value() only to one column? 将tf.clip_by_value()仅用于一列的正确方法是什么?
I think the most straightforward (but maybe not optimal) way is to split outputs
along the second dimension using tf.split
, then apply the clipping and concatenate back (if needed). 我认为最简单(但可能不是最优)的方法是使用
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)
If your outputs
is a variable, you can use tf.assign
: 如果
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]]
The following is not documented on the man page https://www.tensorflow.org/api_docs/python/tf/clip_by_value , but in my tests it seems to work: clip_by_value should support broadcasting. 手册页https://www.tensorflow.org/api_docs/python/tf/clip_by_value中未记录以下内容,但在我的测试中似乎有效:clip_by_value应支持广播。 If so, the easiest (as in: not creating temporary tensors) way to do this clipping is the following:
如果是这样,最简单的方法(如:不创建临时张量)进行此剪辑的方法如下:
outputs = tf.clip_by_value(outputs, [[-2147483647, 0]], [[2147483647, 100]])
Here I'm assuming you're using tf.int32
dtype, hence the min and max values for the field you don't want to clip. 在这里,我假设您正在使用
tf.int32
,因此您不想剪切的字段的最小值和最大值。 Admittedly it's not super nice, it looks better for floats where you can use -numpy.inf
and numpy.inf
instead. 不可否认,它不是超级好看,它看起来更好,你可以使用
-numpy.inf
和numpy.inf
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.