TFRecord ve tf.train.Örnek

TensorFlow.org'da görüntüleyin Google Colab'da çalıştırın Kaynağı GitHub'da görüntüleyin Not defterini indir

TFRecord formatı, bir dizi ikili kaydı depolamak için basit bir formattır.

Protokol arabellekleri , yapılandırılmış verilerin verimli bir şekilde serileştirilmesi için platformlar arası, diller arası bir kitaplıktır.

Protokol mesajları .proto dosyaları tarafından tanımlanır, bunlar genellikle bir mesaj türünü anlamanın en kolay yoludur.

tf.train.Example mesajı (veya protobuf), bir {"string": value} eşlemesini temsil eden esnek bir mesaj türüdür. TensorFlow ile kullanılmak üzere tasarlanmıştır ve TFX gibi daha yüksek seviyeli API'lerde kullanılır.

Bu not defteri, tf.train.Example iletisinin nasıl oluşturulacağını, ayrıştırılacağını ve kullanılacağını ve ardından tf.train.Example iletilerinin .tfrecord dosyalarına ve bu dosyalardan nasıl seri hale getirileceğini, yazılacağını ve okunacağını gösterir.

Kurmak

import tensorflow as tf

import numpy as np
import IPython.display as display

tf.train.Example

tf.train.Example için veri türleri.Örnek

Temel olarak, bir tf.train.Example bir {"string": tf.train.Feature} eşlemesidir.

tf.train.Feature mesaj tipi aşağıdaki üç türden birini kabul edebilir (Referans için .proto dosyasına bakın). Diğer jenerik türlerin çoğu aşağıdakilerden birine zorlanabilir:

  1. tf.train.BytesList (aşağıdaki türler zorlanabilir)

    • string
    • byte
  2. tf.train.FloatList (aşağıdaki türler zorlanabilir)

    • float ( float32 )
    • double ( float64 )
  3. tf.train.Int64List (aşağıdaki türler zorlanabilir)

    • bool
    • enum
    • int32
    • uint32
    • int64
    • uint64

Standart bir TensorFlow türünü bir tf.train.Example uyumlu tf.train.Feature dönüştürmek için aşağıdaki kısayol işlevlerini kullanabilirsiniz. Her işlevin bir skaler giriş değeri aldığını ve yukarıdaki üç list türünden birini içeren bir tf.train.Feature döndürdüğünü unutmayın:

# The following functions can be used to convert a value to a type compatible
# with tf.train.Example.

def _bytes_feature(value):
  """Returns a bytes_list from a string / byte."""
  if isinstance(value, type(tf.constant(0))):
    value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def _float_feature(value):
  """Returns a float_list from a float / double."""
  return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))

def _int64_feature(value):
  """Returns an int64_list from a bool / enum / int / uint."""
  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

Aşağıda bu işlevlerin nasıl çalıştığına dair bazı örnekler verilmiştir. Değişen girdi türlerini ve standartlaştırılmış çıktı türlerini not edin. Bir işlevin giriş türü, yukarıda belirtilen zorlanabilir türlerden biriyle eşleşmezse, işlev bir istisna oluşturur (örneğin, _int64_feature(1.0) 1.0 bir kayan nokta olduğundan hata verir—bu nedenle, bunun yerine _float_feature işleviyle kullanılmalıdır. ):

print(_bytes_feature(b'test_string'))
print(_bytes_feature(u'test_bytes'.encode('utf-8')))

print(_float_feature(np.exp(1)))

print(_int64_feature(True))
print(_int64_feature(1))
tutucu3 l10n-yer
bytes_list {
  value: "test_string"
}

bytes_list {
  value: "test_bytes"
}

float_list {
  value: 2.7182817459106445
}

int64_list {
  value: 1
}

int64_list {
  value: 1
}

Tüm proto iletileri, .SerializeToString yöntemi kullanılarak ikili bir dizeye serileştirilebilir:

feature = _float_feature(np.exp(1))

feature.SerializeToString()
tutucu5 l10n-yer
b'\x12\x06\n\x04T\xf8-@'

Bir tf.train.Example mesajı oluşturma

Mevcut verilerden bir tf.train.Example mesajı oluşturmak istediğinizi varsayalım. Pratikte, veri seti herhangi bir yerden gelebilir, ancak tek bir gözlemden tf.train.Example mesajı oluşturma prosedürü aynı olacaktır:

  1. Her gözlem içinde, her değerin, yukarıdaki işlevlerden biri kullanılarak 3 uyumlu türden birini içeren bir tf.train.Feature dönüştürülmesi gerekir.

  2. Unsur adı dizesinden #1'de üretilen kodlanmış özellik değerine bir harita (sözlük) oluşturursunuz.

  3. 2. adımda üretilen harita, Features mesajına dönüştürülür.

Bu not defterinde NumPy kullanarak bir veri kümesi oluşturacaksınız.

Bu veri kümesi 4 özelliğe sahip olacaktır:

  • bir boole özelliği, eşit olasılıkla False veya True
  • [0, 5] arasından rastgele seçilmiş bir tamsayı özelliği
  • bir dizin olarak tamsayı özelliği kullanılarak bir dize tablosundan oluşturulan bir dize özelliği
  • standart bir normal dağılımdan bir kayan nokta özelliği

Yukarıdaki dağılımların her birinden bağımsız ve aynı şekilde dağıtılmış 10.000 gözlemden oluşan bir örnek düşünün:

# The number of observations in the dataset.
n_observations = int(1e4)

# Boolean feature, encoded as False or True.
feature0 = np.random.choice([False, True], n_observations)

# Integer feature, random from 0 to 4.
feature1 = np.random.randint(0, 5, n_observations)

# String feature.
strings = np.array([b'cat', b'dog', b'chicken', b'horse', b'goat'])
feature2 = strings[feature1]

# Float feature, from a standard normal distribution.
feature3 = np.random.randn(n_observations)

Bu özelliklerin her biri, _bytes_feature , _float_feature , _int64_feature biri kullanılarak bir tf.train.Example uyumlu türe zorlanabilir. Daha sonra bu kodlanmış özelliklerden bir tf.train.Example mesajı oluşturabilirsiniz:

def serialize_example(feature0, feature1, feature2, feature3):
  """
  Creates a tf.train.Example message ready to be written to a file.
  """
  # Create a dictionary mapping the feature name to the tf.train.Example-compatible
  # data type.
  feature = {
      'feature0': _int64_feature(feature0),
      'feature1': _int64_feature(feature1),
      'feature2': _bytes_feature(feature2),
      'feature3': _float_feature(feature3),
  }

  # Create a Features message using tf.train.Example.

  example_proto = tf.train.Example(features=tf.train.Features(feature=feature))
  return example_proto.SerializeToString()

Örneğin, [False, 4, bytes('goat'), 0.9876] veri kümesinden tek bir gözleminiz olduğunu varsayalım. create_message() kullanarak bu gözlem için tf.train.Example mesajını oluşturabilir ve yazdırabilirsiniz. Her bir gözlem, yukarıdakilere göre bir Features mesajı olarak yazılacaktır. tf.train.Example mesajının , Features mesajının yalnızca bir sarmalayıcısı olduğunu unutmayın:

# This is an example observation from the dataset.

example_observation = []

serialized_example = serialize_example(False, 4, b'goat', 0.9876)
serialized_example
tutucu9 l10n-yer
b'\nR\n\x14\n\x08feature2\x12\x08\n\x06\n\x04goat\n\x11\n\x08feature1\x12\x05\x1a\x03\n\x01\x04\n\x11\n\x08feature0\x12\x05\x1a\x03\n\x01\x00\n\x14\n\x08feature3\x12\x08\x12\x06\n\x04[\xd3|?'

Mesajın kodunu çözmek için tf.train.Example.FromString yöntemini kullanın.

example_proto = tf.train.Example.FromString(serialized_example)
example_proto
tutucu11 l10n-yer
features {
  feature {
    key: "feature0"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "feature1"
    value {
      int64_list {
        value: 4
      }
    }
  }
  feature {
    key: "feature2"
    value {
      bytes_list {
        value: "goat"
      }
    }
  }
  feature {
    key: "feature3"
    value {
      float_list {
        value: 0.9876000285148621
      }
    }
  }
}

TFRecords biçimi ayrıntıları

Bir TFRecord dosyası bir dizi kayıt içerir. Dosya yalnızca sırayla okunabilir.

Her kayıt, veri yükü için bir bayt dizisi, artı veri uzunluğu ve bütünlük denetimi için CRC-32C ( Castagnoli polinomunu kullanan 32-bit CRC ) karmalarını içerir.

Her kayıt aşağıdaki biçimlerde saklanır:

uint64 length
uint32 masked_crc32_of_length
byte   data[length]
uint32 masked_crc32_of_data

Kayıtlar, dosyayı oluşturmak için bir araya getirilir. CRC'ler burada açıklanmıştır ve bir CRC'nin maskesi:

masked_crc = ((crc >> 15) | (crc << 17)) + 0xa282ead8ul

tf.data kullanan tf.data dosyaları

tf.data modülü ayrıca TensorFlow'da veri okumak ve yazmak için araçlar sağlar.

Bir TFRecord dosyası yazma

Verileri bir veri kümesine almanın en kolay yolu, from_tensor_slices yöntemini kullanmaktır.

Bir diziye uygulandığında, bir skaler veri kümesi döndürür:

tf.data.Dataset.from_tensor_slices(feature1)
tutucu15 l10n-yer
<TensorSliceDataset element_spec=TensorSpec(shape=(), dtype=tf.int64, name=None)>

Bir dizi diziye uygulandığında, bir dizi veri seti döndürür:

features_dataset = tf.data.Dataset.from_tensor_slices((feature0, feature1, feature2, feature3))
features_dataset
<TensorSliceDataset element_spec=(TensorSpec(shape=(), dtype=tf.bool, name=None), TensorSpec(shape=(), dtype=tf.int64, name=None), TensorSpec(shape=(), dtype=tf.string, name=None), TensorSpec(shape=(), dtype=tf.float64, name=None))>
yer tutucu18 l10n-yer
# Use `take(1)` to only pull one example from the dataset.
for f0,f1,f2,f3 in features_dataset.take(1):
  print(f0)
  print(f1)
  print(f2)
  print(f3)
tf.Tensor(False, shape=(), dtype=bool)
tf.Tensor(4, shape=(), dtype=int64)
tf.Tensor(b'goat', shape=(), dtype=string)
tf.Tensor(0.5251196235602504, shape=(), dtype=float64)

Bir Dataset öğesinin her öğesine bir işlev uygulamak için tf.data.Dataset.map yöntemini kullanın.

Eşlenen işlev, TensorFlow grafik modunda çalışmalıdır; tf.Tensors üzerinde çalışmalı ve döndürmelidir. serialize_example gibi tensör olmayan bir işlev, uyumlu hale getirmek için tf.py_function ile sarılabilir.

tf.py_function kullanılması, aksi halde kullanılamayan şekil ve tür bilgilerinin belirtilmesini gerektirir:

def tf_serialize_example(f0,f1,f2,f3):
  tf_string = tf.py_function(
    serialize_example,
    (f0, f1, f2, f3),  # Pass these args to the above function.
    tf.string)      # The return type is `tf.string`.
  return tf.reshape(tf_string, ()) # The result is a scalar.
tf_serialize_example(f0, f1, f2, f3)
-yer tutucu22 l10n-yer
<tf.Tensor: shape=(), dtype=string, numpy=b'\nR\n\x14\n\x08feature3\x12\x08\x12\x06\n\x04=n\x06?\n\x11\n\x08feature0\x12\x05\x1a\x03\n\x01\x00\n\x14\n\x08feature2\x12\x08\n\x06\n\x04goat\n\x11\n\x08feature1\x12\x05\x1a\x03\n\x01\x04'>

Bu işlevi veri kümesindeki her öğeye uygulayın:

serialized_features_dataset = features_dataset.map(tf_serialize_example)
serialized_features_dataset
<MapDataset element_spec=TensorSpec(shape=(), dtype=tf.string, name=None)>
def generator():
  for features in features_dataset:
    yield serialize_example(*features)
serialized_features_dataset = tf.data.Dataset.from_generator(
    generator, output_types=tf.string, output_shapes=())
serialized_features_dataset
<FlatMapDataset element_spec=TensorSpec(shape=(), dtype=tf.string, name=None)>

Ve bunları bir TFRecord dosyasına yazın:

filename = 'test.tfrecord'
writer = tf.data.experimental.TFRecordWriter(filename)
writer.write(serialized_features_dataset)
tutucu30 l10n-yer
WARNING:tensorflow:From /tmp/ipykernel_25215/3575438268.py:2: TFRecordWriter.__init__ (from tensorflow.python.data.experimental.ops.writers) is deprecated and will be removed in a future version.
Instructions for updating:
To write TFRecords to disk, use `tf.io.TFRecordWriter`. To save and load the contents of a dataset, use `tf.data.experimental.save` and `tf.data.experimental.load`

Bir TFRecord dosyasını okuma

TFRecord dosyasını tf.data.TFRecordDataset sınıfını kullanarak da okuyabilirsiniz.

tf.data kullanarak tf.data dosyalarının kullanılması hakkında daha fazla bilgi tf.data: TensorFlow giriş işlem hatları oluşturma kılavuzunda bulunabilir.

TFRecordDataset s kullanmak, giriş verilerini standartlaştırmak ve performansı optimize etmek için yararlı olabilir.

filenames = [filename]
raw_dataset = tf.data.TFRecordDataset(filenames)
raw_dataset
tutucu32 l10n-yer
<TFRecordDatasetV2 element_spec=TensorSpec(shape=(), dtype=tf.string, name=None)>

Bu noktada veri kümesi, serileştirilmiş tf.train.Example mesajları içerir. Üzerinde yinelendiğinde, bunları skaler dize tensörleri olarak döndürür.

Yalnızca ilk 10 kaydı göstermek için .take yöntemini kullanın.

for raw_record in raw_dataset.take(10):
  print(repr(raw_record))
tutucu34 l10n-yer
<tf.Tensor: shape=(), dtype=string, numpy=b'\nR\n\x11\n\x08feature0\x12\x05\x1a\x03\n\x01\x00\n\x11\n\x08feature1\x12\x05\x1a\x03\n\x01\x04\n\x14\n\x08feature2\x12\x08\n\x06\n\x04goat\n\x14\n\x08feature3\x12\x08\x12\x06\n\x04=n\x06?'>
<tf.Tensor: shape=(), dtype=string, numpy=b'\nR\n\x11\n\x08feature1\x12\x05\x1a\x03\n\x01\x04\n\x11\n\x08feature0\x12\x05\x1a\x03\n\x01\x01\n\x14\n\x08feature3\x12\x08\x12\x06\n\x04\x9d\xfa\x98\xbe\n\x14\n\x08feature2\x12\x08\n\x06\n\x04goat'>
<tf.Tensor: shape=(), dtype=string, numpy=b'\nQ\n\x13\n\x08feature2\x12\x07\n\x05\n\x03dog\n\x11\n\x08feature1\x12\x05\x1a\x03\n\x01\x01\n\x14\n\x08feature3\x12\x08\x12\x06\n\x04a\xc0r?\n\x11\n\x08feature0\x12\x05\x1a\x03\n\x01\x01'>
<tf.Tensor: shape=(), dtype=string, numpy=b'\nQ\n\x11\n\x08feature0\x12\x05\x1a\x03\n\x01\x01\n\x11\n\x08feature1\x12\x05\x1a\x03\n\x01\x00\n\x13\n\x08feature2\x12\x07\n\x05\n\x03cat\n\x14\n\x08feature3\x12\x08\x12\x06\n\x04\x92Q(?'>
<tf.Tensor: shape=(), dtype=string, numpy=b'\nR\n\x14\n\x08feature2\x12\x08\n\x06\n\x04goat\n\x14\n\x08feature3\x12\x08\x12\x06\n\x04>\xc0\xe5>\n\x11\n\x08feature0\x12\x05\x1a\x03\n\x01\x01\n\x11\n\x08feature1\x12\x05\x1a\x03\n\x01\x04'>
<tf.Tensor: shape=(), dtype=string, numpy=b'\nU\n\x14\n\x08feature3\x12\x08\x12\x06\n\x04I!\xde\xbe\n\x11\n\x08feature1\x12\x05\x1a\x03\n\x01\x02\n\x11\n\x08feature0\x12\x05\x1a\x03\n\x01\x00\n\x17\n\x08feature2\x12\x0b\n\t\n\x07chicken'>
<tf.Tensor: shape=(), dtype=string, numpy=b'\nQ\n\x11\n\x08feature1\x12\x05\x1a\x03\n\x01\x00\n\x11\n\x08feature0\x12\x05\x1a\x03\n\x01\x01\n\x14\n\x08feature3\x12\x08\x12\x06\n\x04\xe0\x1a\xab\xbf\n\x13\n\x08feature2\x12\x07\n\x05\n\x03cat'>
<tf.Tensor: shape=(), dtype=string, numpy=b'\nQ\n\x13\n\x08feature2\x12\x07\n\x05\n\x03cat\n\x11\n\x08feature0\x12\x05\x1a\x03\n\x01\x01\n\x14\n\x08feature3\x12\x08\x12\x06\n\x04\x87\xb2\xd7?\n\x11\n\x08feature1\x12\x05\x1a\x03\n\x01\x00'>
<tf.Tensor: shape=(), dtype=string, numpy=b'\nR\n\x11\n\x08feature1\x12\x05\x1a\x03\n\x01\x04\n\x11\n\x08feature0\x12\x05\x1a\x03\n\x01\x01\n\x14\n\x08feature3\x12\x08\x12\x06\n\x04n\xe19>\n\x14\n\x08feature2\x12\x08\n\x06\n\x04goat'>
<tf.Tensor: shape=(), dtype=string, numpy=b'\nR\n\x14\n\x08feature3\x12\x08\x12\x06\n\x04\x1as\xd9\xbf\n\x11\n\x08feature0\x12\x05\x1a\x03\n\x01\x01\n\x11\n\x08feature1\x12\x05\x1a\x03\n\x01\x04\n\x14\n\x08feature2\x12\x08\n\x06\n\x04goat'>

Bu tensörler aşağıdaki fonksiyon kullanılarak ayrıştırılabilir. tf.data.Dataset s grafik yürütmeyi kullandığından ve şekillerini ve tip imzalarını oluşturmak için bu açıklamaya ihtiyaç duyduğu için feature_description burada gerekli olduğunu unutmayın:

# Create a description of the features.
feature_description = {
    'feature0': tf.io.FixedLenFeature([], tf.int64, default_value=0),
    'feature1': tf.io.FixedLenFeature([], tf.int64, default_value=0),
    'feature2': tf.io.FixedLenFeature([], tf.string, default_value=''),
    'feature3': tf.io.FixedLenFeature([], tf.float32, default_value=0.0),
}

def _parse_function(example_proto):
  # Parse the input `tf.train.Example` proto using the dictionary above.
  return tf.io.parse_single_example(example_proto, feature_description)

Alternatif olarak, tüm toplu işi bir kerede ayrıştırmak için tf.parse example kullanın. tf.data.Dataset.map yöntemini kullanarak bu işlevi veri kümesindeki her öğeye uygulayın:

parsed_dataset = raw_dataset.map(_parse_function)
parsed_dataset
tutucu37 l10n-yer
<MapDataset element_spec={'feature0': TensorSpec(shape=(), dtype=tf.int64, name=None), 'feature1': TensorSpec(shape=(), dtype=tf.int64, name=None), 'feature2': TensorSpec(shape=(), dtype=tf.string, name=None), 'feature3': TensorSpec(shape=(), dtype=tf.float32, name=None)}>

Veri kümesindeki gözlemleri görüntülemek için istekli yürütmeyi kullanın. Bu veri kümesinde 10.000 gözlem var, ancak yalnızca ilk 10'u göstereceksiniz. Veriler, bir özellikler sözlüğü olarak görüntülenir. Her öğe bir tf.Tensor 'dir ve bu tensörün numpy öğesi özelliğin değerini görüntüler:

for parsed_record in parsed_dataset.take(10):
  print(repr(parsed_record))
tutucu39 l10n-yer
{'feature0': <tf.Tensor: shape=(), dtype=int64, numpy=0>, 'feature1': <tf.Tensor: shape=(), dtype=int64, numpy=4>, 'feature2': <tf.Tensor: shape=(), dtype=string, numpy=b'goat'>, 'feature3': <tf.Tensor: shape=(), dtype=float32, numpy=0.5251196>}
{'feature0': <tf.Tensor: shape=(), dtype=int64, numpy=1>, 'feature1': <tf.Tensor: shape=(), dtype=int64, numpy=4>, 'feature2': <tf.Tensor: shape=(), dtype=string, numpy=b'goat'>, 'feature3': <tf.Tensor: shape=(), dtype=float32, numpy=-0.29878703>}
{'feature0': <tf.Tensor: shape=(), dtype=int64, numpy=1>, 'feature1': <tf.Tensor: shape=(), dtype=int64, numpy=1>, 'feature2': <tf.Tensor: shape=(), dtype=string, numpy=b'dog'>, 'feature3': <tf.Tensor: shape=(), dtype=float32, numpy=0.94824797>}
{'feature0': <tf.Tensor: shape=(), dtype=int64, numpy=1>, 'feature1': <tf.Tensor: shape=(), dtype=int64, numpy=0>, 'feature2': <tf.Tensor: shape=(), dtype=string, numpy=b'cat'>, 'feature3': <tf.Tensor: shape=(), dtype=float32, numpy=0.65749466>}
{'feature0': <tf.Tensor: shape=(), dtype=int64, numpy=1>, 'feature1': <tf.Tensor: shape=(), dtype=int64, numpy=4>, 'feature2': <tf.Tensor: shape=(), dtype=string, numpy=b'goat'>, 'feature3': <tf.Tensor: shape=(), dtype=float32, numpy=0.44873232>}
{'feature0': <tf.Tensor: shape=(), dtype=int64, numpy=0>, 'feature1': <tf.Tensor: shape=(), dtype=int64, numpy=2>, 'feature2': <tf.Tensor: shape=(), dtype=string, numpy=b'chicken'>, 'feature3': <tf.Tensor: shape=(), dtype=float32, numpy=-0.4338477>}
{'feature0': <tf.Tensor: shape=(), dtype=int64, numpy=1>, 'feature1': <tf.Tensor: shape=(), dtype=int64, numpy=0>, 'feature2': <tf.Tensor: shape=(), dtype=string, numpy=b'cat'>, 'feature3': <tf.Tensor: shape=(), dtype=float32, numpy=-1.3367577>}
{'feature0': <tf.Tensor: shape=(), dtype=int64, numpy=1>, 'feature1': <tf.Tensor: shape=(), dtype=int64, numpy=0>, 'feature2': <tf.Tensor: shape=(), dtype=string, numpy=b'cat'>, 'feature3': <tf.Tensor: shape=(), dtype=float32, numpy=1.6851357>}
{'feature0': <tf.Tensor: shape=(), dtype=int64, numpy=1>, 'feature1': <tf.Tensor: shape=(), dtype=int64, numpy=4>, 'feature2': <tf.Tensor: shape=(), dtype=string, numpy=b'goat'>, 'feature3': <tf.Tensor: shape=(), dtype=float32, numpy=0.18152401>}
{'feature0': <tf.Tensor: shape=(), dtype=int64, numpy=1>, 'feature1': <tf.Tensor: shape=(), dtype=int64, numpy=4>, 'feature2': <tf.Tensor: shape=(), dtype=string, numpy=b'goat'>, 'feature3': <tf.Tensor: shape=(), dtype=float32, numpy=-1.6988251>}

Burada, tf.parse_example işlevi, tf.train.Example alanlarını standart tensörlere açar.

Python'da TFRecord dosyaları

tf.io modülü ayrıca TFRecord dosyalarını okumak ve yazmak için saf Python işlevleri içerir.

Bir TFRecord dosyası yazma

Ardından, 10.000 gözlemi test.tfrecord dosyasına yazın. Her gözlem bir tf.train.Example mesajına dönüştürülür, ardından dosyaya yazılır. Ardından test.tfrecord dosyasının oluşturulduğunu doğrulayabilirsiniz:

# Write the `tf.train.Example` observations to the file.
with tf.io.TFRecordWriter(filename) as writer:
  for i in range(n_observations):
    example = serialize_example(feature0[i], feature1[i], feature2[i], feature3[i])
    writer.write(example)
du -sh {filename}
-yer tutucu42 l10n-yer
984K    test.tfrecord

Bir TFRecord dosyasını okuma

Bu serileştirilmiş tensörler, tf.train.Example.ParseFromString kullanılarak kolayca ayrıştırılabilir:

filenames = [filename]
raw_dataset = tf.data.TFRecordDataset(filenames)
raw_dataset
<TFRecordDatasetV2 element_spec=TensorSpec(shape=(), dtype=tf.string, name=None)>
yer tutucu45 l10n-yer
for raw_record in raw_dataset.take(1):
  example = tf.train.Example()
  example.ParseFromString(raw_record.numpy())
  print(example)
features {
  feature {
    key: "feature0"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "feature1"
    value {
      int64_list {
        value: 4
      }
    }
  }
  feature {
    key: "feature2"
    value {
      bytes_list {
        value: "goat"
      }
    }
  }
  feature {
    key: "feature3"
    value {
      float_list {
        value: 0.5251196026802063
      }
    }
  }
}

Bu, olduğu gibi kullanılması zor olan bir tf.train.Example proto döndürür, ancak temelde bir temsilidir:

Dict[str,
     Union[List[float],
           List[int],
           List[str]]]

Aşağıdaki kod, Example TensorFlow Ops kullanmadan manuel olarak NumPy dizileri sözlüğüne dönüştürür. Ayrıntılar için PROTO dosyasına bakın.

result = {}
# example.features.feature is the dictionary
for key, feature in example.features.feature.items():
  # The values are the Feature objects which contain a `kind` which contains:
  # one of three fields: bytes_list, float_list, int64_list

  kind = feature.WhichOneof('kind')
  result[key] = np.array(getattr(feature, kind).value)

result
tutucu49 l10n-yer
{'feature3': array([0.5251196]),
 'feature1': array([4]),
 'feature0': array([0]),
 'feature2': array([b'goat'], dtype='|S4')}

İzlenecek yol: Görüntü verilerini okuma ve yazma

Bu, TFRecords kullanılarak görüntü verilerinin nasıl okunup yazılacağının uçtan uca bir örneğidir. Girdi verisi olarak bir görüntü kullanarak, verileri bir TFRecord dosyası olarak yazacak, ardından dosyayı geri okuyacak ve görüntüyü göstereceksiniz.

Bu, örneğin aynı girdi veri kümesinde birkaç model kullanmak istiyorsanız yararlı olabilir. Görüntü verilerini ham olarak depolamak yerine, TFRecords formatında ön işleme tabi tutulabilir ve bu, sonraki tüm işleme ve modellemede kullanılabilir.

İlk olarak, karda bir kedinin bu görüntüsünü ve yapım aşamasında olan Williamsburg Bridge, NYC'nin bu fotoğrafını indirelim.

Resimleri getir

cat_in_snow  = tf.keras.utils.get_file(
    '320px-Felis_catus-cat_on_snow.jpg',
    'https://storage.googleapis.com/download.tensorflow.org/example_images/320px-Felis_catus-cat_on_snow.jpg')

williamsburg_bridge = tf.keras.utils.get_file(
    '194px-New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg',
    'https://storage.googleapis.com/download.tensorflow.org/example_images/194px-New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg')
Downloading data from https://storage.googleapis.com/download.tensorflow.org/example_images/320px-Felis_catus-cat_on_snow.jpg
24576/17858 [=========================================] - 0s 0us/step
32768/17858 [=======================================================] - 0s 0us/step
Downloading data from https://storage.googleapis.com/download.tensorflow.org/example_images/194px-New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg
16384/15477 [===============================] - 0s 0us/step
24576/15477 [===============================================] - 0s 0us/step
-yer tutucu52 l10n-yer
display.display(display.Image(filename=cat_in_snow))
display.display(display.HTML('Image cc-by: <a "href=https://commons.wikimedia.org/wiki/File:Felis_catus-cat_on_snow.jpg">Von.grzanka</a>'))

jpeg

display.display(display.Image(filename=williamsburg_bridge))
display.display(display.HTML('<a "href=https://commons.wikimedia.org/wiki/File:New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg">From Wikimedia</a>'))

jpeg

TFRecord dosyasını yazın

Daha önce olduğu gibi, özellikleri tf.train.Example ile uyumlu türler olarak kodlayın. Bu, ham görüntü dizesi özelliğinin yanı sıra yükseklik, genişlik, derinlik ve isteğe bağlı label özelliğini de saklar. İkincisi, kedi görüntüsü ile köprü görüntüsü arasında ayrım yapmak için dosyayı yazdığınızda kullanılır. Kedi görüntüsü için 0 ve köprü görüntüsü için 1 kullanın:

image_labels = {
    cat_in_snow : 0,
    williamsburg_bridge : 1,
}
# This is an example, just using the cat image.
image_string = open(cat_in_snow, 'rb').read()

label = image_labels[cat_in_snow]

# Create a dictionary with features that may be relevant.
def image_example(image_string, label):
  image_shape = tf.io.decode_jpeg(image_string).shape

  feature = {
      'height': _int64_feature(image_shape[0]),
      'width': _int64_feature(image_shape[1]),
      'depth': _int64_feature(image_shape[2]),
      'label': _int64_feature(label),
      'image_raw': _bytes_feature(image_string),
  }

  return tf.train.Example(features=tf.train.Features(feature=feature))

for line in str(image_example(image_string, label)).split('\n')[:15]:
  print(line)
print('...')
-yer tutucu56 l10n-yer
features {
  feature {
    key: "depth"
    value {
      int64_list {
        value: 3
      }
    }
  }
  feature {
    key: "height"
    value {
      int64_list {
        value: 213
      }
...

Tüm özelliklerin artık tf.train.Example mesajında ​​saklandığına dikkat edin. Ardından, yukarıdaki kodu işlevselleştirin ve örnek mesajları images.tfrecords adlı bir dosyaya yazın:

# Write the raw image files to `images.tfrecords`.
# First, process the two images into `tf.train.Example` messages.
# Then, write to a `.tfrecords` file.
record_file = 'images.tfrecords'
with tf.io.TFRecordWriter(record_file) as writer:
  for filename, label in image_labels.items():
    image_string = open(filename, 'rb').read()
    tf_example = image_example(image_string, label)
    writer.write(tf_example.SerializeToString())
du -sh {record_file}
-yer tutucu59 l10n-yer
36K images.tfrecords

TFRecord dosyasını okuyun

Artık dosyanız var - images.tfrecords - ve şimdi yazdıklarınızı okumak için içindeki kayıtları yineleyebilirsiniz. Bu örnekte yalnızca görüntüyü yeniden oluşturacağınız göz önüne alındığında, ihtiyacınız olan tek özellik ham görüntü dizesidir. Yukarıda açıklanan alıcıları, yani example.features.feature['image_raw'].bytes_list.value[0] . Etiketleri, hangi kaydın kedi, hangisinin köprü olduğunu belirlemek için de kullanabilirsiniz:

raw_image_dataset = tf.data.TFRecordDataset('images.tfrecords')

# Create a dictionary describing the features.
image_feature_description = {
    'height': tf.io.FixedLenFeature([], tf.int64),
    'width': tf.io.FixedLenFeature([], tf.int64),
    'depth': tf.io.FixedLenFeature([], tf.int64),
    'label': tf.io.FixedLenFeature([], tf.int64),
    'image_raw': tf.io.FixedLenFeature([], tf.string),
}

def _parse_image_function(example_proto):
  # Parse the input tf.train.Example proto using the dictionary above.
  return tf.io.parse_single_example(example_proto, image_feature_description)

parsed_image_dataset = raw_image_dataset.map(_parse_image_function)
parsed_image_dataset
tutucu61 l10n-yer
<MapDataset element_spec={'depth': TensorSpec(shape=(), dtype=tf.int64, name=None), 'height': TensorSpec(shape=(), dtype=tf.int64, name=None), 'image_raw': TensorSpec(shape=(), dtype=tf.string, name=None), 'label': TensorSpec(shape=(), dtype=tf.int64, name=None), 'width': TensorSpec(shape=(), dtype=tf.int64, name=None)}>

TFRecord dosyasındaki görüntüleri kurtarın:

for image_features in parsed_image_dataset:
  image_raw = image_features['image_raw'].numpy()
  display.display(display.Image(data=image_raw))

jpeg

jpeg