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

问题描述 投票:1回答:2

我有一个张量如下和一个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
2个回答
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]]

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]])
© www.soinside.com 2019 - 2024. All rights reserved.