【问题标题】:How to create a Boolean tensor from a tensor based on whether values in this other tensor is a key in a dictionary or not without using numpy?如何在不使用numpy的情况下根据另一个张量中的值是否是字典中的键从张量创建布尔张量?
【发布时间】:2020-04-15 14:17:06
【问题描述】:

我有一个形状为 (N,T) 的张量,其中包含整数值和一个字典,其中键和值都是整数。我想创建一个相同形状的布尔张量,即 (N,T),其中只有在输入张量中对应的值存在于字典中时,条目才为真。

比如下面是我的输入,

A = [[2,3,4],
     [6,7,8]]
dictionary = {1: -1, 2: -1, 3: -1, 4: -1, 5: -1, 6: -1}

我想创建一个布尔张量,例如,

B = [[True, True, True],
     [True, False, False]]

这里,B 的每个条目都是 True,其中 A 中的相应条目是字典中的有效键。我必须在不将张量转换为 numpy 的情况下执行此操作,因此将不胜感激。

PS:我使用的是Tensorflow v1,所以请提供与Tensorflow v1兼容的解决方案。

【问题讨论】:

    标签: python tensorflow tensor


    【解决方案1】:

    只要这些不是巨大的张量,您可以执行以下操作,

    这假设您知道张量中的列数,以便我们可以来回进行整形。

    A = tf.constant([[2,3,4], [6,7,8]])
    
    dictionary = {1: -1, 2: -1, 3: -1, 4: -1, 5: -1, 6: -1}
    b = tf.constant(list(dictionary.keys()))
    
    c = tf.map_fn(lambda x: tf.reduce_any(tf.equal(b,x)), tf.reshape(A,[-1]), dtype=bool)
    c = tf.reshape(c, [-1,3])
    

    tf.map_fn 与 TF 中的其他矢量化操作相比非常慢。因此,如果你在大张量上使用它,你可能会观察到缓慢的时间。

    此外,如果您使用 TF 2,您可以用更少的代码行来实现这一点。

    【讨论】:

      猜你喜欢
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多