FeatureConnector

tfds.features.FeatureConnector API

  • 定義最終 tf.data.Dataset 的結構、形狀和資料類型
  • 抽象化與磁碟之間的序列化。
  • 公開其他中繼資料 (例如標籤名稱、音訊取樣率等)

總覽

tfds.features.FeatureConnector 定義資料集功能結構 (在 tfds.core.DatasetInfo 中)

tfds.core.DatasetInfo(
    features=tfds.features.FeaturesDict({
        'image': tfds.features.Image(shape=(28, 28, 1), doc='Grayscale image'),
        'label': tfds.features.ClassLabel(
            names=['no', 'yes'],
            doc=tfds.features.Documentation(
                desc='Whether this is a picture of a cat',
                value_range='yes or no'
            ),
        ),
        'metadata': {
            'id': tf.int64,
            'timestamp': tfds.features.Scalar(
                tf.int64,
                doc='Timestamp when this picture was taken as seconds since epoch'),
            'language': tf.string,
        },
    }),
)

功能可以使用純文字描述 (doc='description') 或直接使用 tfds.features.Documentation 來記錄,以提供更詳細的功能描述。

功能可以是

在產生期間,範例將由 FeatureConnector.encode_example 自動序列化為適合磁碟的格式 (目前為 tf.train.Example 通訊協定緩衝區)

yield {
    'image': '/path/to/img0.png',  # `np.array`, file bytes,... also accepted
    'label': 'yes',  # int (0-num_classes) also accepted
    'metadata': {
        'id': 43,
        'language': 'en',
    },
}

讀取資料集時 (例如使用 tfds.load),資料會使用 FeatureConnector.decode_example 自動解碼。傳回的 tf.data.Dataset 將符合 tfds.core.DatasetInfo 中定義的字典結構

ds = tfds.load(...)
ds.element_spec == {
    'image': tf.TensorSpec(shape=(28, 28, 1), tf.uint8),
    'label': tf.TensorSpec(shape=(), tf.int64),
    'metadata': {
        'id': tf.TensorSpec(shape=(), tf.int64),
        'language': tf.TensorSpec(shape=(), tf.string),
    },
}

序列化/還原序列化為 proto

TFDS 公開低階 API,以將範例序列化/還原序列化為 tf.train.Example proto。

若要將 dict[np.ndarray | Path | str | ...] 序列化為 proto 位元組,請使用 features.serialize_example

with tf.io.TFRecordWriter('path/to/file.tfrecord') as writer:
  for ex in all_exs:
    ex_bytes = features.serialize_example(data)
    f.write(ex_bytes)

若要將 proto 位元組還原序列化為 tf.Tensor,請使用 features.deserialize_example

ds = tf.data.TFRecordDataset('path/to/file.tfrecord')
ds = ds.map(features.deserialize_example)

存取中繼資料

請參閱簡介文件以存取功能中繼資料 (標籤名稱、形狀、資料類型等)。範例

ds, info = tfds.load(..., with_info=True)

info.features['label'].names  # ['cat', 'dog', ...]
info.features['label'].str2int('cat')  # 0

建立您自己的 tfds.features.FeatureConnector

如果您認為可用功能中缺少某項功能,請開啟新問題

若要建立您自己的功能連接器,您需要從 tfds.features.FeatureConnector 繼承並實作抽象方法。

tfds.features.FeatureConnector 物件會將功能在磁碟上的編碼方式與向使用者呈現的方式抽象化。以下圖表顯示資料集的抽象層,以及從原始資料集檔案到 tf.data.Dataset 物件的轉換。

DatasetBuilder abstraction layers

若要建立您自己的功能連接器,請將 tfds.features.FeatureConnector 子類別化並實作抽象方法

  • encode_example(data):定義如何將產生器 _generate_examples() 中提供的資料編碼為 tf.train.Example 相容資料。可以傳回單一值,或值的 dict
  • decode_example(data):定義如何從 tf.train.Example 讀取的張量中解碼資料,以成為 tf.data.Dataset 傳回的使用者張量。
  • get_tensor_info():指出 tf.data.Dataset 傳回的張量形狀/資料類型。如果從另一個 tfds.features 繼承,則可能為選用。
  • (選用) get_serialized_info():如果 get_tensor_info() 傳回的資訊與資料實際寫入磁碟的方式不同,則您需要覆寫 get_serialized_info() 以符合 tf.train.Example 的規格
  • to_json_content/from_json_content:這是必要的,以便在沒有原始程式碼的情況下載入資料集。請參閱音訊功能以取得範例。

如需更多資訊,請參閱 tfds.features.FeatureConnector 文件。最好也查看實際範例