기능커넥터

tfds.features.FeatureConnector API:

  • 최종 tf.data.Dataset 의 구조, 모양, dtype을 정의합니다.
  • 디스크와의 직렬화를 추상화합니다.
  • 추가 메타데이터 노출(예: 레이블 이름, 오디오 샘플 속도 등)

개요

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 에 정의된 dict 구조와 일치합니다.

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는 예제를 tf.train.Example proto에 직렬화/역직렬화하기 위한 하위 수준 API를 노출합니다.

dict[np.ndarray | Path | str | ...] proto bytes 로 이동하려면 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 bytes tf.Tensor 로 역직렬화하려면 features.deserialize_example 사용하세요.

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

메타데이터에 액세스

기능 메타데이터(레이블 이름, 모양, dtype 등)에 액세스하려면 소개 문서를 참조하세요. 예:

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.Tensor 에서 상속하고 필요할 때 super() 사용하는 것이 가장 좋습니다. 예제는 tfds.features.BBoxFeature 소스 코드를 참조하세요.
  • 기능이 여러 텐서의 컨테이너인 경우 tfds.features.FeaturesDict 에서 상속하고 super() 사용하여 하위 커넥터를 자동으로 인코딩하는 것이 가장 좋습니다.

tfds.features.FeatureConnector 객체는 기능이 사용자에게 표시되는 방식과 디스크에서 기능이 인코딩되는 방식을 추상화합니다. 아래는 데이터세트의 추상화 레이어와 원시 데이터세트 파일에서 tf.data.Dataset 객체로의 변환을 보여주는 다이어그램입니다.

DatasetBuilder 추상화 레이어

자신만의 기능 커넥터를 생성하려면 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 에서 반환된 텐서의 모양/dtype을 나타냅니다. 다른 tfds.features 에서 상속하는 경우 선택 사항일 수 있습니다.
  • (선택 사항) get_serialized_info() : get_tensor_info() 에서 반환된 정보가 데이터가 실제로 디스크에 기록되는 방식과 다른 경우 tf.train.Example 의 사양과 일치하도록 get_serialized_info() 덮어써야 합니다.
  • to_json_content / from_json_content : 원본 소스 코드 없이 데이터세트를 로드할 수 있도록 허용하는 데 필요합니다. 예를 보려면 오디오 기능을 참조하세요.

자세한 내용은 tfds.features.FeatureConnector 설명서를 참조하세요. 실제 사례를 살펴보는 것도 가장 좋습니다.