TF record (MNIST 데이터 활용 테스트)
[ 제 네이버 블로그 글을 티스토리로 이전한 글입니다. 해당 글은 제 네이버 블로그에 2020.09.04에 작성되었었습니다 ]
최근 Tensorflow Entended(TFX)를 사용하는 중입니다
TFX에서 모델을 운영할경우, 입력 데이터를 TF record로 변환하여 사용하게되면 모델에서의 데이터 입력 처리 속도를 빠르게 할 수 있다고 합니다.
이때까지는 raw data를 직접 모델에 [batch, data_shape] 형태로 입력하여 사용했었는데, 이번 기회에 TF record를 적용하여 데이터 처리 속도를 높이고자 했습니다.
테스트 환경
- window 10, python 3,7, tensorflow 2.3.0, tfx 0.22.1
테스트 데이터: MNIST 데이터
TF record 포맷으로 데이터를 저장하기 위해서는...
1) Dictionary 형태로 입력데이터가 구성되어야 한다.
2) Dictionary 내의 개개의 값들은 scalar 또는 1D 형태로 구성되어야 한다.
(1) Dictionary 형태로 입력데이터 구성하기
- MNIST 데이터의 경우... 입력 데이터가 raw_data이고 label 정보가 label일 경우...
아래와 같이 dictionary 형태로 표현가능하다.
temp_data = {
'height': raw_data.shape[0],
'width': raw_data.shape[1],
'raw_img': raw_data.flattent(order='C')
'label': label}
return temp_data
(2) Dictionary 형태의 데이터를 Tensorflow datatype list로 변경하기
- 세가지 형태의 datatype: Int64List, FloatList, ByteList
(데이터 구조마다 일부 차이가 있을 수 있지만, ByteList로 데이터를 encoding할 경우 데이터 size를 줄일 수도 있다고 함)
아래 코드를 적절히 활용해서 Tensorflow datatype list로 변환한다.
def _byte_feature(value):
if isinstance(value, type(tf.constant(0))):
value = value.numpy()
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
def _float_feature_array(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def image_example(image_string):
feature = {
'height': _int64_feature(image_string['height']),
'width': _int64_feature(image_string['width']),
'depth': _int64_feature(1),
'label': _int64_feature(image_string['label']),
'image_raw': _float_feature_array(image_string['img_string']),
}
record = tf.train.Example(features=tf.train.Features(feature=feature))
return record
(3) TF record 형태로 파일 저장하기
#Number of TFR files to save the data into
numFiles = 5
records_per_file = int(len(train_data)/numFiles)
for file_id in range(numFiles):
with tf.python_io.TFRecordWriter('MNIST_train_data_strings_' + str(file_id) + '.tfrecord') as writer:
# 모든 데이터 저장할 때까지 반복
for temp_id in range(records_per_file):
convert_data = convert_dict_form(temp_id + file_id * records_per_file)
example = image_example(convert_data)
# TFRecord 파일 쓰기
writer.write(example.SerializeToString())
참고 사이트
https://www.tensorflow.org/tutorials/load_data/tfrecord
TFRecord 및 tf.train.Example | TensorFlow Core
TFRecord 형식은 이진 레코드 시퀀스를 저장하기위한 간단한 형식입니다. 프로토콜 버퍼 는 구조화 된 데이터의 효율적인 직렬화를위한 플랫폼 간, 언어 간 라이브러리입니다. 프로토콜 메시지는
www.tensorflow.org
텐서플로우 트레이닝 데이타 포맷인 *.tfrecord 파일 읽고 쓰기
TFRecord 조대협 (http://bcho.tistory.com) 텐서플로우를 접하게 다 보면 필히 만나는 부분이 텐서플로우 학습 데이타 포맷인 TFRecord라는 파일 포맷이다. 마침 얼굴 인식 모델을 이번에는 텐서플로우에서
bcho.tistory.com
https://kaen2891.tistory.com/69
2차원 음성 대용량 데이터셋을 TfRecord로 읽어오기 (reading TfRecords files for get batch)
글이 많이 늦었습니다. 졸업 준비하느라 바빠져서... 이전 포스팅에 TfRecord로 모든 음성 데이터에 대해 byte로 읽고, 저장하는 것 까지 처리하였다. 이제 해야되는 것은? 모델 설계 한 이후 tensorflow
kaen2891.tistory.com