시작하기: Keras를 사용한 학습 및 예측

Colab 로고 이 가이드를 Colab에서 메모장으로 실행하기 GitHub 로고 GitHub에서 메모장 보기

이 가이드에서는 Keras sequential API를 사용하여 AI Platform의 신경망을 학습시키고 해당 모델에서 예측을 제공하는 방법을 설명합니다.

Keras는 딥 러닝 모델을 빌드하고 학습시키기 위한 고급 API입니다. tf.keras는 이 API를 TensorFlow 구현한 것입니다.

이 가이드의 처음 두 부분에서는 사전 작성된 Keras 코드를 사용하여 AI Platform에서 모델을 학습시키고, 학습된 모델을 AI Platform에 배포하고, 배포된 모델에서 온라인 예측을 제공하는 과정을 설명합니다.

이 가이드의 마지막 부분에서는 이 모델에 사용된 학습 코드를 자세히 살펴보고 AI Platform과의 호환성을 확인합니다. Keras에서 머신러닝 모델을 보다 일반적으로 빌드하는 방법에 대한 자세한 내용은 TensorFlow의 Keras 가이드를 참조하세요.

데이터세트

이 가이드에서는 UC Irvine Machine Learning Repository에서 제공하는 미국 인구조사 소득 데이터 세트를 사용합니다. 이 데이터세트에는 1994년 인구조사 데이터베이스의 인구 정보(나이, 교육 수준, 결혼 여부, 직업, 연간 소득 $50,000 초과 여부 등)가 포함되어 있습니다.

목표

목표는 다른 인구조사 정보(특성)를 바탕으로 한 개인의 연간 소득이 $50,000를 초과하는지 여부(타겟 라벨)를 예측하는 심층신경망(DNN)을 Keras로 학습시키는 것입니다.

이 가이드에서는 모델 자체의 설계보다는 AI Platform에서 이 모델을 사용하는 방법에 중점을 둡니다. 하지만 머신러닝 시스템 빌드 시 항상 잠재적인 문제와 의도치 못한 결과를 생각해 보는 것이 중요합니다. 공정성에 대한 머신러닝 단기집중과정 연습을 통해 머신러닝 공정성과 인구조사 데이터세트의 편향 요인을 알아보세요.

비용

이 가이드에서는 비용이 청구될 수 있는 다음 Google Cloud 구성요소를 사용합니다.

  • AI Platform Training
  • AI Platform Prediction
  • Cloud Storage

AI Platform Training 가격 책정, AI Platform Prediction 가격 책정, Cloud Storage 가격 책정에 대해 알아보고 가격 계산기를 사용하여 예상 사용량을 기준으로 예상 비용을 산출할 수 있습니다.

시작하기 전에

AI Platform에서 모델을 학습시키고 배포하려면 먼저 다음과 같은 몇 가지 작업을 수행해야 합니다.

  • 로컬 개발 환경을 설정합니다.
  • 결제 및 필요한 API가 사용 설정된 Google Cloud 프로젝트를 설정합니다.
  • 학습 패키지와 학습된 모델을 저장할 Cloud Storage 버킷을 만듭니다.

로컬 개발 환경 설정

이 가이드를 완료하려면 다음이 필요합니다.

  • Git
  • Python 3
  • virtualenv
  • Google Cloud SDK

Python 개발 환경 설정에 대한 Google Cloud 가이드에서는 이러한 요구사항을 충족하는 절차를 상세하게 설명합니다. 다음 단계는 이 절차를 간략하게 설명한 것입니다.

  1. Python 3을 설치합니다.

  2. virtualenv를 설치하고 Python 3을 사용하는 가상 환경을 만듭니다.

  3. 이 환경을 활성화합니다.

  4. 다음 섹션의 단계를 완료하여 Google Cloud SDK를 설치합니다.

Google Cloud 프로젝트 설정

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. API AI Platform Training & Prediction and Compute Engine 사용 설정

    API 사용 설정

  5. Google Cloud CLI를 설치합니다.
  6. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  7. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  8. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  9. API AI Platform Training & Prediction and Compute Engine 사용 설정

    API 사용 설정

  10. Google Cloud CLI를 설치합니다.
  11. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init

GCP 계정 인증

인증을 설정하려면 서비스 계정 키를 만들고 서비스 계정 키의 파일 경로에 해당하는 환경 변수를 설정해야 합니다.

  1. 서비스 계정을 만듭니다.

    1. Google Cloud Console에서 서비스 계정 만들기 페이지로 이동합니다.

      서비스 계정 만들기로 이동

    2. 서비스 계정 이름 필드에 이름을 입력합니다.
    3. 선택사항: 서비스 계정 설명 필드에 설명을 입력합니다.
    4. 만들기를 클릭합니다.
    5. 역할 선택 필드를 클릭합니다. 모든 역할에서 AI Platform > AI Platform 관리자를 선택합니다.
    6. 다른 역할 추가를 클릭합니다.
    7. 역할 선택 필드를 클릭합니다. 모든 역할에서 스토리지 > 스토리지 객체 관리자를 선택합니다.

    8. 완료를 클릭하여 서비스 계정을 만듭니다.

      브라우저 창을 닫지 마세요. 다음 단계에서 사용합니다.

  2. 다음과 같이 인증을 위한 서비스 계정 키를 만듭니다.

    1. Google Cloud Console에서 만든 서비스 계정의 이메일 주소를 클릭합니다.
    2. 를 클릭합니다.
    3. 키 추가를 클릭한 후 새 키 만들기를 클릭합니다.
    4. 만들기를 클릭합니다. JSON 키 파일이 컴퓨터에 다운로드됩니다.
    5. 닫기를 클릭합니다.
  3. 환경 변수 GOOGLE_APPLICATION_CREDENTIALS를 서비스 계정 키가 포함된 JSON 파일의 파일 경로로 설정합니다. 이 변수는 현재 셸 세션에만 적용되므로 새 세션을 연 경우 변수를 다시 설정합니다.

Cloud Storage 버킷 생성

Cloud SDK를 사용하여 학습 작업을 제출할 때 학습 코드가 포함된 Python 패키지를 Cloud Storage 버킷에 업로드합니다. AI Platform은 이 패키지의 코드를 실행합니다. 또한 이 가이드에서 AI Platform은 작업 결과로 얻은 학습된 모델을 동일한 버킷에 저장합니다. 그러면 이 결과를 바탕으로 AI Platform 모델 버전을 만들어 온라인 예측을 제공할 수 있습니다.

Cloud Storage 버킷 이름을 환경 변수로 설정합니다. 이 이름은 모든 Cloud Storage 버킷에서 고유해야 합니다.

BUCKET_NAME="your-bucket-name"

AI Platform TrainingAI Platform Prediction을 사용할 수 있는 리전을 선택하고 다른 환경 변수를 만듭니다. 예를 들면 다음과 같습니다.

REGION="us-central1"

이 리전에 Cloud Storage 버킷을 만들고 나중에 같은 리전을 학습 및 예측에 사용합니다. 버킷이 아직 없으면 다음 명령어를 실행하여 버킷을 만듭니다.

gsutil mb -l $REGION gs://$BUCKET_NAME

빠른 시작: AI Platform에서 학습

가이드의 이 섹션에서는 AI Platform에 학습 작업을 제출하는 과정을 설명합니다. 이 작업에서는 미국 인구조사 데이터로 심층신경망을 학습시키는 데 Keras를 사용하는 샘플 코드를 실행합니다. 그러면 학습된 모델은 Cloud Storage 버킷의 TensorFlow 저장된 모델 디렉터리로 출력됩니다.

학습 코드 및 종속 항목 가져오기

먼저 학습 코드를 다운로드하고 작업 디렉터리를 변경합니다.

# Clone the repository of AI Platform samples
git clone --depth 1 https://github.com/GoogleCloudPlatform/cloudml-samples

# Set the working directory to the sample code directory
cd cloudml-samples/census/tf-keras

학습 코드는 trainer/ 하위 디렉터리에서 Python 패키지로 구성됩니다.

# `ls` shows the working directory's contents. The `p` flag adds trailing
# slashes to subdirectory names. The `R` flag lists subdirectories recursively.
ls -pR
.:
README.md  requirements.txt  trainer/

./trainer:
__init__.py  model.py  task.py  util.py

다음으로 모델을 로컬에서 학습시키는 데 필요한 Python 종속 항목을 설치합니다.

pip install -r requirements.txt

AI Platform에서 학습 작업을 실행하면 선택한 런타임 버전에 따라 종속 항목이 사전 설치됩니다.

로컬에서 모델 학습

AI Platform에서 학습을 진행하기 전에 로컬에서 작업을 학습시켜서 파일 구조와 패키징이 올바른지 확인합니다.

복잡하거나 리소스 사용량이 많은 작업의 경우, 로컬에서 소량의 샘플 데이터세트에 학습시켜 코드를 확인할 수도 있습니다. 그런 다음 AI Platform에서 작업을 실행하여 전체 데이터세트를 학습시킬 수 있습니다.

이 샘플은 소량인 데이터세트에서 비교적 빠르게 작업을 실행하므로 로컬 학습과 AI Platform 작업이 같은 데이터에서 동일한 코드를 실행합니다.

다음 명령어를 실행하여 로컬에서 모델을 학습시킵니다.

# This is similar to `python -m trainer.task --job-dir local-training-output`
# but it better replicates the AI Platform environment, especially
# for distributed training (not applicable here).
gcloud ai-platform local train \
  --package-path trainer \
  --module-name trainer.task \
  --job-dir local-training-output

셸에서 학습 진행 상황을 살펴봅니다. 학습이 끝나면 학습 애플리케이션은 학습된 모델을 내보내고 다음과 같은 메시지를 출력합니다.

Model exported to:  local-training-output/keras_export/1553709223

AI Platform으로 모델 학습

다음으로 AI Platform에 학습 작업을 제출합니다. 그러면 학습 모듈이 클라우드에서 실행되고 학습된 모델이 Cloud Storage로 내보내기됩니다.

먼저 학습 작업 이름을 지정하고, 중간 파일과 출력 파일을 저장할 Cloud Storage 버킷의 디렉터리를 선택합니다. 이 디렉터리를 환경 변수로 설정합니다. 예를 들면 다음과 같습니다.

JOB_NAME="my_first_keras_job"
JOB_DIR="gs://$BUCKET_NAME/keras-job-dir"

다음 명령어를 실행하여 trainer/ 디렉터리를 패키징하고, 지정된 --job-dir에 업로드하고, 이 패키지에서 trainer.task 모듈을 실행하도록 AI Platform에 지시합니다.

셸에서 --stream-logs 플래그를 사용하면 학습 로그를 확인할 수 있습니다. 또한 Google Cloud 콘솔에서 로그 및 기타 작업 세부정보를 확인할 수 있습니다.

gcloud ai-platform jobs submit training $JOB_NAME \
  --package-path trainer/ \
  --module-name trainer.task \
  --region $REGION \
  --python-version 3.7 \
  --runtime-version 1.15 \
  --job-dir $JOB_DIR \
  --stream-logs

이렇게 하면 로컬 학습보다 시간이 오래 걸릴 수 있지만, 비슷한 방식으로 셸에서 학습 진행 상황을 확인할 수 있습니다. 학습이 끝나면 학습 작업은 학습된 모델을 Cloud Storage 버킷으로 내보내고 다음과 같은 메시지를 출력합니다.

INFO    2019-03-27 17:57:11 +0000   master-replica-0        Model exported to:  gs://your-bucket-name/keras-job-dir/keras_export/1553709421
INFO    2019-03-27 17:57:11 +0000   master-replica-0        Module completed; cleaning up.
INFO    2019-03-27 17:57:11 +0000   master-replica-0        Clean up finished.
INFO    2019-03-27 17:57:11 +0000   master-replica-0        Task completed successfully.

초매개변수 조정

포함된 hptuning_config.yaml 구성 파일을 사용하여 선택적으로 초매개변수 조정을 수행할 수 있습니다. AI Platform은 정확성을 최대화하기 위해 이 파일의 정보에 따라 학습을 위한 배치 크기 및 학습률을 여러 번 조정해 봅니다.

이 예시에 있는 학습 코드는 학습 중 TensorFlow Summary Event를 만드는 텐서보드 콜백을 사용합니다. AI Platform은 이와 같은 이벤트를 사용하여 최적화할 측정항목을 추적합니다. AI Platform 학습에서 초매개변수 조정에 대해 자세히 알아보세요.

gcloud ai-platform jobs submit training ${JOB_NAME}_hpt \
  --config hptuning_config.yaml \
  --package-path trainer/ \
  --module-name trainer.task \
  --region $REGION \
  --python-version 3.7 \
  --runtime-version 1.15 \
  --job-dir $JOB_DIR \
  --stream-logs

빠른 시작: AI Platform에서 온라인 예측

이 섹션에서는 AI Platform과 이전 섹션에서 학습시킨 모델을 사용하여 다른 인구조사 정보를 바탕으로 한 개인의 소득 계층을 예측하는 방법을 설명합니다.

AI Platform에서 모델과 버전 리소스 만들기

빠른 시작: 학습에서 학습시켜 내보낸 모델을 사용하여 온라인 예측을 제공하려면 AI Platform에서 모델 리소스를 만들고 그 안에 버전 리소스를 만들어야 합니다. 실제로 버전 리소스가 학습된 모델을 사용하여 예측을 제공합니다. 이러한 구조를 통해 모델을 여러 번 조정 및 재학습시키고 AI Platform에서 모든 버전을 함께 구성할 수 있습니다. 자세한 내용은 모델 및 버전을 참조하세요.

먼저 모델 이름을 지정하고 모델 리소스를 만듭니다.

MODEL_NAME="my_first_keras_model"

gcloud ai-platform models create $MODEL_NAME \
  --regions $REGION
Created ml engine model [projects/your-project-id/models/my_first_keras_model].

다음으로 모델 버전을 만듭니다. 빠른 시작: 학습의 학습 작업에서는 타임스탬프가 적용된 TensorFlow 저장된 모델 디렉터리를 Cloud Storage 버킷으로 내보냈습니다. AI Platform에서는 이 디렉터리를 사용하여 모델 버전을 만듭니다. 저장된 모델 및 AI Platform에 대해 자세히 알아보세요.

이 디렉터리의 경로는 학습 작업의 로그에서 확인할 수 있습니다. 다음과 같은 줄을 찾습니다.

Model exported to:  gs://your-bucket-name/keras-job-dir/keras_export/1545439782

다음 명령어를 실행하여 저장된 모델 디렉터리를 확인하고 이 디렉터리를 사용해 모델 버전 리소스를 만듭니다.

MODEL_VERSION="v1"

# Get a list of directories in the `keras_export` parent directory. Then pick
# the directory with the latest timestamp, in case you've trained multiple
# times.
SAVED_MODEL_PATH=$(gsutil ls $JOB_DIR/keras_export | head -n 1)

# Create model version based on that SavedModel directory
gcloud ai-platform versions create $MODEL_VERSION \
  --model $MODEL_NAME \
  --region $REGION \
  --runtime-version 1.15 \
  --python-version 3.7 \
  --framework tensorflow \
  --origin $SAVED_MODEL_PATH

예측용 입력 준비

유효하고 유용한 예측 결과를 얻으려면 학습 데이터 사전 처리 방법과 동일한 방법으로 예측 입력을 사전 처리해야 합니다. 프로덕션 시스템에서 학습 시와 예측 시에 동일하게 사용할 수 있는 사전 처리 파이프라인을 만들 수도 있습니다.

이 연습에서는 학습 패키지의 데이터 로드 코드를 사용하여 평가 데이터 중에서 무작위로 샘플을 선택합니다. 이 데이터는 각 학습 세대가 끝난 후에 정확성을 평가하는 데 사용된 형식이므로 추가 사전 처리 없이 테스트 예측을 전송하는 데 사용될 수 있습니다.

다음 몇 가지 코드 스니펫을 실행하기 위해 현재 작업 디렉터리에서 Python 인터프리터(python)를 엽니다.

from trainer import util

_, _, eval_x, eval_y = util.load_data()

prediction_input = eval_x.sample(20)
prediction_targets = eval_y[prediction_input.index]

prediction_input
연령 workclass education_num marital_status occupation relationship race capital_gain capital_loss hours_per_week native_country
1979 0.901213 1 1.525542 2 9 0 4 -0.144792 -0.217132 -0.437544 38
2430 -0.922154 3 -0.419265 4 2 3 4 -0.144792 -0.217132 -0.034039 38
4214 -1.213893 3 -0.030304 4 10 1 4 -0.144792 -0.217132 1.579979 38
10389 -0.630415 3 0.358658 4 0 3 4 -0.144792 -0.217132 -0.679647 38
14525 -1.505632 3 -1.586149 4 7 3 0 -0.144792 -0.217132 -0.034039 38
15040 -0.119873 5 0.358658 2 2 0 4 -0.144792 -0.217132 -0.841048 38
8409 0.244801 3 1.525542 2 9 0 4 -0.144792 -0.217132 1.176475 6
10628 0.098931 1 1.525542 2 9 0 4 0.886847 -0.217132 -0.034039 38
10942 0.390670 5 -0.030304 2 4 0 4 -0.144792 -0.217132 4.727315 38
5129 1.120017 3 1.136580 2 12 0 4 -0.144792 -0.217132 -0.034039 38
2096 -1.286827 3 -0.030304 4 11 3 4 -0.144792 -0.217132 -1.648058 38
12463 -0.703350 3 -0.419265 2 7 5 4 -0.144792 4.502280 -0.437544 38
8528 0.536539 3 1.525542 4 3 4 4 -0.144792 -0.217132 -0.034039 38
7093 -1.359762 3 -0.419265 4 6 3 2 -0.144792 -0.217132 -0.034039 38
12565 0.536539 3 1.136580 0 11 2 2 -0.144792 -0.217132 -0.034039 38
5655 1.338821 3 -0.419265 2 2 0 4 -0.144792 -0.217132 -0.034039 38
2322 0.682409 3 1.136580 0 12 3 4 -0.144792 -0.217132 -0.034039 38
12652 0.025997 3 1.136580 2 11 0 4 -0.144792 -0.217132 0.369465 38
4755 -0.411611 3 -0.419265 2 11 0 4 -0.144792 -0.217132 1.176475 38
4413 0.390670 6 1.136580 4 4 1 4 -0.144792 -0.217132 -0.034039 38

occupation과 같은 범주형 필드는 (학습에 사용된 매핑과 동일한 매핑을 사용하여) 이미 정수로 변환되었습니다. age와 같은 숫자 필드는 z-점수로 조정되었습니다. 일부 필드는 원래 데이터에서 삭제되었습니다. 동일한 예에서 예측 입력과 원시 데이터를 비교합니다.

import pandas as pd

_, eval_file_path = util.download(util.DATA_DIR)
raw_eval_data = pd.read_csv(eval_file_path,
                            names=util._CSV_COLUMNS,
                            na_values='?')

raw_eval_data.iloc[prediction_input.index]
연령 workclass fnlwgt education education_num marital_status occupation relationship race gender capital_gain capital_loss hours_per_week native_country income_bracket
1979 51 Local-gov 99064 Masters 14 Married-civ-spouse Prof-specialty Husband White Male 0 0 35 United-States <=50,000
2430 26 Private 197967 HS-grad 9 Never-married Craft-repair Own-child White Male 0 0 40 United-States <=50,000
4214 22 Private 221694 Some-college 10 Never-married Protective-serv Not-in-family White Male 0 0 60 United-States <=50,000
10389 30 Private 96480 Assoc-voc 11 Never-married Adm-clerical Own-child White Female 0 0 32 United-States <=50,000
14525 18 Private 146225 10th 6 Never-married Other-service Own-child Amer-Indian-Eskimo Female 0 0 40 United-States <=50,000
15040 37 Self-emp-not-inc 50096 Assoc-voc 11 Married-civ-spouse Craft-repair Husband White Male 0 0 30 United-States <=50,000
8409 42 Private 102988 Masters 14 Married-civ-spouse Prof-specialty Husband White Male 0 0 55 Ecuador >50,000
10628 40 Local-gov 284086 Masters 14 Married-civ-spouse Prof-specialty Husband White Male 7688 0 40 United-States >50,000
10942 44 Self-emp-not-inc 52505 Some-college 10 Married-civ-spouse Farming-fishing Husband White Male 0 0 99 United-States <=50,000
5129 54 Private 106728 Bachelors 13 Married-civ-spouse Tech-support Husband White Male 0 0 40 United-States <=50,000
2096 21 Private 190916 Some-college 10 Never-married Sales Own-child White Female 0 0 20 United-States <=50,000
12463 29 Private 197565 HS-grad 9 Married-civ-spouse Other-service Wife White Female 0 1902 35 United-States >50,000
8528 46 Private 193188 Masters 14 Never-married Exec-managerial Unmarried White Male 0 0 40 United-States <=50,000
7093 20 Private 273147 HS-grad 9 Never-married Machine-op-inspct Own-child Black Male 0 0 40 United-States <=50,000
12565 46 Private 203653 Bachelors 13 Divorced Sales Other-relative Black Male 0 0 40 United-States <=50,000
5655 57 Private 174662 HS-grad 9 Married-civ-spouse Craft-repair Husband White Male 0 0 40 United-States <=50,000
2322 48 Private 232149 Bachelors 13 Divorced Tech-support Own-child White Female 0 0 40 United-States <=50,000
12652 39 Private 82521 Bachelors 13 Married-civ-spouse Sales Husband White Male 0 0 45 United-States >50,000
4755 33 Private 330715 HS-grad 9 Married-civ-spouse Sales Husband White Male 0 0 55 United-States <=50,000
4413 44 State-gov 128586 Bachelors 13 Never-married Farming-fishing Not-in-family White Male 0 0 40 United-States <=50,000

예측 입력을 줄바꿈으로 구분된 JSON 파일로 내보냅니다.

import json

with open('prediction_input.json', 'w') as json_file:
  for row in prediction_input.values.tolist():
    json.dump(row, json_file)
    json_file.write('\n')

Python 인터프리터(exit())를 종료합니다. 셸에서 prediction_input.json을 검사합니다.

cat prediction_input.json
[0.9012127751273994, 1.0, 1.525541514460902, 2.0, 9.0, 0.0, 4.0, -0.14479173735784842, -0.21713186390175285, -0.43754385253479555, 38.0]
[-0.9221541171760282, 3.0, -0.4192650914017433, 4.0, 2.0, 3.0, 4.0, -0.14479173735784842, -0.21713186390175285, -0.03403923708700391, 38.0]
[-1.2138928199445767, 3.0, -0.030303770229214273, 4.0, 10.0, 1.0, 4.0, -0.14479173735784842, -0.21713186390175285, 1.5799792247041626, 38.0]
[-0.6304154144074798, 3.0, 0.35865755094331475, 4.0, 0.0, 3.0, 4.0, -0.14479173735784842, -0.21713186390175285, -0.6796466218034705, 38.0]
[-1.5056315227131252, 3.0, -1.5861490549193304, 4.0, 7.0, 3.0, 0.0, -0.14479173735784842, -0.21713186390175285, -0.03403923708700391, 38.0]
[-0.11987268456252011, 5.0, 0.35865755094331475, 2.0, 2.0, 0.0, 4.0, -0.14479173735784842, -0.21713186390175285, -0.8410484679825871, 38.0]
[0.24480069389816542, 3.0, 1.525541514460902, 2.0, 9.0, 0.0, 4.0, -0.14479173735784842, -0.21713186390175285, 1.176474609256371, 6.0]
[0.0989313425138912, 1.0, 1.525541514460902, 2.0, 9.0, 0.0, 4.0, 0.8868473744801746, -0.21713186390175285, -0.03403923708700391, 38.0]
[0.39067004528243965, 5.0, -0.030303770229214273, 2.0, 4.0, 0.0, 4.0, -0.14479173735784842, -0.21713186390175285, 4.7273152251969375, 38.0]
[1.1200168022038106, 3.0, 1.1365801932883728, 2.0, 12.0, 0.0, 4.0, -0.14479173735784842, -0.21713186390175285, -0.03403923708700391, 38.0]
[-1.2868274956367138, 3.0, -0.030303770229214273, 4.0, 11.0, 3.0, 4.0, -0.14479173735784842, -0.21713186390175285, -1.6480576988781703, 38.0]
[-0.7033500900996169, 3.0, -0.4192650914017433, 2.0, 7.0, 5.0, 4.0, -0.14479173735784842, 4.5022796885373735, -0.43754385253479555, 38.0]
[0.5365393966667138, 3.0, 1.525541514460902, 4.0, 3.0, 4.0, 4.0, -0.14479173735784842, -0.21713186390175285, -0.03403923708700391, 38.0]
[-1.3597621713288508, 3.0, -0.4192650914017433, 4.0, 6.0, 3.0, 2.0, -0.14479173735784842, -0.21713186390175285, -0.03403923708700391, 38.0]
[0.5365393966667138, 3.0, 1.1365801932883728, 0.0, 11.0, 2.0, 2.0, -0.14479173735784842, -0.21713186390175285, -0.03403923708700391, 38.0]
[1.338820829280222, 3.0, -0.4192650914017433, 2.0, 2.0, 0.0, 4.0, -0.14479173735784842, -0.21713186390175285, -0.03403923708700391, 38.0]
[0.6824087480509881, 3.0, 1.1365801932883728, 0.0, 12.0, 3.0, 4.0, -0.14479173735784842, -0.21713186390175285, -0.03403923708700391, 38.0]
[0.0259966668217541, 3.0, 1.1365801932883728, 2.0, 11.0, 0.0, 4.0, -0.14479173735784842, -0.21713186390175285, 0.3694653783607877, 38.0]
[-0.4116113873310685, 3.0, -0.4192650914017433, 2.0, 11.0, 0.0, 4.0, -0.14479173735784842, -0.21713186390175285, 1.176474609256371, 38.0]
[0.39067004528243965, 6.0, 1.1365801932883728, 4.0, 4.0, 1.0, 4.0, -0.14479173735784842, -0.21713186390175285, -0.03403923708700391, 38.0]

gcloud 명령줄 도구는 온라인 예측을 위해 줄바꿈으로 구분된 JSON을 허용하며, 이 특정 Keras 모델에는 각 입력 예시의 단순 숫자 목록이 필요합니다.

gcloud 도구를 사용하지 않고 REST API에 온라인 예측을 요청하는 경우 AI Platform에는 다른 형식이 필요합니다. 모델 구조에 따라 예측용 데이터 형식 지정 방법이 바뀔 수도 있습니다. 자세한 내용은 온라인 예측용 데이터 형식 지정을 참조하세요.

온라인 예측 요청 제출

gcloud를 사용하여 온라인 예측 요청을 제출합니다.

gcloud ai-platform predict \
  --model $MODEL_NAME \
  --region $REGION \
  --version $MODEL_VERSION \
  --json-instances prediction_input.json
DENSE_4
[0.6854287385940552]
[0.011786997318267822]
[0.037236183881759644]
[0.016223609447479248]
[0.0012015104293823242]
[0.23621389269828796]
[0.6174039244651794]
[0.9822691679000854]
[0.3815768361091614]
[0.6715215444564819]
[0.001094043254852295]
[0.43077391386032104]
[0.22132840752601624]
[0.004075437784194946]
[0.22736871242523193]
[0.4111979305744171]
[0.27328649163246155]
[0.6981356143951416]
[0.3309604525566101]
[0.20807647705078125]

모델의 마지막 레이어는 시그모이드 함수를 사용하여 활성화되므로 0과 0.5 사이의 출력은 음성 예측('<=50,000')을 나타내고, 0.5와 1 사이의 출력은 양성 예측('>50,000')을 나타냅니다.

Keras 모델을 처음부터 개발하기

이제 AI Platform에서 머신러닝 모델을 학습시켰고, 학습된 모델을 AI Platform에서 버전 리소스로 배포했으며, 배포에서 온라인 예측 결과를 얻었습니다. 다음 섹션에서는 모델 학습에 사용되는 Keras 코드를 다시 만드는 과정을 설명합니다. 특히 다음과 같은 AI Platform에서 사용할 수 있도록 머신러닝 모델을 개발하는 부분을 다룹니다.

  • 데이터 다운로드 및 사전 처리
  • 모델 설계 및 학습
  • 학습 시각화 및 학습된 모델 내보내기

이 섹션에서는 앞부분에서 완료한 작업을 보다 상세하게 설명합니다. 하지만 tf.keras 사용 방법을 자세히 알아보려면 TensorFlow의 Keras 가이드를 참조하세요. AI Platform용 학습 패키지로 코드를 구성하는 방법에 대한 자세한 내용은 학습 애플리케이션 패키징 및 Python 패키지로 구성된 전체 학습 코드를 참조하세요.

라이브러리 가져오기 및 상수 정의

먼저 학습에 필요한 Python 라이브러리를 가져옵니다.

import os
from six.moves import urllib
import tempfile

import numpy as np
import pandas as pd
import tensorflow as tf

# Examine software versions
print(__import__('sys').version)
print(tf.__version__)
print(tf.keras.__version__)

그런 다음 몇 가지 유용한 상수를 정의합니다.

  • 학습 데이터와 평가 데이터 다운로드 정보
  • Pandas가 데이터를 해석하고 범주형 필드를 숫자 특성으로 변환하는 데 필요한 정보
  • 학습률 및 배치 크기와 같은 학습용 초매개변수
### For downloading data ###

# Storage directory
DATA_DIR = os.path.join(tempfile.gettempdir(), 'census_data')

# Download options.
DATA_URL = 'https://storage.googleapis.com/cloud-samples-data/ai-platform' \
           '/census/data'
TRAINING_FILE = 'adult.data.csv'
EVAL_FILE = 'adult.test.csv'
TRAINING_URL = '%s/%s' % (DATA_URL, TRAINING_FILE)
EVAL_URL = '%s/%s' % (DATA_URL, EVAL_FILE)

### For interpreting data ###

# These are the features in the dataset.
# Dataset information: https://archive.ics.uci.edu/ml/datasets/census+income
_CSV_COLUMNS = [
    'age', 'workclass', 'fnlwgt', 'education', 'education_num',
    'marital_status', 'occupation', 'relationship', 'race', 'gender',
    'capital_gain', 'capital_loss', 'hours_per_week', 'native_country',
    'income_bracket'
]

_CATEGORICAL_TYPES = {
  'workclass': pd.api.types.CategoricalDtype(categories=[
    'Federal-gov', 'Local-gov', 'Never-worked', 'Private', 'Self-emp-inc',
    'Self-emp-not-inc', 'State-gov', 'Without-pay'
  ]),
  'marital_status': pd.api.types.CategoricalDtype(categories=[
    'Divorced', 'Married-AF-spouse', 'Married-civ-spouse',
    'Married-spouse-absent', 'Never-married', 'Separated', 'Widowed'
  ]),
  'occupation': pd.api.types.CategoricalDtype([
    'Adm-clerical', 'Armed-Forces', 'Craft-repair', 'Exec-managerial',
    'Farming-fishing', 'Handlers-cleaners', 'Machine-op-inspct',
    'Other-service', 'Priv-house-serv', 'Prof-specialty', 'Protective-serv',
    'Sales', 'Tech-support', 'Transport-moving'
  ]),
  'relationship': pd.api.types.CategoricalDtype(categories=[
    'Husband', 'Not-in-family', 'Other-relative', 'Own-child', 'Unmarried',
    'Wife'
  ]),
  'race': pd.api.types.CategoricalDtype(categories=[
    'Amer-Indian-Eskimo', 'Asian-Pac-Islander', 'Black', 'Other', 'White'
  ]),
  'native_country': pd.api.types.CategoricalDtype(categories=[
    'Cambodia', 'Canada', 'China', 'Columbia', 'Cuba', 'Dominican-Republic',
    'Ecuador', 'El-Salvador', 'England', 'France', 'Germany', 'Greece',
    'Guatemala', 'Haiti', 'Holand-Netherlands', 'Honduras', 'Hong', 'Hungary',
    'India', 'Iran', 'Ireland', 'Italy', 'Jamaica', 'Japan', 'Laos', 'Mexico',
    'Nicaragua', 'Outlying-US(Guam-USVI-etc)', 'Peru', 'Philippines', 'Poland',
    'Portugal', 'Puerto-Rico', 'Scotland', 'South', 'Taiwan', 'Thailand',
    'Trinadad&Tobago', 'United-States', 'Vietnam', 'Yugoslavia'
  ]),
  'income_bracket': pd.api.types.CategoricalDtype(categories=[
    '<=50K', '>50K'
  ])
}

# This is the label (target) we want to predict.
_LABEL_COLUMN = 'income_bracket'

### Hyperparameters for training ###

# This the training batch size
BATCH_SIZE = 128

# This is the number of epochs (passes over the full training data)
NUM_EPOCHS = 20

# Define learning rate.
LEARNING_RATE = .01

데이터 다운로드 및 사전 처리

데이터 다운로드

다음으로 학습 데이터와 평가 데이터를 다운로드하는 함수를 정의합니다. 이 함수는 데이터 형식의 사소한 문제도 수정합니다.

def _download_and_clean_file(filename, url):
  """Downloads data from url, and makes changes to match the CSV format.

  The CSVs may use spaces after the comma delimters (non-standard) or include
  rows which do not represent well-formed examples. This function strips out
  some of these problems.

  Args:
    filename: filename to save url to
    url: URL of resource to download
  """
  temp_file, _ = urllib.request.urlretrieve(url)
  with tf.gfile.Open(temp_file, 'r') as temp_file_object:
    with tf.gfile.Open(filename, 'w') as file_object:
      for line in temp_file_object:
        line = line.strip()
        line = line.replace(', ', ',')
        if not line or ',' not in line:
          continue
        if line[-1] == '.':
          line = line[:-1]
        line += '\n'
        file_object.write(line)
  tf.gfile.Remove(temp_file)

def download(data_dir):
  """Downloads census data if it is not already present.

  Args:
    data_dir: directory where we will access/save the census data
  """
  tf.gfile.MakeDirs(data_dir)

  training_file_path = os.path.join(data_dir, TRAINING_FILE)
  if not tf.gfile.Exists(training_file_path):
    _download_and_clean_file(training_file_path, TRAINING_URL)

  eval_file_path = os.path.join(data_dir, EVAL_FILE)
  if not tf.gfile.Exists(eval_file_path):
    _download_and_clean_file(eval_file_path, EVAL_URL)

  return training_file_path, eval_file_path

이러한 함수를 사용하여 학습용 데이터를 다운로드하고 학습 및 평가용 CSV 파일이 있는지 확인합니다.

training_file_path, eval_file_path = download(DATA_DIR)

다음으로 Pandas를 사용하여 이러한 파일을 로드하고 데이터를 검사합니다.

# This census data uses the value '?' for fields (column) that are missing data.
# We use na_values to find ? and set it to NaN values.
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html

train_df = pd.read_csv(training_file_path, names=_CSV_COLUMNS, na_values='?')
eval_df = pd.read_csv(eval_file_path, names=_CSV_COLUMNS, na_values='?')

다음 테이블에서는 사전 처리하기 전의 데이터(train_df.head()) 일부를 보여줍니다.

연령 workclass fnlwgt education education_num marital_status occupation relationship race gender capital_gain capital_loss hours_per_week native_country income_bracket
0 39 State-gov 77516 Bachelors 13 Never-married Adm-clerical Not-in-family White Male 2174 0 40 United-States <=50,000
1 50 Self-emp-not-inc 83311 Bachelors 13 Married-civ-spouse Exec-managerial Husband White Male 0 0 13 United-States <=50,000
2 38 Private 215646 HS-grad 9 Divorced Handlers-cleaners Not-in-family White Male 0 0 40 United-States <=50,000
3 53 Private 234721 11th 7 Married-civ-spouse Handlers-cleaners Husband Black Male 0 0 40 United-States <=50,000
4 28 Private 338409 Bachelors 13 Married-civ-spouse Prof-specialty Wife Black Female 0 0 40 Cuba <=50,000

데이터 사전 처리

첫 번째 사전 처리 단계에서는 데이터에서 지정된 특성을 삭제하고 Keras에서 사용할 수 있도록 범주형 특성을 숫자 값으로 변환합니다.

자세한 내용은 특성 추출데이터 편향을 참조하세요.

UNUSED_COLUMNS = ['fnlwgt', 'education', 'gender']

def preprocess(dataframe):
  """Converts categorical features to numeric. Removes unused columns.

  Args:
    dataframe: Pandas dataframe with raw data

  Returns:
    Dataframe with preprocessed data
  """
  dataframe = dataframe.drop(columns=UNUSED_COLUMNS)

  # Convert integer valued (numeric) columns to floating point
  numeric_columns = dataframe.select_dtypes(['int64']).columns
  dataframe[numeric_columns] = dataframe[numeric_columns].astype('float32')

  # Convert categorical columns to numeric
  cat_columns = dataframe.select_dtypes(['object']).columns
  dataframe[cat_columns] = dataframe[cat_columns].apply(lambda x: x.astype(
    _CATEGORICAL_TYPES[x.name]))
  dataframe[cat_columns] = dataframe[cat_columns].apply(lambda x: x.cat.codes)
  return dataframe

prepped_train_df = preprocess(train_df)
prepped_eval_df = preprocess(eval_df)

다음 테이블(prepped_train_df.head())에서는 데이터가 사전 처리를 통해 어떻게 바뀌었는지 보여줍니다. 특히 예측을 위해 모델을 학습시킬 라벨인 income_bracket<=50K>50K에서 01로 변경되었습니다.

연령 workclass education_num marital_status occupation relationship race capital_gain capital_loss hours_per_week native_country income_bracket
0 39.0 6 13.0 4 0 1 4 2174.0 0.0 40.0 38 0
1 50.0 5 13.0 2 3 0 4 0.0 0.0 13.0 38 0
2 38.0 3 9.0 0 5 1 4 0.0 0.0 40.0 38 0
3 53.0 3 7.0 2 5 0 2 0.0 0.0 40.0 38 0
4 28.0 3 13.0 2 9 5 2 0.0 0.0 40.0 4 0

이제 데이터를 특징("x") 및 라벨("y")로 구분하고 라벨 배열을 나중에 tf.data.Dataset에 사용할 수 있는 형식으로 바꿉니다

# Split train and test data with labels.
# The pop() method will extract (copy) and remove the label column from the dataframe
train_x, train_y = prepped_train_df, prepped_train_df.pop(_LABEL_COLUMN)
eval_x, eval_y = prepped_eval_df, prepped_eval_df.pop(_LABEL_COLUMN)

# Reshape label columns for use with tf.data.Dataset
train_y = np.asarray(train_y).astype('float32').reshape((-1, 1))
eval_y = np.asarray(eval_y).astype('float32').reshape((-1, 1))

각 숫자 특성 열의 평균 값이 0이고 표준 편차가 1이 되도록 학습 데이터를 조정하면 모델을 개선할 수 있습니다.

프로덕션 시스템에서 학습 세트의 평균 값과 표준 편차를 저장한 후 예측 시 사용하여 테스트 데이터에서 동일한 변환을 수행할 수 있습니다. 이 연습에서는 편의를 위해 학습 데이터와 평가 데이터를 임시로 결합하여 함께 조정합니다.

def standardize(dataframe):
  """Scales numerical columns using their means and standard deviation to get
  z-scores: the mean of each numerical column becomes 0, and the standard
  deviation becomes 1. This can help the model converge during training.

  Args:
    dataframe: Pandas dataframe

  Returns:
    Input dataframe with the numerical columns scaled to z-scores
  """
  dtypes = list(zip(dataframe.dtypes.index, map(str, dataframe.dtypes)))
  # Normalize numeric columns.
  for column, dtype in dtypes:
      if dtype == 'float32':
          dataframe[column] -= dataframe[column].mean()
          dataframe[column] /= dataframe[column].std()
  return dataframe

# Join train_x and eval_x to normalize on overall means and standard
# deviations. Then separate them again.
all_x = pd.concat([train_x, eval_x], keys=['train', 'eval'])
all_x = standardize(all_x)
train_x, eval_x = all_x.xs('train'), all_x.xs('eval')

다음 테이블(train_x.head())은 사전 처리가 완료된 데이터의 모습을 보여줍니다.

연령 workclass education_num marital_status occupation relationship race capital_gain capital_loss hours_per_week native_country
0 0.025997 6 1.136580 4 0 1 4 0.146933 -0.217132 -0.034039 38
1 0.828278 5 1.136580 2 3 0 4 -0.144792 -0.217132 -2.212964 38
2 -0.046938 3 -0.419265 0 5 1 4 -0.144792 -0.217132 -0.034039 38
3 1.047082 3 -1.197188 2 5 0 2 -0.144792 -0.217132 -0.034039 38
4 -0.776285 3 1.136580 2 9 5 2 -0.144792 -0.217132 -0.034039 4

모델 설계 및 학습

학습 데이터 세트와 검증 데이터 세트 만들기

학습 또는 평가를 위해 특징과 라벨을 tf.data.Dataset로 변환하는 입력 함수를 만듭니다.

def input_fn(features, labels, shuffle, num_epochs, batch_size):
  """Generates an input function to be used for model training.

  Args:
    features: numpy array of features used for training or inference
    labels: numpy array of labels for each example
    shuffle: boolean for whether to shuffle the data or not (set True for
      training, False for evaluation)
    num_epochs: number of epochs to provide the data for
    batch_size: batch size for training

  Returns:
    A tf.data.Dataset that can provide data to the Keras model for training or
      evaluation
  """
  if labels is None:
    inputs = features
  else:
    inputs = (features, labels)
  dataset = tf.data.Dataset.from_tensor_slices(inputs)

  if shuffle:
    dataset = dataset.shuffle(buffer_size=len(features))

  # We call repeat after shuffling, rather than before, to prevent separate
  # epochs from blending together.
  dataset = dataset.repeat(num_epochs)
  dataset = dataset.batch(batch_size)
  return dataset

다음으로 학습 데이터세트와 평가 데이터세트를 만듭니다. 앞에서 정의한 NUM_EPOCHSBATCH_SIZE 초매개변수를 사용하여 학습 중에 학습 데이터세트가 모델에 예를 제공하는 방법을 정의합니다. 각 학습 세대가 끝나면 단일 검증 단계에 모든 예시를 일괄 제공하는 검증 데이터세트를 설정합니다.

# Pass a numpy array by using DataFrame.values
training_dataset = input_fn(features=train_x.values,
                    labels=train_y,
                    shuffle=True,
                    num_epochs=NUM_EPOCHS,
                    batch_size=BATCH_SIZE)

num_eval_examples = eval_x.shape[0]

# Pass a numpy array by using DataFrame.values
validation_dataset = input_fn(features=eval_x.values,
                    labels=eval_y,
                    shuffle=False,
                    num_epochs=NUM_EPOCHS,
                    batch_size=num_eval_examples)

Keras 모델 설계

Keras Sequential API를 사용하여 신경망을 설계합니다.

이 심층신경망(DNN)에는 히든 레이어가 여러 개 있으며, 마지막 레이어에서는 시그모이드 활성화 함수를 사용하여 0과 1 사이의 값을 출력합니다.

  • 입력 레이어에는 ReLU 활성화 함수를 사용하는 단위가 100개 있습니다.
  • 히든 레이어에는 ReLU 활성화 함수를 사용하는 단위가 75개 있습니다.
  • 히든 레이어에는 ReLU 활성화 함수를 사용하는 단위가 50개 있습니다.
  • 히든 레이어에는 ReLU 활성화 함수를 사용하는 단위가 25개 있습니다.
  • 출력 레이어에는 시그모이드 활성화 함수를 사용하는 단위가 1개 있습니다.
  • 옵티마이저는 이와 같은 바이너리 분류 문제에 적합한 바이너리 교차 엔트로피 손실 함수를 사용합니다.

이러한 레이어를 원하는 대로 변경하여 모델을 개선할 수 있습니다.

def create_keras_model(input_dim, learning_rate):
  """Creates Keras Model for Binary Classification.

  Args:
    input_dim: How many features the input has
    learning_rate: Learning rate for training

  Returns:
    The compiled Keras model (still needs to be trained)
  """
  Dense = tf.keras.layers.Dense
  model = tf.keras.Sequential(
    [
        Dense(100, activation=tf.nn.relu, kernel_initializer='uniform',
                input_shape=(input_dim,)),
        Dense(75, activation=tf.nn.relu),
        Dense(50, activation=tf.nn.relu),
        Dense(25, activation=tf.nn.relu),
        Dense(1, activation=tf.nn.sigmoid)
    ])

  # Custom Optimizer:
  # https://www.tensorflow.org/api_docs/python/tf/train/RMSPropOptimizer
  optimizer = tf.keras.optimizers.RMSprop(
      lr=learning_rate)

  # Compile Keras model
  model.compile(
      loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
  return model

다음으로 Keras 모델 객체를 만듭니다.

num_train_examples, input_dim = train_x.shape
print('Number of features: {}'.format(input_dim))
print('Number of examples: {}'.format(num_train_examples))

keras_model = create_keras_model(
    input_dim=input_dim,
    learning_rate=LEARNING_RATE)

keras_model.summary()로 모델을 검사하면 다음과 같은 결과가 반환됩니다.

Number of features: 11
Number of examples: 32561
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/resource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense (Dense)                (None, 100)               1200
_________________________________________________________________
dense_1 (Dense)              (None, 75)                7575
_________________________________________________________________
dense_2 (Dense)              (None, 50)                3800
_________________________________________________________________
dense_3 (Dense)              (None, 25)                1275
_________________________________________________________________
dense_4 (Dense)              (None, 1)                 26
=================================================================
Total params: 13,876
Trainable params: 13,876
Non-trainable params: 0
_________________________________________________________________

모델 학습 및 평가

학습률 감소를 정의하여 학습 진행됨에 따라 모델 매개변수가 변경 크기를 줄이도록 유도합니다.

# Setup Learning Rate decay.
lr_decay_cb = tf.keras.callbacks.LearningRateScheduler(
    lambda epoch: LEARNING_RATE + 0.02 * (0.5 ** (1 + epoch)),
    verbose=True)

# Setup TensorBoard callback.
JOB_DIR = os.getenv('JOB_DIR')
tensorboard_cb = tf.keras.callbacks.TensorBoard(
      os.path.join(JOB_DIR, 'keras_tensorboard'),
      histogram_freq=1)

마지막으로 모델을 학습시킵니다. 각 세대 중에 전체 학습 데이터세트(단계마다 BATCH_SIZE 예시 포함)에서 모델을 학습시키는 데 적합한 steps_per_epoch를 제공합니다. 그리고 각 세대가 끝나면 큰 검증 배치 한 개를 사용하여 검증 정확도를 계산하도록 모델에 지시합니다.

history = keras_model.fit(training_dataset,
                          epochs=NUM_EPOCHS,
                          steps_per_epoch=int(num_train_examples/BATCH_SIZE),
                          validation_data=validation_dataset,
                          validation_steps=1,
                          callbacks=[lr_decay_cb, tensorboard_cb],
                          verbose=1)

학습 진행 상황은 다음과 같이 표시됩니다.

WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.

Epoch 00001: LearningRateScheduler reducing learning rate to 0.02.
Epoch 1/20
254/254 [==============================] - 1s 5ms/step - loss: 0.6986 - acc: 0.7893 - val_loss: 0.3894 - val_acc: 0.8329

Epoch 00002: LearningRateScheduler reducing learning rate to 0.015.
Epoch 2/20
254/254 [==============================] - 1s 4ms/step - loss: 0.3574 - acc: 0.8335 - val_loss: 0.3861 - val_acc: 0.8131

...

Epoch 00019: LearningRateScheduler reducing learning rate to 0.010000038146972657.
Epoch 19/20
254/254 [==============================] - 1s 4ms/step - loss: 0.3239 - acc: 0.8512 - val_loss: 0.3334 - val_acc: 0.8496

Epoch 00020: LearningRateScheduler reducing learning rate to 0.010000019073486329.
Epoch 20/20
254/254 [==============================] - 1s 4ms/step - loss: 0.3279 - acc: 0.8504 - val_loss: 0.3174 - val_acc: 0.8523

학습 시각화 및 학습된 모델 내보내기

학습 시각화

matplotlib을 가져와 학습 기간 동안의 모델 학습 과정을 시각화할 수 있습니다. (필요한 경우 먼저 pip install matplotlib으로 설치합니다.)

from matplotlib import pyplot as plt

각 학습 세대가 끝나면 측정된 모델 손실(바이너리 교차 엔트로피)과 정확성이 표시됩니다.

# Visualize History for Loss.
plt.title('Keras model loss')
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['training', 'validation'], loc='upper right')
plt.show()

# Visualize History for Accuracy.
plt.title('Keras model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.legend(['training', 'validation'], loc='lower right')
plt.show()

시간이 경과함에 따라 손실은 줄어들고 정확성은 높아집니다. 하지만 이러한 손실과 정확성이 안정적인 수준에 수렴하는지, 학습 측정항목과 검증 측정항목 사이에 큰 차이가 있는지(과적합 징후) 확인해야 합니다.

자세한 내용은 머신러닝 모델 개선하는 방법을 참조하세요. 그런 다음 초매개변수 또는 모델 아키텍처를 원하는 대로 조정하고 다시 학습시킵니다.

예측을 제공할 모델 내보내기

tf.contrib.saved_model.save_keras_model을 사용하여 TensorFlow 저장된 모델 디렉터리를 내보냅니다. 이 형식은 AI Platform에서 모델 버전 리소스를 만들 때 필요합니다.

모든 옵티마이저를 저장된 모델 형식으로 내보낼 수 있는 것은 아니므로 내보내기 중에 경고가 표시될 수 있습니다. 서빙 그래프를 성공적으로 내보내기만 하면 AI Platform이 저장된 모델을 사용하여 예측을 제공할 수 있습니다.

# Export the model to a local SavedModel directory
export_path = tf.contrib.saved_model.save_keras_model(keras_model, 'keras_export')
print("Model exported to: ", export_path)
WARNING: The TensorFlow contrib module will not be included in TensorFlow 2.0.
For more information, please see:
  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md
  * https://github.com/tensorflow/addons
If you depend on functionality not listed there, please file an issue.

WARNING:tensorflow:This model was compiled with a Keras optimizer (<tensorflow.python.keras.optimizers.RMSprop object at 0x7fc198c4e400>) but is being saved in TensorFlow format with `save_weights`. The model's weights will be saved, but unlike with TensorFlow optimizers in the TensorFlow format the optimizer's state will not be saved.

Consider using a TensorFlow optimizer from `tf.train`.
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/network.py:1436: update_checkpoint_state (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.train.CheckpointManager to manage checkpoints rather than manually editing the Checkpoint proto.
WARNING:tensorflow:Model was compiled with an optimizer, but the optimizer is not from `tf.train` (e.g. `tf.train.AdagradOptimizer`). Only the serving graph was exported. The train and evaluate graphs were not added to the SavedModel.
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/saved_model/signature_def_utils_impl.py:205: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.
INFO:tensorflow:Signatures INCLUDED in export for Classify: None
INFO:tensorflow:Signatures INCLUDED in export for Regress: None
INFO:tensorflow:Signatures INCLUDED in export for Predict: ['serving_default']
INFO:tensorflow:Signatures INCLUDED in export for Train: None
INFO:tensorflow:Signatures INCLUDED in export for Eval: None
INFO:tensorflow:No assets to save.
INFO:tensorflow:No assets to write.
INFO:tensorflow:SavedModel written to: keras_export/1553710367/saved_model.pb
Model exported to:  b'keras_export/1553710367'

필요한 권한이 있는 저장된 모델 디렉터리 한 개를 로컬 파일 시스템 또는 Cloud Storage에 내보낼 수 있습니다. 현재 환경에서 Google Cloud 계정을 인증하고 GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 설정하여 Cloud Storage에 대한 액세스 권한을 부여했습니다. AI Platform 서비스 계정은 자신의 프로젝트에 있는 Cloud Storage 버킷에 액세스할 수 있으므로 AI Platform 학습 작업도 Cloud Storage로 직접 내보낼 수 있습니다.

Cloud Storage로 직접 내보내 보세요.

JOB_DIR = os.getenv('JOB_DIR')

# Export the model to a SavedModel directory in Cloud Storage
export_path = tf.contrib.saved_model.save_keras_model(keras_model, JOB_DIR + '/keras_export')
print("Model exported to: ", export_path)
WARNING:tensorflow:This model was compiled with a Keras optimizer (<tensorflow.python.keras.optimizers.RMSprop object at 0x7fc198c4e400>) but is being saved in TensorFlow format with `save_weights`. The model's weights will be saved, but unlike with TensorFlow optimizers in the TensorFlow format the optimizer's state will not be saved.

Consider using a TensorFlow optimizer from `tf.train`.
WARNING:tensorflow:Model was compiled with an optimizer, but the optimizer is not from `tf.train` (e.g. `tf.train.AdagradOptimizer`). Only the serving graph was exported. The train and evaluate graphs were not added to the SavedModel.
INFO:tensorflow:Signatures INCLUDED in export for Classify: None
INFO:tensorflow:Signatures INCLUDED in export for Regress: None
INFO:tensorflow:Signatures INCLUDED in export for Predict: ['serving_default']
INFO:tensorflow:Signatures INCLUDED in export for Train: None
INFO:tensorflow:Signatures INCLUDED in export for Eval: None
INFO:tensorflow:No assets to save.
INFO:tensorflow:No assets to write.
INFO:tensorflow:SavedModel written to: gs://your-bucket-name/keras-job-dir/keras_export/1553710379/saved_model.pb
Model exported to:  b'gs://your-bucket-name/keras-job-dir/keras_export/1553710379'

이제 빠른 시작: 예측 단계에 따라 이 모델을 AI Platform에 배포하고 예측을 제공할 수 있습니다.

삭제

이 프로젝트에 사용된 모든 Google Cloud 리소스를 삭제하려면 이 가이드에서 사용한 Google Cloud 프로젝트를 삭제하면 됩니다.

또는 다음 명령어를 실행하여 개별 리소스를 삭제할 수 있습니다.

# Delete model version resource
gcloud ai-platform versions delete $MODEL_VERSION --quiet --model $MODEL_NAME

# Delete model resource
gcloud ai-platform models delete $MODEL_NAME --quiet

# Delete Cloud Storage objects that were created
gsutil -m rm -r $JOB_DIR

# If training job is still running, cancel it
gcloud ai-platform jobs cancel $JOB_NAME --quiet

Cloud Storage 버킷에 다른 객체가 포함되어 있지 않고 버킷을 삭제하려는 경우에는 gsutil rm -r gs://$BUCKET_NAME을 실행합니다.

다음 단계

  • 커스텀 초매개변수를 명령줄 플래그로 허용하는 코드를 구성하는 데 사용된 이 가이드의 전체 학습 코드 보기
  • AI Platform 학습 작업에 사용할 수 있는 패키징 코드 알아보기
  • 예측 제공 모델 배포 알아보기