[英]Conditional assignment of tensor values in TensorFlow
我想在tensorflow
復制以下numpy
代碼。 例如,我想為之前值為1
所有張量索引分配一個0
。
a = np.array([1, 2, 3, 1])
a[a==1] = 0
# a should be [0, 2, 3, 0]
如果我在tensorflow
編寫類似的代碼, tensorflow
出現以下錯誤。
TypeError: 'Tensor' object does not support item assignment
方括號中的條件應該是任意的,如a[a<1] = 0
。
有沒有辦法在tensorflow
實現這種“條件分配”(因為沒有更好的名字)?
TensorFlow API 中可用的比較運算符,例如大於。
然而,在直接操作張量方面,沒有什么等同於簡潔的 NumPy 語法。 您必須使用單獨的comparison
, where
和assign
運算符來執行相同的操作。
與您的 NumPy 示例等效的代碼是:
import tensorflow as tf
a = tf.Variable( [1,2,3,1] )
start_op = tf.global_variables_initializer()
comparison = tf.equal( a, tf.constant( 1 ) )
conditional_assignment_op = a.assign( tf.where (comparison, tf.zeros_like(a), a) )
with tf.Session() as session:
# Equivalent to: a = np.array( [1, 2, 3, 1] )
session.run( start_op )
print( a.eval() )
# Equivalent to: a[a==1] = 0
session.run( conditional_assignment_op )
print( a.eval() )
# Output is:
# [1 2 3 1]
# [0 2 3 0]
打印語句當然是可選的,它們只是為了證明代碼正確執行。
我也剛開始使用 tensorflow 也許有人會更直觀地填充我的方法
import tensorflow as tf
conditionVal = 1
init_a = tf.constant([1, 2, 3, 1], dtype=tf.int32, name='init_a')
a = tf.Variable(init_a, dtype=tf.int32, name='a')
target = tf.fill(a.get_shape(), conditionVal, name='target')
init = tf.initialize_all_variables()
condition = tf.not_equal(a, target)
defaultValues = tf.zeros(a.get_shape(), dtype=a.dtype)
calculate = tf.select(condition, a, defaultValues)
with tf.Session() as session:
session.run(init)
session.run(calculate)
print(calculate.eval())
主要問題是難以實現“自定義邏輯”。 如果你不能用線性數學術語解釋你的邏輯,你需要為 tensorflow 編寫“自定義操作”庫( 更多細節在這里)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.