我有一个这样的张量:
masked_bad_col = [[False True True False True True True True True True True False]]
我想遍历这个张量,直到所有元素都得到True
。
所以我有另一个函数,它将更新此张量,将其称为uniqueness
。
def uniqueness():
'blah blah blha'
return tensor1, updated_masked_bad_col
我查看了文档,并知道可以使用tf.while_loop
来做到这一点。虽然,我找不到关于布尔值的任何示例。
这是我到目前为止所做的:
tensor1, _ = tf.while_loop(masked_bad_col != True, uniqueness)
这显然是错误的,但是不知道如何使用masked_bad_col
的每个元素作为继续循环通过uniqueness
函数的条件。
更新1 这是我尝试在循环中调用的方法:
corpus = load_corpus('path_to_corpus/train.corpus')
topics = []
vocab, docs = corpus['vocab'], corpus['docs']
number_of_topics = 0
encoder_model = load_keras_model(
'path_to_model/encoder_model',
custom_objects={"KCompetitive": KCompetitive})
weights = encoder_model.get_weights()[0]
for idx in range(encoder_model.output_shape[1]):
token_idx = np.argsort(weights[:, idx])[::-1][:20]
topics.append([(revdict(vocab)[x]) for x in token_idx])
number_of_topics += 1
nparr = np.asarray(topics)
# print nparr.shape
unique, indices, count = np.unique(nparr, return_inverse=True, return_counts=True)
tensor1 = (np.sum(count[indices].reshape(nparr.shape), axis=1).reshape(1, nparr.shape[0]) / (
number_of_topics * 20))
def uniqueness_score():
corpus = load_corpus('path_to_corpus/train.corpus')
topics = []
vocab, docs = corpus['vocab'], corpus['docs']
number_of_topics = 0
encoder_model = load_keras_model(
'path_to_model/encoder_model',
custom_objects={"KCompetitive": KCompetitive})
weights = encoder_model.get_weights()[0]
for idx in range(encoder_model.output_shape[1]):
token_idx = np.argsort(weights[:, idx])[::-1][:20]
topics.append([(revdict(vocab)[x]) for x in token_idx])
number_of_topics += 1
nparr = np.asarray(topics)
unique, indices, count = np.unique(nparr, return_inverse=True, return_counts=True)
tensor1 = (np.sum(count[indices].reshape(nparr.shape), axis=1).reshape(1, nparr.shape[0]) / (
number_of_topics * 20))
return tensor1
这就是我在while_loop
with tf.Session() as sess:
tensor2, _ = tf.while_loop(
# Loop condition (negated goal condition)
lambda tensor1: ~tf.math.reduce_all(tensor1 > tf.reduce_mean(tensor1)),
# Loop body
lambda tensor1: uniqueness_score(),
# Loop variables
[tensor1])
# Returned loop value
print(tensor2.eval())
答案 0 :(得分:1)
我认为我或多或少都了解您想要的东西,但是我不确定我是否需要布尔数组。如果要执行一些迭代过程,在此过程中您可以计算或检索某些值,直到它们满足某些条件,则无需附加数组即可执行此操作。例如,请参见以下循环对一些随机值进行采样,直到所有随机值都满足条件为止:
import tensorflow as tf
# Draw five random numbers until all are > 0.5
with tf.Graph().as_default(), tf.Session() as sess:
tf.random.set_random_seed(0)
# Initial values, here simply initialized to zero
tensor1 = tf.zeros([5], dtype=tf.float32)
# Loop
tensor1 = tf.while_loop(
# Loop condition (negated goal condition)
lambda tensor1: ~tf.math.reduce_all(tensor1 > 0.5),
# Loop body
lambda tensor1: tf.random.uniform(tf.shape(tensor1), dtype=tensor1.dtype),
# Loop variables
[tensor1])
# Returned loop value
print(tensor1.eval())
# [0.7778928 0.9396961 0.572209 0.6187117 0.89615726]
查看是否有帮助,如果您仍然不确定如何将其应用于特定案例,请发表评论。
编辑:再次看到您的问题,您的uniqueness
函数同时计算了tensor1
和掩码,因此也许更类似的代码是这样的:
import tensorflow as tf
def sample_numbers(shape, dtype):
tensor1 = tf.random.uniform(shape, dtype=dtype)
mask = tensor1 > 0.5
return tensor1, mask
# Draw five random numbers until all are > 0.5
with tf.Graph().as_default(), tf.Session() as sess:
tf.random.set_random_seed(0)
# Initial values, here simply initialized to zero
tensor1 = tf.zeros([5], dtype=tf.float32)
mask = tf.zeros(tf.shape(tensor1), dtype=tf.bool)
# Loop
tensor1, _ = tf.while_loop(
# Loop condition (negated goal condition)
lambda tensor1, mask: ~tf.math.reduce_all(mask),
# Loop body
lambda tensor1, mask: sample_numbers(tf.shape(tensor1), tensor1.dtype),
# Loop variables
[tensor1, mask])
# Returned loop value
print(tensor1.eval())
# [0.95553064 0.5170193 0.69573617 0.9501506 0.99776053]