我是Tensorflow的新手,我试图使用Tensors形式的整数索引(在我的代码中稍后需要)作为键来创建字典。创建字典后,我可以迭代并打印字典的键和值,但似乎无法单独访问字典的元素。例如:
import numpy as np
import tensorflow as tf
A=np.random.randn(320,320)
A=tf.convert_to_tensor(A)
dict_nid_neighbors = {}
for nid in range(A.get_shape()[0]):
zero = tf.constant(0, dtype=tf.float64)
where = tf.not_equal(A[nid], zero)
neighbors=tf.where(where)
neighbors = tf.reshape(tf.where(where),[-1])
nid=tf.constant(nid)
dict_nid_neighbors[nid] = neighbors
当我尝试这样做时:
sess=tf.Session()
for x,y in dict_nid_neighbors.items():
print sess.run(x),sess.run(y)
它打印出预期的结果,但是当我尝试访问第一个元素时:
print 'Tensor key 0: ',dict_nid_neighbors[tf.constant(0)]
我得到了错误:
KeyError: <tf.Tensor 'Const_18122:0' shape=() dtype=int32>
您是否不允许这样做,我是否遗漏了明显的内容?谢谢。