Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

TensorFlow Estimator와 Python으로 모델을 컴파일하고 학습하는 방법

TensorFlow는 Estimator와 함께 사용할 수 있으며, 'train' 메서드를 호출하는 것만으로 모델을 손쉽게 컴파일하고 학습시킬 수 있습니다.

함께 읽으면 좋은 글: TensorFlow란 무엇이며, Keras는 어떻게 TensorFlow와 연동하여 신경망을 구축할까요?

이 튜토리얼에서는 Keras Sequential API를 사용합니다. Sequential API는 레이어를 순서대로 쌓아 올리는 단순한 스택 구조의 모델을 만드는 데 유용하며, 각 레이어는 정확히 하나의 입력 텐서와 하나의 출력 텐서를 가집니다.

최소 하나 이상의 합성곱(convolutional) 레이어를 포함하는 신경망을 합성곱 신경망(CNN)이라고 부르며, 이를 활용해 학습 모델을 구축할 수 있습니다.

TensorFlow Text는 TensorFlow 2.0과 함께 사용할 수 있는 텍스트 관련 클래스와 연산(op)들의 모음으로, 시퀀스 모델링을 위한 전처리 작업에 활용됩니다.

본문의 코드는 Google Colaboratory에서 실행되었습니다. Colab은 브라우저에서 별도 설정 없이 Python 코드를 바로 실행할 수 있게 해주며, GPU(그래픽 처리 장치)에도 무료로 접근할 수 있습니다. Colaboratory는 Jupyter Notebook을 기반으로 만들어졌습니다.

Estimator란 무엇인가?

Estimator는 하나의 완전한 모델 전체를 추상화한 TensorFlow의 고수준 인터페이스입니다. 모델을 쉽게 확장(scale)하고 비동기 방식으로 학습할 수 있도록 설계되었습니다.

이 예제에서는 붓꽃(iris) 데이터셋을 사용하여 모델을 학습합니다. 데이터셋은 4개의 특성(feature)과 1개의 라벨(label)로 구성됩니다.

  • 꽃받침 길이(sepal length)
  • 꽃받침 너비(sepal width)
  • 꽃잎 길이(petal length)
  • 꽃잎 너비(petal width)

예제 코드

print("The model is being trained")
classifier.train(input_fn=lambda: input_fn(train, train_y, training=True), steps=5000)

코드 출처 − https://www.tensorflow.org/tutorials/estimator/premade#first_things_first

출력 결과

WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.
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.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Saving checkpoints for 0 into /tmp/tmpbhg2uvbr/model.ckpt.
INFO:tensorflow:loss = 1.1140382, step = 0
INFO:tensorflow:loss = 0.8781501, step = 100 (0.321 sec)
INFO:tensorflow:loss = 0.80712265, step = 200 (0.266 sec)
INFO:tensorflow:loss = 0.7615077, step = 300 (0.268 sec)
INFO:tensorflow:loss = 0.733555, step = 400 (0.271 sec)
...
# (중간 단계 로그 생략: step 500 ~ 4800)
...
INFO:tensorflow:loss = 0.37167495, step = 4900 (0.273 sec)
INFO:tensorflow:Saving checkpoints for 5000 into /tmp/tmpbhg2uvbr/model.ckpt.
INFO:tensorflow:Loss for final step: 0.36297452.
<tensorflow_estimator.python.estimator.canned.dnn.DNNClassifierV2 at 0x7fc9983ed470>

설명

  • Estimator 객체가 한 번 생성되면 다양한 메서드를 호출할 수 있습니다.
  • train 메서드를 호출하여 모델을 학습시킵니다.
  • 학습된 모델을 평가(evaluate)할 수 있습니다.
  • 학습된 모델을 사용해 새로운 데이터에 대한 예측(prediction)을 수행할 수 있습니다.
  • 필요하다면 모델을 추가로 다시 학습시킬 수도 있습니다.
  • 이 모든 과정은 Estimator의 train 메서드 호출을 통해 이루어집니다.

위 출력 결과에서 알 수 있듯이, 손실(loss) 값이 초기 약 1.114에서 최종 약 0.363까지 꾸준히 감소했습니다. 이는 5000 스텝에 걸친 학습 과정에서 모델이 점진적으로 수렴하고 있음을 보여주며, Estimator의 train 메서드가 모델 학습 파이프라인을 얼마나 간편하게 처리해 주는지 잘 드러냅니다.