创建一个int列表功能以在tensorflow中保存为tfrecord?

Ste*_*ven 10 python tensorflow

如何从列表中创建张量流记录?

从这里的文档似乎可能.还有这个例子,他们使用.tostring()from numpy 将numpy数组转换为字节数组.但是,当我尝试传入时:

labels = np.asarray([[1,2,3],[4,5,6]])
...
example = tf.train.Example(features=tf.train.Features(feature={
    'height': _int64_feature(rows),
    'width': _int64_feature(cols),
    'depth': _int64_feature(depth),
    'label': _int64_feature(labels[index]),
    'image_raw': _bytes_feature(image_raw)}))
writer.write(example.SerializeToString())
Run Code Online (Sandbox Code Playgroud)

我收到错误:

TypeError: array([1, 2, 3]) has type type 'numpy.ndarray', but expected one of: (type 'int', type 'long')
Run Code Online (Sandbox Code Playgroud)

这对我没有帮助我弄清楚如何将整数列表存储到tfrecord中.我试过翻阅文档.

Ste*_*ven 19

经过一段时间的讨论并在文档中进一步查看后,我找到了自己的答案.在上面的函数中使用示例代码作为基础:

def _int64_feature(value):
  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
...
'label': _int64_feature(labels[index]),
Run Code Online (Sandbox Code Playgroud)

标签[index]正在被转换为[value]的列表,因此你有[np.array([1,2,3])]导致错误.

上面的强制转换在示例中是必需的,因为tf.train.Int64List()需要list或numpy数组,并且示例传入一个整数,因此它们将其类型化为一个列表.
在这个例子中就像这样

label = [1,2,3,4]
...
'label': _int64_feature(label[index]) 

tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
#Where value = [1] in this case
Run Code Online (Sandbox Code Playgroud)

如果你想传入一个列表,请执行此操作

labels = np.asarray([[1,2,3],[4,5,6]])
...
def _int64_feature(value):
  return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
...
'label': _int64_feature(labels[index]),
Run Code Online (Sandbox Code Playgroud)

我可能会做一个pull请求,因为我发现tf.train.Feature的原始文档几乎不存在.

TL; DR

将列表或numpy数组传递给tf.train.Int64List(),但不传递列表或numpy数组列表.