TensorFlow는 Estimator와 함께 사용할 수 있으며, classifier 모듈에 포함된 evaluate 메서드를 통해 학습된 모델의 성능을 손쉽게 평가할 수 있습니다.
사전 이해: Keras Sequential API와 CNN
이 글에서는 Keras Sequential API를 사용합니다. Sequential API는 일반적인 레이어 스택 구조의 순차적(sequential) 모델을 구축하는 데 유용하며, 각 레이어는 정확히 하나의 입력 텐서와 하나의 출력 텐서를 가집니다.
적어도 하나의 합성곱(convolutional) 레이어를 포함하는 신경망을 합성곱 신경망(CNN)이라고 하며, 이를 활용해 학습 모델을 만들 수 있습니다.
또한 TensorFlow Text는 텍스트 관련 클래스와 연산(op)들을 모아둔 라이브러리로, TensorFlow 2.0과 함께 사용할 수 있으며 시퀀스 모델링을 위한 전처리 작업에 활용됩니다.
개발 환경: Google Colaboratory
이 글의 코드는 Google Colaboratory에서 실행되었습니다. Colab은 브라우저에서 바로 Python 코드를 실행할 수 있게 해주며, 별도의 설정 없이 GPU(그래픽 처리 장치)를 무료로 사용할 수 있습니다. Colaboratory는 Jupyter Notebook을 기반으로 구축되었습니다.
Estimator란 무엇인가?
Estimator는 TensorFlow에서 완전한 모델을 추상화한 고수준(high-level) 표현입니다. 손쉬운 확장성(scaling)과 비동기 학습(asynchronous training)을 지원하도록 설계되었습니다.
여기서는 대표적인 예제 데이터셋인 붓꽃(iris) 데이터셋을 사용하여 모델을 학습시킵니다.
예제 코드
eval_result = classifier.evaluate(input_fn=lambda: input_fn(test, test_y, training=False))
print('\nTest dataset accuracy is: {accuracy:0.3f}\n'.format(**eval_result))코드 출처 − https://www.tensorflow.org/tutorials/estimator/premade#first_things_first
실행 결과
INFO:tensorflow:Calling model_fn.
WARNING:tensorflow:Layer dnn is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2. The layer has dtype float32 because its dtype defaults to floatx.
If you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this warning is likely only an issue if you are porting a TensorFlow 1.X model to TensorFlow 2.
To change all layers to have dtype float64 by default, call `tf.keras.backend.set_floatx('float64')`. To change just this layer, pass dtype='float64' to the layer constructor. If you are the author of this layer, you can disable autocasting by passing autocast=False to the base Layer constructor.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Starting evaluation at 2020-09-10T01:40:47Z
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmp/tmpbhg2uvbr/model.ckpt-5000
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Inference Time : 0.21153s
INFO:tensorflow:Finished evaluation at 2020-09-10-01:40:47
INFO:tensorflow:Saving dict for global step 5000: accuracy = 0.96666664, average_loss = 0.42594802, global_step = 5000, loss = 0.42594802
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 5000: /tmp/tmpbhg2uvbr/model.ckpt-5000
Test dataset accuracy is: 0.967코드 설명
모델 학습이 완료되면
evaluate메서드를 호출하여 모델의 성능 정보를 확인할 수 있습니다.평가 단계에서는 별도의 매개변수를
evaluate함수에 전달하지 않습니다.평가(evaluation)에 사용되는
input_fn은 데이터를 단 한 번의 에포크(epoch)만 산출(yield)합니다.eval_result딕셔너리에는 다음과 같은 주요 지표가 담겨 있습니다:- average_loss: 샘플 하나당 평균 손실(mean loss per sample)
- loss: 미니 배치(mini-batch)당 평균 손실
- global_step: 해당 Estimator가 수행한 학습 반복(iteration) 횟수
위 실행 결과에서 테스트 데이터셋에 대한 정확도(accuracy)는 약 0.967, 즉 96.7%로 확인되었으며, 총 5,000번의 학습 반복을 거친 체크포인트에서 평가가 수행되었습니다.