【问题标题】:How to index and assign to a tensor in tensorflow?如何在张量流中索引并分配给张量?
【发布时间】:2018-07-02 13:41:39
【问题描述】:

我有一个如下的张量和一个 numpy 二维数组

k = 1
mat = np.array([[1,2],[3,4],[5,6]])
for row in mat:
    values_zero, indices_zero = tf.nn.top_k(row, len(row) - k)
    row[indices_zero] = 0  #????

我想将该行中的元素在这些索引处分配为零。但是我不能索引张量并分配给它。我曾尝试使用 tf.gather 功能,但我该如何做作业?我想将其保留为张量,然后在可能的情况下在最后的会话中运行它。

【问题讨论】:

    标签: python numpy tensorflow tensor numpy-ndarray


    【解决方案1】:

    我猜你想将每行中的最大值屏蔽为零?如果是这样,我会这样做。这个想法是通过构造而不是分配来创建张量。

    import numpy as np
    import tensorflow as tf
    
    mat = np.array([[1, 2], [3, 4], [5, 6]])
    
    # All tensorflow from here
    tmat = tf.convert_to_tensor(mat)
    
    # Get index of maximum
    max_inds = tf.argmax(mat, axis=1)
    
    # Create an array of column indices in each row
    shape = tmat.get_shape()
    inds = tf.range(0, shape[1], dtype=max_inds.dtype)[None, :]
    
    # Create boolean mask of maximums
    bmask = tf.equal(inds, max_inds[:, None])
    
    # Convert boolean mask to ones and zeros
    imask = tf.where(bmask, tf.zeros_like(tmat), tf.ones_like(tmat))
    
    # Create new tensor that is masked with maximums set to zer0
    newmat = tmat * imask
    
    with tf.Session() as sess:
        print(newmat.eval())
    

    哪个输出

    [[1 0]
     [3 0]
     [5 0]]
    

    【讨论】:

      【解决方案2】:

      一种方法是通过高级索引:

      In [87]: k = 1
      In [88]: mat = np.array([[1,2],[3,4],[5,6]])
      
      # `sess` is tf.InteractiveSession()
      In [89]: vals, idxs = sess.run(tf.nn.top_k(mat, k=1))
      
      In [90]: idxs
      Out[90]: 
      array([[1],
             [1],
             [1]], dtype=int32)
      
      In [91]: mat[:, np.squeeze(idxs)[0]] = 0
      
      In [92]: mat
      Out[92]: 
      array([[1, 0],
             [3, 0],
             [5, 0]])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-09
        • 2019-05-07
        • 1970-01-01
        • 1970-01-01
        • 2018-01-17
        • 2018-04-18
        • 2019-04-13
        相关资源
        最近更新 更多