【问题标题】:Tensorflow - Conditionally assign value to a tensorTensorflow - 有条件地为张量赋值
【发布时间】:2019-12-02 22:43:54
【问题描述】:

我有 2 个张量。

t1 = tf.constant([b'hi', b'#hh', b'hello', 'there', '#ii'], dtype=tf.string)

t2 = tf.constant([1,2,3], dtype = tf.int64)

如何将 t1 中以 # 初始化的元素替换为 0,将 t1 中的所有其他元素替换为 t2 中的数字?

具体来说,输出应该是[1, 0, 2, 3, 0]。

谢谢,

【问题讨论】:

    标签: python tensorflow tensor


    【解决方案1】:

    您可以执行以下操作。这应该适用于 TF1 和 TF2(已测试)。在 TF1 中,只需执行 sess.run(res) 即可获得结果。

    t1 = tf.constant(['hi', '#hh', 'hello', 'there', '#ii'], dtype=tf.string)
    t2 = tf.constant([1,2,3], dtype = tf.int32)
    
    # Create mask of the ids we want to change
    mask = tf.logical_not(tf.strings.regex_full_match(t1,'^#.*'))
    idx = tf.cast(mask, dtype=tf.int32)
    # Get the cumulative sum [1, 1, 2, 3, 3]
    cumsum = tf.cumsum(idx)
    # Do a where and replace the unwanted ids with zeros
    res = tf.where(mask, y=tf.zeros_like(t1, dtype=tf.int32), x=cumsum)
    

    【讨论】:

    • 谢谢。我使用tf.scatter_nd() 稍微修改了您的代码以使其更通用
    猜你喜欢
    • 2016-12-27
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多