-
TFRecord FileStudy/TensorFlow 2020. 9. 26. 00:05
TFRecord는 Tensorflow 에서 지원하는 파일 형식이다. 공식 홈페이지에서는 The TFRecord file format is a simple record-oriented binary format that many TensorFlow applications use for training data 라고 표현하고 있다.
TFRecord 파일은 Tensorflow로 딥러닝 학습할때 필요한 데이터들을 보관하기 위한 데이터 포맷이다. 형태는 Binary 형식으로 저장하는 기능을 제공한다.
TFRecord 파일 포맷을 쓰면 좋은 점은 무엇일까??
1. 학습에 필요한 데이터를 관리할 때 학습 데이터 파일과 각 데이터 파일이 의미하는 label 정보가 담겨 있는 파일 두가지로 관리 하게 된다. 학습 데이터와 라벨 정보를 매칭해주는 코드가 필요한데 TFRecord 파일은 이 둘은 함께 관리하고 있다. 별도의 작업이 필요하지 않아 코드 구현시 더욱 효율적이다.
2, 이미지 파일과 같은 경우에는 jpg,png 파일로 되어 있을 경우 매번 코드에서 인코딩/디코딩 작업을 해줘야 하는데 데이터 포맷이 binary형식이기 때문에 이러한 작업이 필요 없다.
3. 이비지 파일을 원본으로 관리하게 되면 파일 사이즈가 크다. 학습에 데이터가 많을수록 큰 사이즈는 속도에 있어서 부담이 된다. 기존 이미지 파일을 TFRecord 파일로 바꿔서 관리하면 사이즈가 작게 관리가 가능하다.
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]))
TensorFlow 공식 홈페이지에서 제공하는 Data types for tf.Example 관련 코드이다.
데이터 형식은 위와 같다.
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()
example_proto.SerializeToString으로 return 받아서 만든다.
개인적으로 프로젝트를 진행 중인데 관련 개념이 나오고 몰라서 간단하게 정리해보았다.
참고자료 : www.tensorflow.org/ , digitalbourgeois.tistory.com/50