【问题标题】:What is more sophisticated way to assign to tensor in tensorflow 2.x在 tensorflow 2.x 中分配给张量的更复杂的方法是什么
【发布时间】:2021-11-15 14:22:22
【问题描述】:

我只是想知道是否有更好的方法来更新 tf2.假设我有tensor_a = tf.ones(4,5,5) (batch_size, H, W),我想用零替换第二个样本的所有值(index=1)。这就是我在不使用 Eager 执行模式的情况下设法做到的方式:

tensor_a = tf.ones([4,5,5])
tensor_b = tf.zeros([1,5,5])
index=1
tensor_a = tf.concat([tensor_a[:index], tensor_b, tensor_a[index+1:]], axis=0)

我知道存在 tf.tensor_scatter_nd_update() 函数,但我不熟悉网格网格,在我看来,对于简单的切片分配操作,它们看起来有点难看。此外,在某些情况下,一次更新具有多个索引的切片(例如样本 0,1 和 2 为零)会很方便。

【问题讨论】:

    标签: python tensorflow tensorflow2.0


    【解决方案1】:

    Tensorflow 操作有时会有点混乱。

    import tensorflow as tf
    
    tensor = tf.ones([4, 5, 5])
    
    tensor = tf.tensor_scatter_nd_update(
        tensor, [[1]], tf.zeros_like(tf.gather(tensor, [1])) 
    )
    
    <tf.Tensor: shape=(4, 5, 5), dtype=float32, numpy=
    array([[[1., 1., 1., 1., 1.],
            [1., 1., 1., 1., 1.],
            [1., 1., 1., 1., 1.],
            [1., 1., 1., 1., 1.],
            [1., 1., 1., 1., 1.]],
           [[0., 0., 0., 0., 0.],
            [0., 0., 0., 0., 0.],
            [0., 0., 0., 0., 0.],
            [0., 0., 0., 0., 0.],
            [0., 0., 0., 0., 0.]],
           [[1., 1., 1., 1., 1.],
            [1., 1., 1., 1., 1.],
            [1., 1., 1., 1., 1.],
            [1., 1., 1., 1., 1.],
            [1., 1., 1., 1., 1.]],
           [[1., 1., 1., 1., 1.],
            [1., 1., 1., 1., 1.],
            [1., 1., 1., 1., 1.],
            [1., 1., 1., 1., 1.],
            [1., 1., 1., 1., 1.]]], dtype=float32)>
    

    【讨论】:

    • 啊,这就是简单的 tf.tensor_scatter_nd_update()。我不熟悉索引参数,我之前放弃了尝试使用 concat。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2019-05-07
    • 2020-03-24
    • 2023-03-11
    相关资源
    最近更新 更多