【问题标题】:How to use tf.clip_by_value() on sliced tensor in tensorflow?如何在张量流中的切片张量上使用 tf.clip_by_value()?
【发布时间】:2018-10-23 21:44:28
【问题描述】:

我正在使用 RNN 根据过去 24 小时的湿度和温度值预测下一小时的湿度和温度。为了训练模型,我的输入和输出张量的形状为 [24, 2],如下所示:

[[23, 78],
 [24, 79],
 [25, 78],
 [23, 81],
  .......
 [27, 82],
 [21, 87],
 [28, 88],
 [23, 90]]

在这里,我只想将 Humidity 列(第二个)的值剪裁在 0 到 100 之间,因为它不能超出这个范围。

我为此目的使用的代码是

.....
outputs[:,1] = tf.clip_by_value(outputs[:,1], 0, 100)
.....

并得到以下错误:

'Tensor' object does not support item assignment

仅将 tf.clip_by_value() 用于一列的正确方法应该是什么?

【问题讨论】:

    标签: python tensorflow deep-learning


    【解决方案1】:

    我认为最直接(但可能不是最佳)的方法是使用 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)
    

    【讨论】:

      【解决方案2】:

      如果你的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]]
      

      【讨论】:

        【解决方案3】:

        手册页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 dtype,因此您不想剪辑的字段的最小值和最大值。诚然,它不是超级好,它看起来更适合你可以使用 -numpy.infnumpy.inf 的浮动。

        【讨论】:

          猜你喜欢
          • 2017-12-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-15
          • 1970-01-01
          • 2018-12-28
          • 2019-11-05
          • 2016-07-04
          相关资源
          最近更新 更多