如何索引和分配张量流中的张量?

时间:2018-01-23 16:40:34

标签: python numpy tensorflow tensor numpy-ndarray

我有一个如下的张量和一个numpy 2D数组

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 功能但是如何进行分配呢?我希望将它保持为张量,然后在最后的会话中运行它,如果可能的话。

2 个答案:

答案 0 :(得分:2)

我猜你试图将每行的最大值掩盖为零?如果是这样,我会这样做。我们的想法是通过构造而不是赋值来创建张量。

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]]

答案 1 :(得分:0)

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

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]])