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

标签 python tensorflow

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

来自documentation这似乎是可能的。还有这个 example他们使用 numpy 中的 .tostring() 将 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())

我得到错误:

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

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

最佳答案

在弄乱了一段时间并进一步查看文档后,我找到了自己的答案。 在上述函数中,以示例代码为基础:

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])] 导致错误。

上面的转换在示例中是必需的,因为 tf.train.Int64List() 需要一个列表或 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

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

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 的原始文档几乎不存在。

长话短说

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

关于python - 创建一个 int 列表功能以在 tensorflow 中另存为 tfrecord?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37668485/

相关文章:

python - 在回溯期间显示变量

python - 将Python字典键对转换为字符串

python - 对列表的迭代无法达到我的想象。为什么?

javascript - Django,如何强制返回ajax错误?

variables - 数据类型 Variable 与 VariableV2 之间有什么区别?

javascript - 使用 Tensorflow.js 开发游戏 AI

python - 在 Python 中解决进程链

python - Tensorflow - 值错误 : Shape must be rank 1 but is rank 0 for 'ParseExample/ParseExample'

python - tensorflow API 检测盒及评测

TensorFlow 使用 image_dataset_from_directory 加载图像