在构建张量流图时使用张量作为数组的索引

using a tensor as index to an array in building the tensorflow graph

我正在尝试为 python 中的网络构建张量流图,其中我需要张量(标量值)作为 np.array 的索引 代码截图如下:

def get_votes(input, classnum):
    in_shape = input.get_shape().as_list()
    votes = np.zeros([classnum])
    for i in range(0,in_shape[0]):
        print(input[i])
        votes[input[i]]=votes[input[i]]+1

输入是一维张量。

我得到的错误是:

votes[input[i]]=votes[input[i]]+1 File "C:\Anaconda3\envs\silvafilho\lib\site-packages\tensorflow_core\python\framework\ops.py", line 736, in array " array.".format(self.name)) NotImplementedError: Cannot convert a symbolic Tensor (strided_slice_1:0) to a numpy array.

我尝试使用 tensor.eval(session=tf.Session()) 但它需要一个占位符,我在构建图表时还没有。

如果有人知道解决它的方法,请提前致谢。 我正在使用 tensorflow_gpu 1.15

可以用tf.InteractiveSession()实现,获取InteractiveSession()内的tensor值,然后进行如下操作

%tensorflow_version 1.x
import tensorflow as tf
import numpy as np

input = tf.constant([5])
classnum = 10
def get_votes(input, classnum):
    in_shape = input.get_shape().as_list()
    votes = np.zeros([classnum])
    for i in range(0,in_shape[0]):
        sess = tf.InteractiveSession()
        input = input.eval()
        print(input[i])
        votes[input[i]]=votes[input[i]]+1
        sess.close()
    return votes 

输出:

5
array([0., 0., 0., 0., 0., 1., 0., 0., 0., 0.])  

但是,在 TensorFlow 2.x 中,因为默认情况下启用急切执行 您无需对代码进行任何更改。