python - 如何使用可变长度字符串解码 TFRecord 数据样本?

标签 python tensorflow

假设我们有一个包含如下数据样本的 TFRecord 文件:

def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def _float32_feature(value):
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))

example = tf.train.Example(features=tf.train.Features(feature={
    'image/encoded': _bytes_feature(encoded_jpg),
    'label': _float_list_feature(label),
}))

这里的encoded_jpg是编码后的32x32 jpg图片的原始值,不同图片的长度可能会有很大差异; label 是一个固定长度的向量。

对于固定长度的字段,总是可以使用类似下面的内容来解码示例:

features = tf.parse_single_example(
    serialized_example,
    features = {
        'image/encoded': tf.FixedLenFeature([], tf.string)
        'label': tf.FixedLenFeature([], tf.float32)
    }

)

但是这里image/encoded的长度不是常量,上面那个就不行了。

如果我把代码改成这样:

features = tf.parse_single_example(
    serialized_example,
    features = {
        'image/encoded': tf.VarLenFeature(tf.string)
        'label': tf.FixedLenFeature([], tf.float32)
    }
)

encoded = features['image/encoded']

image/encoded 有点像稀疏张量,我不知道如何从这些东西中解码图像。

有没有人有过类似的经历?任何建议表示赞赏。

谢谢!

最佳答案

以下代码可能有用:

转换为 tfrecord:

ex = tf.train.SequenceExample()
ex.context.feature["length"].int64_list.value.append(label)
ex_tokens = ex.feature_lists.feature_list["image/encoded"]
for value in range(encoded_jpg):
    ex_tokens.feature.add().int64_list.value.append(value)

with tf.python_io.TFRecordWriter(os.path.join(DATA_PATH, filename) + ".tfrecord") as filew:
    filew.write(ex.SerializeToString())

读取 tfrecord

context_features = {
    "pose": tf.FixedLenFeature([], dtype=tf.float32)
}

sequence_features = {
    "image/encoded": tf.FixedLenSequenceFeature([], dtype=tf.int64),
}

tf_reader = tf.TFRecordReader()
tf_key, tf_serialized = tf_reader.read(tf_file_queue)
tf_context, tf_sequence = tf.parse_single_sequence_example(
    serialized = tf_serialized,
    context_features = context_features,
    sequence_features = sequence_features
)
encoded = tf_sequence['image/encoded']

关于python - 如何使用可变长度字符串解码 TFRecord 数据样本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45043979/

相关文章:

python - 未使用 TensorFlow 编译的 CPU 指令

python - 求点与线之间的距离,得到该点在一条线上的投影距离

python - 单击 "Exit"时 Tkinter 窗口没有响应

javascript - 如何使用 python mechanize 解析动态更新的 .jsp 表单?

python - 为什么我的损失趋于下降,而我的准确度却趋于零?

python - tensorflow : TypeError: Fetch argument None has invalid type <class 'NoneType' >

c++ - 如何编写函数和成员函数的包装器,在包装函数之前和之后执行一些代码?

python - 如何在 Python 中对列表进行切片

tensorflow - KERAS model.summary 中的 "None"是什么意思?

python - 将 .tfrecords 文件拆分为多个 .tfrecords 文件