簡體   English   中英

如何對張量變量進行比較分配?

[英]How to perform comparative assignment to tensor variable?

在這里,我將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.

我收到此錯誤:

“張量”對象不支持項目分配

在TensorFlow中,您可以使用tf.greatertf.lesstf.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)

這對我有用:

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)

暫無
暫無

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

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