创建一个 int 列表功能以在 tensorflow 中保存为 tfrecord? [英] Create an int list feature to save as tfrecord in tensorflow?

查看:33
本文介绍了创建一个 int 列表功能以在 tensorflow 中保存为 tfrecord?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从列表中创建 tensorflow 记录?

How can I create a tensorflow record from a list?

来自文档 这里似乎有可能.还有这个 example 使用 numpy 中的 .tostring() 将 numpy 数组转换为字节数组.但是,当我尝试传入时:

From the documentation here it seems possible. There's also this example where they convert a numpy array into a byte array using the .tostring() from numpy. However when I try to pass in:

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())

我收到错误:

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

这不能帮助我弄清楚如何将整数列表存储到 tfrecord 中.我试过查看文档.

Which doesn't help me to figure out how to store a list of integers into the tfrecord. I've tried looking through the docs.

推荐答案

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

After a while of messing around with it and looking further in the documentation I found my own answer. In the above function using the example code as a base:

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

labels[index] 被转换为 [value] 列表,所以你有 [np.array([1,2,3])] 这会导致错误.

labels[index] is being cast to a list as [value] so you have [np.array([1,2,3])] which causes the error.

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

The above cast was necessary in the example because tf.train.Int64List() expects either a list or numpy array and the example was passing in a single integer so they typecasted it to a list as so.
In the example it was like this

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

如果你想传入一个列表,这样做

If you want to pass in a list do this

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]),

我可能会提出拉取请求,因为我发现 tf.train.Feature 的原始文档几乎不存在.

I'll probably do a pull request because I found the original documentation for tf.train.Feature to be almost non-existent.

TL;DR

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

Pass either a list or numpy array to tf.train.Int64List() but not a list of lists or list of numpy arrays.

这篇关于创建一个 int 列表功能以在 tensorflow 中保存为 tfrecord?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆