개요

tensorflow estimator에 대해 일부 기억할만한 내용을 정리해둔다. 번역 및 해석에 오류가 있을수 있으니 유의하자.

Estimators

에스티메이터는 high level 텐서플로우 API로 아래의 역할을 한다.

  • training
  • evaluation
  • prediction
  • export for serving

estimator 장점

  • 한번 만들어진 estimator 모델은 코드의 수정없이 CPU/GPU/TPU에서 유연하게 실행 될 수 있다.
  • estimator는 모데을 개발하는 개발자들 사이에서 구현체를 간단하게 공유할 수 있게 해준다.
  • estimator 그 자체는 tf.layers 위에서 구현되어 간단히 customization을 할 수 있게 해준다.
  • estimator가 graph를 자동으로 생성해준다.

Pre-made Estimators

미리 만들어진 estimator를 통해 더 추상화된 레벨로 tensorflow API를 제공한다. 따라서 개발자들은 더이상 그래프 생성이나 세선을 만드는 걱정을 덜 해도 된다. 즉, Estimator가 그래프와 세선 객체를 관리해준다. 더 나아가, Pre-made Estimator는 다른 모델 아키텍쳐를 최소의 코드 변경만으로 가능케 해준다. DNNClassifier를 예로 들면 feed forward 뉴럴넷으로 분류 모델로 학습을 가능케 해준다.

Structure of a pre-made Estimators program

pre-made Estimator를 이용하는 텐서플로우 프로그램은 4가지 단계로 구성되어 있다.

1. 하나 이상의 dataset을 import 함수를 작성한다.

예를 들어, 하나의 함수로 trainset을 불러오고 또다른 하나로 testset을 불러온다. 각 함수는 2개의 객체를 리턴해야 한다.

  • dictionary(keys는 feature 이름, values는 Tensor(또는 SparseTensor))
  • label dictionary(Tensor)

예를 들어 코드의 형식은 아래와 같다.

def input_fn(dataset):
   ...  # manipulate dataset, extracting feature names and the label
   return feature_dict, label

2. feature column 정의하기

tf.feature_column은 feature 이름과 type, 모든 pre-processing 입력을 정의한다. 예를 들어, 아래의 코드 스니펫은 3개의 feature 칼럼을 생성하여 integer나 float로 데이터를 담는다. 첫번째 2개의 feature 칼럼은 feature 이름과 type 정의를 단순화 한다. 3번째 feature column은 또한 람다 표현식을 통해 raw data의 mean scale을 호출한다.

# Define three numeric feature columns.
population = tf.feature_column.numeric_column('population')
crime_rate = tf.feature_column.numeric_column('crime_rate')
median_education = tf.feature_column.numeric_column('median_education',
                    normalizer_fn='lambda x: x - global_education_mean')

3. pre-made Estimator 인스턴스화 하기

예를 들어, 아래는 LinearClassifier 인스턴스화의 예제이다.

# Instantiate an estimator, passing the feature columns.
estimator = tf.estimator.Estimator.LinearClassifier(
    feature_columns=[population, crime_rate, median_education],
    )

4. training, evaluation 또는 inference 메소드를 호출하기 예를 들어, 모든 Estimator는 train 메소드를 제공한다.

# my_training_set is the function created in Step 1
estimator.train(input_fn=my_training_set, steps=2000)

Benefits of pre-made Estimators

pre-made Estimator는 아래의 장점을 지닌다.

  • computation graph 실행에서 일부 다른 부분을 결정하거나 단일 머신이나 클러스터에서 구현에 대한 확장성
  • 이벤트(summary) 기록과 유용한 universal scope의 summary 제공

만약 pre-made Estimator를 사용하지 않는다면, 직접 feature를 handle해야 함.

Custom Estimators

모든 Estimator의 핵심은 model function이다. 이 메소드가 training, evaluation, prediction에 필요한 그래프를 빌드한다. pre-made Estimator를 사용한다는 것은 이미 다른 누군가가 이 함수를 구현해 두었다는 것이다. Custom Estimator를 사용한다면 사용자가 직접 model 함수를 구현해야 한다. 더 자세한 구현법은 링크를 참조한다.

Recommended workflow

아래의 workflow를 권장한다.

  1. pre-made Estimator가 이미 존재하는 것을 가정, 이를 사용하여 모델을 만들고 baseline으로 삼는다.
  2. 종합적인 파이프라인을 생성하고 테스트 하는데 사용자 데이터의 integrity와 reliability를 고려한다.
  3. 사용 가능한 또다른 pre-mdade Estimator가 존재한다면 기존 모델과 비교한다.
  4. 가능하다면, custom Estimator로 모델을 개선한다.

Creating Estimators from Keras models

사용자는 또한 기존의 케라스 모델을 Estimator로 변환할 수 있다. 이를 통해 케라스 모델이 Estimator의 강점을 취할수 있게 한다. 핵심은 https://www.tensorflow.org/api_docs/python/tf/keras/estimator/model_to_estimator 이부분이다.

# Instantiate a Keras inception v3 model.
keras_inception_v3 = tf.keras.applications.inception_v3.InceptionV3(weights=None)
# Compile model with the optimizer, loss, and metrics you'd like to train with.
keras_inception_v3.compile(optimizer=tf.keras.optimizers.SGD(lr=0.0001, momentum=0.9),
                          loss='categorical_crossentropy',
                          metric='accuracy')
# Create an Estimator from the compiled Keras model. Note the initial model
# state of the keras model is preserved in the created Estimator.
est_inception_v3 = tf.keras.estimator.model_to_estimator(keras_model=keras_inception_v3)

# Treat the derived Estimator as you would with any other Estimator.
# First, recover the input name(s) of Keras model, so we can use them as the
# feature column name(s) of the Estimator input function:
keras_inception_v3.input_names  # print out: ['input_1']
# Once we have the input name(s), we can create the input function, for example,
# for input(s) in the format of numpy ndarray:
train_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"input_1": train_data},
    y=train_labels,
    num_epochs=1,
    shuffle=False)
# To train, we call Estimator's train function:
est_inception_v3.train(input_fn=train_input_fn, steps=2000)