Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在张量对象上循环直到满足条件_Python_Tensorflow_While Loop - Fatal编程技术网

Python 如何在张量对象上循环直到满足条件

Python 如何在张量对象上循环直到满足条件,python,tensorflow,while-loop,Python,Tensorflow,While Loop,我有一个像这样的张量: masked_bad_col = [[False True True False True True True True True True True False]] 我想循环使用这个张量,直到所有元素都得到True。 所以我有另一个函数,它将更新这个张量,我们称它为唯一性 def uniqueness(): 'blah blah blha' return tensor1, updated_masked_bad_col 我看了文档,知道

我有一个像这样的张量:

masked_bad_col = [[False  True  True False  True  True  True  True  True  True  True False]]
我想循环使用这个张量,直到所有元素都得到
True
。 所以我有另一个函数,它将更新这个张量,我们称它为唯一性

def uniqueness():

   'blah blah blha'
   return tensor1, updated_masked_bad_col
我看了文档,知道我可以使用
tf.while\u loop
来实现这一点。虽然,我找不到任何关于布尔值的例子。 这就是我到目前为止所做的:

tensor1, _ = tf.while_loop(masked_bad_col != True, uniqueness)
这显然是不正确的,但不知道如何使用
隐藏的\u bad\u col
的每个元素作为继续通过
唯一性
函数循环的条件

更新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\u 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())

我想我大致了解您想要什么,但我不确定是否需要布尔数组。如果您想执行一些迭代过程,计算或检索一些值,直到它们满足某些条件,那么您可以在不使用额外数组的情况下执行该过程。例如,请参见此循环,以对一些随机值进行采样,直到它们全部满足条件:

将tensorflow导入为tf
#绘制五个随机数,直到所有数值均大于0.5
将tf.Graph()作为默认值(),将tf.Session()作为sess:
tf.random.set_random_seed(0)
#初始值,这里只是初始化为零
tensor1=tf.zeros([5],dtype=tf.float32)
#环路
张量1=tf.while\u循环(
#循环条件(否定的目标条件)
lambda tensor1:~tf.math.reduce_all(tensor1>0.5),
#环体
lambda tensor1:tf.random.uniform(tf.shape(tensor1),dtype=tensor1.dtype),
#循环变量
[tensor1])
#返回的循环值
打印(tensor1.eval())
# [0.7778928  0.9396961  0.572209   0.6187117  0.89615726]
看看这是否有帮助,如果您仍然不确定如何将其应用于您的特定案例,请留下评论


编辑:再次查看您的问题,您的
唯一性
函数同时计算了
张量1
和掩码,因此可能更类似的代码如下:

将tensorflow导入为tf
def样本编号(形状、数据类型):
tensor1=tf.random.uniform(形状,dtype=dtype)
遮罩=张量1>0.5
返回张量1,掩码
#绘制五个随机数,直到所有数值均大于0.5
将tf.Graph()作为默认值(),将tf.Session()作为sess:
tf.random.set_random_seed(0)
#初始值,这里只是初始化为零
tensor1=tf.zeros([5],dtype=tf.float32)
mask=tf.zeros(tf.shape(tensor1),dtype=tf.bool)
#环路
张量1,u=tf.while_循环(
#循环条件(否定的目标条件)
lambda tensor1,mask:~tf.math.reduce_all(mask),
#环体
lambda tensor1,mask:sample_编号(tf.shape(tensor1),tensor1.dtype),
#循环变量
[张量1,遮罩])
#返回的循环值
打印(tensor1.eval())
# [0.95553064 0.5170193  0.69573617 0.9501506  0.99776053]

很难理解您想做什么。不是那样工作的,它接收作为条件和身体参数的函数。条件总是布尔型的,所以不确定这是什么意思。我真的不明白你说的“我想循环这个张量,直到所有元素都得到
True
”是什么意思。你能告诉我,对于你给出的示例输入,你希望得到什么样的输出吗?@jdehesa谢谢你回答我的问题。实际上,在
唯一性
方法中,我将对张量做一些更改,直到
更新的\u masked\u bad\u col
的张量元素全部为真(同时我还有另一个张量
张量1
我对此感兴趣)。换句话说,我想更改
tensor1
,直到
的所有元素都更新了\u masked\u bad\u col
成为现实。这有意义吗?有张量。我会在这上面做点什么,然后驱动
更新的\u屏蔽的\u坏的\u col
。但是我想继续改变
张量1
,直到我得到
更新\u masked\u bad\u col
,所有元素都是真的。让我来分享真实的故事,停止泛化。在
tensor1
中,我将得到每列的前20个,计算一个函数,函数的结果是一个
数字
,如果数字小于
平均值
,则该列的
更新的\u masked\u bad\u col
将为
。但我将对同一列的另一个前20名进行洗牌,并对其应用相同的函数,直到结果数大于
mean
,这样在这种情况下,该列的
updated\u masked\u bad\u col
将为真。我会为其他专栏做同样的事情。再次非常感谢。在
#循环体中
调用
tf.random.uniform
。在这里,我可以调用一个函数来洗牌另一个前20名的
tensor1
?或者我需要在这里验证该函数的实现?我尝试了这个:`#循环体lambda tensor1:university_score(),`and raises error`,该函数返回
tensor1
@sariii,听起来应该可以工作。。。我已经添加了另一个例子,做同样的事情,但是使用了一个外部函数,试图更接近(我认为)您所拥有的。看一看,如果你仍然有错误,也许你可以用它们来编辑你的问题。@sariii我看到了你的更新,在“渴望”模式下似乎是可行的,但实际上,要把它变成图形模式,还需要做很多工作。您试图多次加载Keras模型,这可能是不合理的(您应该只需要加载一次并多次使用它),您使用的是NumPy操作和Python列表,而不是TensorFlow操作和Tensor,老实说,在任何情况下,我都不完全理解代码的作用。通常,您需要重写所有逻辑以使用TensorFlow操作(不使用
tf.Variable
,这是一个命令