首页 > 解决方案 > 为 SQLite 格式的 TFF 创建自定义联合图像数据集的最佳方法是什么?

问题描述

我浏览了 CIFAR-100 内置数据集的源代码,并决定为 FairFace 数据集创建一个兼容版本,以便在我将 FairFace 转换为与CIFAR-100。

我确实四处搜索,但找不到 CIFAR-100 SQLite 数据库是如何创建的——特别是图像是如何转换为 BLOB 进行存储的。经过一番反复试验,我尝试这样做:

sample = getDatabyIndex(train_labels, index)
example = tf.train.Example(features=tf.train.Features(feature={
  'image' : bytes_feature(sample[0].tobytes()),
  'label' : int64_feature(sample[1])
}))
example = example.SerializeToString()
cur.execute("insert into examples('split_name','client_id','serialized_example_proto') values(?,?,?)", ('train', i, sqlite3.Binary(example)))

对训练数据中的每个样本执行此操作,对测试数据执行类似操作。我可以使用这种解码方法加载它:

def parse_proto(tensor_proto):
  parse_spec = {
    'image': tf.io.FixedLenFeature(shape=(), dtype=tf.string),
    'label': tf.io.FixedLenFeature(shape=(), dtype=tf.int64),
  }
  decoded_example = tf.io.parse_example(tensor_proto, parse_spec)
  return collections.OrderedDict(
            image=tf.reshape(tf.io.decode_raw(decoded_example['image'], tf.uint8), (224,224,3)),
            label=decoded_example['label'])

然而,我注意到,最终的 sqlite.lzma 压缩存档大小为 6.4 GB,而数据集的源存档为 555 MB。我猜测由于我存储图像的方式,如果它们以更兼容的方式存储,压缩效果不会很好。我从 CIFAR-100 代码中看到,图像直接加载为形状为 (32,32,3) 的 FixedLenFeatures,这意味着它们是按原样存储的,但我一直无法找到这样存储我的图像的方法。唯一对我有用的方法是 bytes_feature 路线。

解决此问题的最佳/推荐方法是什么?

标签: tensorflowimage-classificationtensorflow-federatedfederated-learning

解决方案


如果没有更多关于 LZMA 压缩的信息被应用,它很难回答关于尺寸增加的问题。

要直接使用与tf.io.FixedLenFeatureCIFAR-100 数据集相同的数据集,tff.simulation.datasets.cifar100.load_data需要tf.train.Example使用键而不是字节来int64_feature()构建'image'。这可能需要转换sample[0]为不同的 dtype(假设它是 a np.ndarray)。

解码期间:

  1. (N, M, 3)首先使用 int64解析为张量。从tensorflow_federated/python/simulation/datasets/cifar100.py#L31

    'image': tf.io.FixedLenFeature(shape=(32, 32, 3), dtype=tf.int64),
    
  2. 投射到tf.unit8. 从tensorflow_federated/python/simulation/datasets/cifar100.py#L37

    image=tf.cast(parsed_features['image'], tf.uint8),
    

注意:由于协议缓冲区(https://developers.google.com/protocol-buffers/docs/encoding#varints)中使用了 varint 编码,使用 int64 预计不会为序列化表示增加显着开销(至少更少超过 4 倍)。


推荐阅读