在构建tensorflow图中使用张量作为数组索引

2024-09-30 04:38:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python为一个网络构建一个tensorflow图,其中我需要张量(标量值)作为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


Tags: 代码in网络inputgettensorflowdefas
1条回答
网友
1楼 · 发布于 2024-09-30 04:38:28

您可以使用tf.InteractiveSession()实现这一点,获取InteractiveSession()内的张量值,然后执行以下操作

%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中,因为在默认情况下启用了急切执行 您不必对代码进行任何更改

相关问题 更多 >

    热门问题