【问题标题】:How to perform comparative assignment to tensor variable?如何对张量变量进行比较赋值?
【发布时间】:2019-12-19 07:40:42
【问题描述】:

这里我有 x 和 y 作为形状的张量变量:每个 [5,256,256,3] 和 dtype: float32。这里,5 是我的批量大小,[256,256,3] 是三通道图像。我正在尝试执行这样的操作:

y[y>255] = 255
x[x > 255] = 255
y[y<0] = 0
x[x<0] = 0

#I have tried to create two tf variables by:
var_255 = tf.Variable(tf.ones(tf.shape(x), tf.float32))*255  
var_0 =  tf.Variable(tf.zeros(tf.shape(x), tf.float32))
#and tried to use tf.assign(). However, it still is not what I need.

我收到此错误:

'Tensor' 对象不支持项赋值

【问题讨论】:

标签: python tensorflow keras


【解决方案1】:

在 TensorFlow 中,您可以使用 tf.greater、tf.less 和 tf.where。

简单的演示代码如下。

# TensorFlow 1.14
import tensorflow as tf  

x = [[254, 255, 256],
     [257, 258, 259],
     [252, 253, 254]]

condition = tf.math.greater(x, 255)

result_x = tf.where_v2(condition, 255, x) # tf.where is deprecated in 1.14

sess = tf.Session()
sess.run(tf.global_variables_initializer())
result = sess.run(result_x)
print(result)
[[254 255 255]
 [255 255 255]
 [252 253 254]]

此外,您可以使用tf.ones_like 代替tf.ones(tf.shape(x), tf.float32)。

tf.ones_like(x)

【讨论】:

  • 我有 tensorflow 1.13.1 有没有办法在这个版本中做到这一点? tf.where_v2 在 tf 1.13.1 中不可用,并且 tf.where 在 tf.where(...) 中抛出形状不匹配错误
  • @TSimron,尝试将tf.where_v2 更改为tf.where(condition, 255*tf.ones_like(x), x)。我认为广播不适用于 1.13.1。在tf.where中,第二个和第三个参数的形状应该匹配。
  • 谢谢@SiHyeonKim。我在 Lambda 函数中使用了 tf.where,它就像一个魅力。
【解决方案2】:

这对我有用:

x_1 = Lambda(lambda x: tf.where(x >= 255.0, tf.ones_like(x)*255.0, x))(x)
x = Lambda(lambda x: tf.where(x <= 0.0, tf.zeros_like(x), x))(x_1)
y_1 = Lambda(lambda x: tf.where(x >= 255.0, tf.ones_like(x)*255.0, x))(y)
y = Lambda(lambda x: tf.where(x <= 0.0, tf.zeros_like(x), x))(y_1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 2013-05-03
    • 2020-02-16
    相关资源
    最近更新 更多