簡體   English   中英

如何在張量流中的切片張量上使用tf.clip_by_value()?

[英]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.infnumpy.inf

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM