Tensorflow2.0のTFRRecords制作


TFRRecords制作
  • は、データを効率的に読み出すために、データをシーケンス化して記憶することができ、ネットワークストリーミングによるデータの読み取りを容易にすることができる.TFRRecordは、バイナリシーケンスデータを比較的一般的に記憶する方法
  • である.
  • tf.Exampleクラスはデータを{"string":value}形式で表すmeassageタイプであり、Tensorflowではtfがよく用いられる.Exampleは、TFRRecordデータ
  • を書き込み、読み出す
  • プラットフォーム:Jupter Notebook
  • #        
    import warnings
    warnings.filterwarnings("ignore")
    import numpy as np
    import tensorflow as tf

    通常、tf.Exampleでは、次のフォーマットを使用できます.
  • tf.train.BytesList:stringとbyte
  • を含む使用可能なタイプ
  • tf.train.FloatList:floatとdouble
  • が使用可能
  • tf.train.Int 64 List:使用可能なタイプはenum,bool,int 32,uint 32,int 6
  • #    
    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):
        """Return a float_list form a float/double."""
        return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
    
    def _int64_feature(value):
        """Return a int64_list from a bool/enum/int/uint."""
        return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
    
    
    #    
    # tf.train.BytesList
    print(_bytes_feature(b'test_string'))
    print(_bytes_feature('test_string'.encode('utf8')))
    
    # tf.train.FloatList
    print(_float_feature(np.exp(1)))
    
    # tf.train.Int64List
    print(_int64_feature(True))
    print(_int64_feature(1))
    
    #    
    bytes_list {
      value: "test_string"
    }
    
    bytes_list {
      value: "test_string"
    }
    
    float_list {
      value: 2.7182817459106445
    }
    
    int64_list {
      value: 1
    }
    
    int64_list {
      value: 1
    }
    

    tfrecordの作り方
  • tfを作成する.Example
  • #       
    
    def serialize_example(feature0, feature1, feature2, feature3):
        """
          tf.Example
        """
        
        #        
        feature = {
            'feature0': _int64_feature(feature0),
            'feature1': _int64_feature(feature1),
            'feature2': _bytes_feature(feature2),
            'feature3': _float_feature(feature3),
        }
        #  tf.train.Example   
        example_proto = tf.train.Example(features=tf.train.Features(feature=feature))
        #SerializeToString           
        return example_proto.SerializeToString()
    
    
    #      
    
    #    
    n_observations = int(1e4)
    
    # Boolean feature
    feature0 = np.random.choice([False, True], n_observations)
    
    # Integer feature
    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
    feature3 = np.random.randn(n_observations)
    
    
    #      
    
    filename = 'tfrecord-1'
    
    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)
    

    tfrecordファイルのロード
    filenames = [filename]
    
    #   
    raw_dataset = tf.data.TFRecordDataset(filenames)

     
    以上がアナログtfrecordデータ作成方法
    リンク実戦画像制作実戦