Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/ko/guide/estimator.ipynb
25115 views
Kernel: Python 3
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.

Estimator

경고: Estimator는 새 코드에 권장되지 않습니다. Estimator는 v1.Session 스타일 코드를 실행하며, 이 코드는 올바르게 작성하기가 좀 더 어렵고 특히 TF 2 코드와 결합할 경우 예기치 않게 작동할 수 있습니다. Estimator는 호환성 보장이 적용되지만 보안 취약점 외에는 수정 사항이 제공되지 않습니다. 자세한 내용은 마이그레이션 가이드를 참조하세요.

이 문서는 높은 수준의 TensorFlow API인 tf.estimator를 소개합니다. Estimator는 다음 동작을 캡슐화합니다.

  • 훈련

  • 평가

  • 예측

  • 처리를 위한 내보내기

TensorFlow는 사전 작성된 여러 estimator를 구현합니다. 사용자 정의 estimator도 여전히 지원되지만, 주로 하위 호환성을 위해 사용됩니다. 새 코드에는 사용자 정의 estimator를 사용하지 않아야 합니다. 사전 작성되거나 사용자가 만든 모든 estimator는 tf.estimator.Estimator 클래스를 기반으로 하는 클래스입니다.

간단한 예를 보려면 Estimator 튜토리얼을 참조하세요. API 설계에 대한 개요는 백서를 참조하세요.

설정

!pip install -U tensorflow_datasets
import tempfile import os import tensorflow as tf import tensorflow_datasets as tfds

이점

tf.keras.Model과 유사하게, estimator는 모델 레벨 추상화입니다. tf.estimatortf.keras용으로 현재 개발 중인 일부 기능을 제공합니다. 다음과 같습니다.

  • 매개변수 서버 기반 훈련

  • 완전한 TFX 통합

Estimator 기능

Estimator는 다음과 같은 이점을 제공합니다.

  • 모델을 변경하지 않고 로컬 호스트 또는 분산 다중 서버 환경에서 Estimator 기반 모델을 실행할 수 있습니다. 또한, 모델을 다시 코딩하지 않고 CPU, GPU 또는 TPU에서 Estimator 기반 모델을 실행할 수 있습니다.

  • Estimator는 다음과 같은 방법과 경우를 제어하는 안전한 분산 훈련 루프를 제공합니다.

    • 데이터 로드

    • 예외 처리

    • 체크포인트 파일 생성 및 장애 복구

    • TensorBoard에 대한 요약 저장

Estimator로 애플리케이션을 작성할 때는 데이터 입력 파이프라인을 모델과 분리해야 합니다. 분리를 통해 서로 다른 데이터세트로 실험을 단순화합니다.

사전 작성 Estimator 사용하기

사전 작성 Estimator를 사용하면 기본 TensorFlow API보다 개념이 훨씬 높은 수준에서 작업할 수 있습니다. Estimator가 모든 "배관"을 처리하기 때문에 더 이상 계산 그래프 또는 세션 생성에 대해 걱정할 필요가 없습니다. 또한, 사전 작성 Estimator를 사용하면 최소한의 코드 변경만으로 다양한 모델 아키텍처를 실험할 수 있습니다. 예를 들어, tf.estimator.DNNClassifier는 밀집된 피드 전달 신경망을 기반으로 분류 모델을 훈련하는 사전 작성 Estimator 클래스입니다.

사전 작성된 Estimator에 의존하는 TensorFlow 프로그램은 일반적으로 다음 네 단계로 구성됩니다.

1. 입력 함수를 작성합니다.

예를 들어, 훈련 세트를 가져오는 함수 하나와 테스트 세트를 가져오는 다른 함수 하나를 만들 수 있습니다. Estimator는 입력이 한 쌍의 객체로 형식화될 것으로 예상합니다.

  • 키가 특성 이름이고 값이 해당 특성 데이터를 포함하는 Tensor(또는 SparseTensors)인 사전

  • 하나 이상의 레이블을 포함하는 Tensor

input_fn은 해당 형식의 쌍을 생성하는 tf.data.Dataset을 반환해야 합니다.

예를 들어, 다음 코드는 Titanic 데이터세트의 train.csv 파일에서 tf.data.Dataset를 빌드합니다.

def train_input_fn(): titanic_file = tf.keras.utils.get_file("train.csv", "https://storage.googleapis.com/tf-datasets/titanic/train.csv") titanic = tf.data.experimental.make_csv_dataset( titanic_file, batch_size=32, label_name="survived") titanic_batches = ( titanic.cache().repeat().shuffle(500) .prefetch(tf.data.AUTOTUNE)) return titanic_batches

input_fntf.Graph에서 그래픽 텐서를 포함하는 (features_dics, labels) 쌍을 직접 반환할 수 있지만, 상수 반환과 같은 간단한 경우를 제외하고 오류가 발생하기 쉽습니다.

2. 특성 열을 정의합니다.

tf.feature_column은 특성 이름, 유형 및 모든 입력 전처리를 식별합니다.

예를 들어, 다음 조각은 3개의 특성 열을 만듭니다.

  • 첫 번째는 age 특성을 부동 소수점 입력으로 직접 사용합니다.

  • 두 번째는 class 특성을 범주 입력으로 사용합니다.

  • 세 번째는 embark_town을 범주 입력으로 사용하지만, hashing trick을 사용하여 옵션을 열거할 필요가 없고 옵션 수를 설정합니다.

자세한 내용은 기능 열 튜토리얼을 확인하세요.

age = tf.feature_column.numeric_column('age') cls = tf.feature_column.categorical_column_with_vocabulary_list('class', ['First', 'Second', 'Third']) embark = tf.feature_column.categorical_column_with_hash_bucket('embark_town', 32)

3. 관련 사전 작성 Estimator를 인스턴스화합니다.

예를 들어, LinearClassifier라는 사전 작성된 Estimator의 샘플 인스턴스화는 다음과 같습니다.

model_dir = tempfile.mkdtemp() model = tf.estimator.LinearClassifier( model_dir=model_dir, feature_columns=[embark, cls, age], n_classes=2 )

자세한 내용은 선형 분류자 튜토리얼을 참조하세요.

4. 훈련, 평가 또는 추론 메서드를 호출합니다.

모든 Estimator는 train, evaluatepredict 메서드를 제공합니다.

model = model.train(input_fn=train_input_fn, steps=100)
result = model.evaluate(train_input_fn, steps=10) for key, value in result.items(): print(key, ":", value)
for pred in model.predict(train_input_fn): for key, value in pred.items(): print(key, ":", value) break

사전 작성 Estimator의 이점

사전 작성 Estimator는 모범 사례를 인코딩하여 다음과 같은 이점을 제공합니다.

  • 계산 그래프의 서로 다른 부분이 실행되어야 하는 위치를 결정하고 단일 머신 또는 클러스터에서 전략을 구현하는 모범 사례입니다.

  • 이벤트(요약) 작성 및 보편적으로 유용한 요약에 대한 모범 사례입니다.

사전 작성 Estimator를 사용하지 않는 경우, 앞의 기능을 직접 구현해야 합니다.

사용자 정의 Estimator

모든 Estimator의 핵심은(사전 작성이든 사용자 정의이든) 훈련, 평가 및 예측을 빌드하는 메서드인 모델 함수, model_fn입니다. 사전 작성된 Estimator를 사용하는 경우, 다른 사람이 이미 모델 함수를 구현했습니다. 사용자 정의 Estimator에 의존할 때는 모델 함수를 직접 작성해야 합니다.

참고: 사용자 정의 model_fn은 여전히 ​​1.x 스타일 그래프 모드에서 실행됩니다. 이는 즉시 실행이 없고 자동 제어 종속성이 없음을 의미합니다. 사용자 정의 model_fn을 사용하여 tf.estimator에서 마이그레이션할 계획을 세워야 합니다. 대체 API는 tf.kerastf.distribute입니다. 훈련의 일부에 Estimator가 여전히 필요한 경우, tf.keras.estimator.model_to_estimator 변환기를 사용하여 keras.Model에서 Estimator를 생성할 수 있습니다.

Keras 모델에서 Estimator 생성하기

tf.keras.estimator.model_to_estimator를 사용하여 기존 Keras 모델을 Estimator로 변환할 수 있습니다. 이는 모델 코드를 현대화하려는 경우 유용하지만, 훈련 파이프라인에는 여전히 Estimator가 필요합니다.

Keras MobileNet V2 모델을 인스턴스화하고 옵티마이저, 손실 및 메트릭으로 모델을 컴파일하여 다음으로 훈련합니다.

keras_mobilenet_v2 = tf.keras.applications.MobileNetV2( input_shape=(160, 160, 3), include_top=False) keras_mobilenet_v2.trainable = False estimator_model = tf.keras.Sequential([ keras_mobilenet_v2, tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(1) ]) # Compile the model estimator_model.compile( optimizer='adam', loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics=['accuracy'])

컴파일된 Keras 모델에서 Estimator를 작성합니다. Keras 모델의 초기 모델 상태는 작성된 Estimator에서 유지됩니다.

est_mobilenet_v2 = tf.keras.estimator.model_to_estimator(keras_model=estimator_model)

파생된 Estimator를 다른 Estimator와 마찬가지로 취급합니다.

IMG_SIZE = 160 # All images will be resized to 160x160 def preprocess(image, label): image = tf.cast(image, tf.float32) image = (image/127.5) - 1 image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE)) return image, label
def train_input_fn(batch_size): data = tfds.load('cats_vs_dogs', as_supervised=True) train_data = data['train'] train_data = train_data.map(preprocess).shuffle(500).batch(batch_size) return train_data

훈련하려면, Estimator의 훈련 함수를 호출합니다.

est_mobilenet_v2.train(input_fn=lambda: train_input_fn(32), steps=50)

마찬가지로, 평가하려면 Estimator의 평가 함수를 호출합니다.

est_mobilenet_v2.evaluate(input_fn=lambda: train_input_fn(32), steps=10)

자세한 내용은 tf.keras.estimator.model_to_estimator의 설명서를 참조하세요.

Estimator로 객체 기반 체크포인트 저장하기

Estimator는 기본적으로 체크포인트 가이드에 설명된 객체 그래프가 아닌 변수 이름으로 체크포인트를 저장합니다. tf.train.Checkpoint는 이름 기반 체크포인트를 읽지만, 모델의 일부를 Estimator의 model_fn 외부로 이동할 때 변수 이름이 변경될 수 있습니다. 포워드 호환성을 위해 객체 기반 체크포인트를 저장하면 Estimator 내부에서 모델을 훈련한 다음 모델 외부에서 사용하기가 더 쉽습니다.

import tensorflow.compat.v1 as tf_compat
def toy_dataset(): inputs = tf.range(10.)[:, None] labels = inputs * 5. + tf.range(5.)[None, :] return tf.data.Dataset.from_tensor_slices( dict(x=inputs, y=labels)).repeat().batch(2)
class Net(tf.keras.Model): """A simple linear model.""" def __init__(self): super(Net, self).__init__() self.l1 = tf.keras.layers.Dense(5) def call(self, x): return self.l1(x)
def model_fn(features, labels, mode): net = Net() opt = tf.keras.optimizers.Adam(0.1) ckpt = tf.train.Checkpoint(step=tf_compat.train.get_global_step(), optimizer=opt, net=net) with tf.GradientTape() as tape: output = net(features['x']) loss = tf.reduce_mean(tf.abs(output - features['y'])) variables = net.trainable_variables gradients = tape.gradient(loss, variables) return tf.estimator.EstimatorSpec( mode, loss=loss, train_op=tf.group(opt.apply_gradients(zip(gradients, variables)), ckpt.step.assign_add(1)), # Tell the Estimator to save "ckpt" in an object-based format. scaffold=tf_compat.train.Scaffold(saver=ckpt)) tf.keras.backend.clear_session() est = tf.estimator.Estimator(model_fn, './tf_estimator_example/') est.train(toy_dataset, steps=10)

tf.train.Checkpointmodel_dir에서 Estimator의 체크포인트를 로드할 수 있습니다.

opt = tf.keras.optimizers.Adam(0.1) net = Net() ckpt = tf.train.Checkpoint( step=tf.Variable(1, dtype=tf.int64), optimizer=opt, net=net) ckpt.restore(tf.train.latest_checkpoint('./tf_estimator_example/')) ckpt.step.numpy() # From est.train(..., steps=10)

Estimator에서 SavedModel 내보내기

Estimator는 tf.Estimator.export_saved_model를 통해 SavedModels를 내보냅니다.

input_column = tf.feature_column.numeric_column("x") estimator = tf.estimator.LinearClassifier(feature_columns=[input_column]) def input_fn(): return tf.data.Dataset.from_tensor_slices( ({"x": [1., 2., 3., 4.]}, [1, 1, 0, 0])).repeat(200).shuffle(64).batch(16) estimator.train(input_fn)

Estimator를 저장하려면 serving_input_receiver를 만들어야 합니다. 이 함수는 SavedModel에서 수신한 원시 데이터를 구문 분석하는 tf.Graph의 일부를 빌드합니다.

tf.estimator.export 모듈에는 이러한 receivers를 빌드하는 데 도움이 되는 함수가 포함되어 있습니다.

다음 코드는 tf-serving과 함께 자주 사용되는 직렬화된 tf.Example 프로토콜 버퍼를 허용하는 feature_columns을 기반으로 receiver를 빌드합니다.

tmpdir = tempfile.mkdtemp() serving_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn( tf.feature_column.make_parse_example_spec([input_column])) estimator_base_path = os.path.join(tmpdir, 'from_estimator') estimator_path = estimator.export_saved_model(estimator_base_path, serving_input_fn)

Python에서 해당 모델을 로드하고 실행할 수도 있습니다.

imported = tf.saved_model.load(estimator_path) def predict(x): example = tf.train.Example() example.features.feature["x"].float_list.value.extend([x]) return imported.signatures["predict"]( examples=tf.constant([example.SerializeToString()]))
print(predict(1.5)) print(predict(3.5))

tf.estimator.export.build_raw_serving_input_receiver_fn를 사용하여 tf.train.Example이 아닌 원시 텐서를 사용하는 입력 함수를 만들 수 있습니다.

Estimator와 함께 tf.distribute.Strategy 사용하기(제한적 지원)

tf.estimator는 원래 비동기 매개변수 서버 접근 방식을 지원했던 분산 훈련 TensorFlow API입니다. tf.estimator는 이제 tf.distribute.Strategy를 지원합니다. tf.estimator를 사용하는 경우, 코드를 거의 변경하지 않고 분산 훈련으로 변경할 수 있습니다. 이를 통해 Estimator 사용자는 이제 여러 GPU와 여러 작업자에서 동기식 분산 훈련을 수행하고 TPU도 사용할 수 있습니다. 그러나 Estimator의 이러한 지원은 제한적입니다. 자세한 내용은 현재 지원되는 기능 섹션을 참조하세요.

Estimator에서 tf.distribute.Strategy의 사용은 Keras의 경우와는 약간 다릅니다. 이제 strategy.scope를 사용하는 대신 Estimator용 RunConfig에 전략 객체를 전달합니다.

자세한 내용은 배포 교육 가이드를 참조하세요.

다음은 사전 작성 Estimator LinearRegressorMirroredStrategy로 그 방법을 보여주는 코드 조각입니다.

mirrored_strategy = tf.distribute.MirroredStrategy() config = tf.estimator.RunConfig( train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy) regressor = tf.estimator.LinearRegressor( feature_columns=[tf.feature_column.numeric_column('feats')], optimizer='SGD', config=config)

여기에서는 사전 작성된 Estimator를 사용하지만 사용자 정의 Estimator에서도 같은 코드가 동작합니다. train_distribute는 훈련이 배포되는 방식을 결정하고, eval_distribute는 평가가 배포되는 방식을 결정합니다. 이것은 훈련과 평가 모두에 같은 전략을 사용하는 Keras와의 또 다른 차이점입니다.

이제 입력 함수로 Estimator를 훈련하고 평가할 수 있습니다.

def input_fn(): dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.])) return dataset.repeat(1000).batch(10) regressor.train(input_fn=input_fn, steps=10) regressor.evaluate(input_fn=input_fn, steps=10)

여기서 주목할 Estimator와 Keras의 또 다른 차이점은 입력 처리입니다. Keras에서는 데이터세트의 각 배치가 여러 복제본에 자동으로 분할됩니다. 그러나 Estimator에서는 배치의 자동 분할을 수행하지 않으며 여러 작업자 간에 데이터를 자동으로 샤딩하지도 않습니다. 작업자 및 기기 간에 데이터를 배포하는 방식을 자신이 완전히 제어할 수 있으며 데이터의 배포 방법을 지정하려면 input_fn을 제공해야 합니다.

input_fn은 작업자당 한 번 호출되므로 작업자당 하나의 데이터세트를 제공합니다. 그런 다음 해당 데이터세트의 배치 하나가 해당 작업자의 복제본 하나에 공급되어 작업자 1개에서 복제본 N개에 대해 N개의 배치를 소비합니다. 즉, input_fn에서 반환된 데이터세트는 크기 PER_REPLICA_BATCH_SIZE의 배치를 제공해야 합니다. 그리고 단계의 전역 배치 크기는 PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync로 얻을 수 있습니다.

다중 작업자 훈련을 수행할 때는 작업자 간에 데이터를 분할하거나 각 작업자에 대해 임의의 시드로 셔플해야 합니다. Estimator를 사용한 다중 작업자 훈련 튜토리얼에서 이를 수행하는 방법에 대한 예를 볼 수 있습니다.

마찬가지로 다중 작업자 및 매개변수 서버 전략도 사용할 수 있습니다. 코드는 동일하게 유지되지만, tf.estimator.train_and_evaluate를 사용하고 클러스터에서 실행 중인 각 바이너리에 대해 TF_CONFIG 환경 변수를 설정해야 합니다.

현재 지원되는 것은 무엇입니까?

TPUStrategy를 제외한 모든 전략을 사용하여 Estimator로 훈련하는 작업은 제한적으로 지원됩니다. 기본적인 훈련과 평가는 동작하지만, v1.train.Scaffold와 같은 여러 고급 기능은 동작하지 않습니다. 또한, 이 통합에는 다양한 버그가 있을 수도 있으며 현재로서는 이 지원을 적극적으로 개선할 계획이 없습니다(대신 Keras와 사용자 정의 훈련 루프의 지원에 중점을 둠). 가능하다면 해당 API에 tf.distribute를 대신 사용하는 것이 좋습니다.

훈련 APIMirroredStrategyTPUStrategyMultiWorkerMirroredStrategyCentralStorageStrategyParameterServerStrategy
Estimator API제한적인 지원지원되지 않음제한적인 지원제한적인 지원제한적인 지원

예제 및 튜토리얼

다음은 Estimator로 다양한 전략을 사용하는 방법을 보여주는 몇 가지 엔드 투 엔드 예제입니다.

  1. Estimator를 사용한 다중 작업자 훈련 튜토리얼에서는 MNIST 데이터세트에서 MultiWorkerMirroredStrategy를 사용하여 여러 작업자로 교육하는 방법을 보여줍니다.

  2. Kubernetes 템플릿을 사용하여 tensorflow/ecosystem에서 배포 전략으로 다중 작업자 훈련을 실행하는 엔드 투 엔드 예제. 이 예제는 Keras 모델로 시작하며 tf.keras.estimator.model_to_estimator API를 사용하여 이를 Estimator로 변환합니다.

  3. MirroredStrategy 또는 MultiWorkerMirroredStrategy를 사용하여 훈련할 수 있는 공식 ResNet50 모델