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

TensorFlow Estimator로 학습된 모델에서 예측을 수행하는 방법

TensorFlow는 Estimator와 함께 사용하여 새로운 데이터에 대한 예측을 수행할 수 있습니다. 이때 classifier 객체에 내장된 predict 메서드를 활용합니다.

사전 지식

이 글에서는 Keras Sequential API를 사용합니다. Sequential API는 여러 층(layer)이 순서대로 쌓인 순차 모델을 만들 때 유용하며, 각 층은 정확히 하나의 입력 텐서와 하나의 출력 텐서를 가집니다.

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

TensorFlow Text는 TensorFlow 2.0과 함께 사용할 수 있는 텍스트 관련 클래스 및 연산자 집합으로, 시퀀스 모델링을 위한 전처리 작업에 활용됩니다.

본 예제 코드는 Google Colaboratory에서 실행할 수 있습니다. Colab은 브라우저에서 별도 설정 없이 Python 코드를 실행할 수 있게 해주며, GPU에 무료로 접근할 수 있습니다. Colaboratory는 Jupyter Notebook을 기반으로 구축되었습니다.

Estimator란?

Estimator는 TensorFlow에서 완전한 모델을 나타내는 고수준(high-level) 추상화입니다. 손쉬운 확장성(scaling)과 비동기 학습(asynchronous training)을 지원하도록 설계되었습니다.

이번 예제에서는 붓꽃(iris) 데이터셋을 사용해 모델을 학습시킵니다. 데이터셋은 4개의 특성(feature)과 하나의 레이블(label)로 구성됩니다.

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

예제 코드

print("Generating predictions from model")
expected = ['Setosa', 'Versicolor', 'Virginica']
predict_x = {
    'SepalLength': [5.1, 5.9, 6.9],
    'SepalWidth': [3.3, 3.0, 3.1],
    'PetalLength': [1.7, 4.2, 5.4],
    'PetalWidth': [0.5, 1.5, 2.1],
}
print("Defining input function for prediction")
print("It converts inputs to dataset without labels")
def input_fn(features, batch_size=256):
    return tf.data.Dataset.from_tensor_slices(dict(features)).batch(batch_size)
predictions = classifier.predict(
    input_fn=lambda: input_fn(predict_x))

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

실행 결과

Generating predictions from model
Defining input function for prediction
It converts inputs to dataset without labels

설명

  • 학습이 완료된 모델은 좋은 성능의 결과를 생성합니다.
  • 레이블이 없는 측정값만 주어졌을 때도, 해당 측정값을 기반으로 붓꽃의 품종(species)을 예측할 수 있습니다.
  • 예측은 단 한 번의 함수 호출만으로 수행됩니다.