arr = tf.Variable(initial_value=[True, False, True], dtype=tf.bool)
现在,我需要翻转一位arr,并在会话期间将其分配给一个新变量。我必须对循环中的每一位都这样做。
我可以在arr中进行就地替换,但这会破坏原来的张量arr
import tensorflow as tf
arr = tf.Variable(initial_value=[True, False, True], dtype=tf.bool)
flipped_bit = tf.placeholder(dtype=tf.int32, shape=())
flipped_arr = tf.assign(arr[flipped_bit],
tf.math.logical_not(arr[flipped_bit]))
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print('Original', sess.run(arr))
for i in range(0, 3):
print('flipped arr', i, sess.run(flipped_arr, feed_dict={flipped_bit: i}))
我的解决方案。
import tensorflow as tf
import numpy as np
arr = tf.Variable(initial_value=[True, False, True],
trainable=False,
dtype=tf.bool)
mask = tf.placeholder(dtype=tf.bool, shape=arr.shape)
flipped_arr = tf.math.logical_xor(arr, mask)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print('Original', sess.run(arr))
for flip_bit in range(0, 3):
mask_val = np.zeros(arr.shape)
mask_val[flip_bit] = 1
print('mask', mask_val)
print(
'flip_arr', flip_bit,
sess.run(flipped_arr,
feed_dict={
flipped_bit: flip_bit,
mask: mask_val
}))