【问题标题】:how to fill particular indices of a dimension of tensor with a constant value k in tensorflow?如何在张量流中用常数k填充张量维度的特定索引?
【发布时间】:2021-03-08 09:24:30
【问题描述】:

我正在尝试找到一种方法,用常数值 k 替换张量中某个维度的某些索引。类似于 PyTorch 中的 index_fill_。

我已经检查了 tensor_scatter_nd_update,但这需要整个张量以及要替换的索引和值。这要求索引与整个张量有关,而不仅仅是一个特定维度,并且还要求值是张量的形式,而不仅仅是一个常数。我正在寻找更简单的东西?

如果有人知道这些,您能否提供一些解决方案或我应该研究的方向?谢谢

【问题讨论】:

    标签: tensorflow tensorflow2.0 tensor


    【解决方案1】:

    你没有给出一个例子,但你可以像这样切片和分配。

    import tensorflow as tf
    
    aa = tf.Variable(tf.zeros([10, 4]))
    tensor = tf.constant(10,shape=(4,3))
    aa[0:4, 1:4 ].assign(tf.ones_like(tensor, dtype=tf.float32))
    print(aa)
    
    aa[0:4, 1:4 ].assign([[1,1,1],[1,1,1],[1,1,1],[1,1,1]])
    print(aa)
    

    assign 的两种格式都会打印这个。

     array([[0., 1., 1., 1.],
           [0., 1., 1., 1.],
           [0., 1., 1., 1.],
           [0., 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.]], dtype=float32)>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-28
      • 2019-05-30
      • 2018-06-09
      • 2021-12-30
      • 2020-09-23
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      相关资源
      最近更新 更多