정리 블록 #}을 표시하려면 1로 설정합니다
이 튜토리얼은 Cloud TPU에서 Inception 모델을 학습시키는 방법을 설명합니다.
면책조항
이 튜토리얼은 제3자 데이터 세트를 사용합니다. Google은 이 데이터 세트의 유효성을 비롯한 그 어떤 특성에 대한 진술, 보증 또는 기타 보장을 제공하지 않습니다.
모델 설명
Inception v3은 영상 인식 모델로서 높은 정확성을 달성할 수 있습니다. 이 모델은 장기간 수많은 연구에서 나온 다양한 아이디어가 축적된 결과입니다. 이 내용은 세게디 외 여러 저자가 저술한 'Rethinking the Inception Architecture for Computer Vision'이라는 원본 논문을 토대로 작성되었습니다.
모델은 다음을 비롯한 대칭 및 비대칭 구성 요소의 조합으로 이루어져 있습니다.
- 컨볼루션
- 평균 풀링
- 최대 풀링
- 이어붙이기
- 드롭아웃
- 완전 연결형 레이어
손실은 소프트맥스를 통해 계산됩니다.
다음 그림에서 이 모델을 대략적으로 볼 수 있습니다.
GitHub에서 이 모델에 관한 자세한 정보를 확인할 수 있습니다.
이 모델은 Estimator API를 사용하여 설계되었습니다.
이 API는 가장 낮은 수준의 함수를 캡슐화하여 모델 생성을 크게 간소화합니다. 따라서 사용자는 실행 기반이 되는 하드웨어의 내부 작동에 신경 쓸 필요 없이 모델 개발에 집중할 수 있습니다.
목표
- 데이터 세트와 모델 출력을 저장할 Cloud Storage 버킷 만들기
- 학습 작업 실행
- 출력 결과 확인
비용
이 문서에서는 비용이 청구될 수 있는 다음과 같은 Google Cloud 구성요소를 사용합니다.
- Compute Engine
- Cloud TPU
- Cloud Storage
프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용하세요.
시작하기 전에
이 튜토리얼을 시작하기 전에 Google Cloud 프로젝트가 올바르게 설정되었는지 확인하세요.
- Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
-
Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.
-
Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.
이 둘러보기에서는 비용이 청구될 수 있는 Google Cloud 구성요소를 사용합니다. 예상 비용은 Cloud TPU 가격 책정 페이지를 참조하세요. 리소스 사용을 마친 후에는 생성한 리소스를 삭제해야 불필요한 비용이 청구되지 않습니다.
리소스 설정
이 섹션에서는 튜토리얼에 사용할 Cloud Storage, VM, Cloud TPU 리소스를 설정하는 방법을 설명합니다.
Cloud Shell 창을 엽니다.
프로젝트 ID의 변수를 만듭니다.
export PROJECT_ID=project-id
Cloud TPU를 만들려는 프로젝트를 사용하도록 Google Cloud CLI를 구성합니다.
gcloud config set project ${PROJECT_ID}
새 Cloud Shell VM에서 이 명령어를 처음 실행하면
Authorize Cloud Shell
페이지가 표시됩니다. 페이지 하단에 있는Authorize
를 클릭하여gcloud
에서 사용자 인증 정보로 Google Cloud API를 호출하도록 허용합니다.Cloud TPU 프로젝트의 서비스 계정을 만듭니다.
gcloud beta services identity create --service tpu.googleapis.com --project $PROJECT_ID
이 명령어는 다음 형식의 Cloud TPU 서비스 계정을 반환합니다.
service-PROJECT_NUMBER@cloud-tpu.iam.gserviceaccount.com
다음 명령어를 사용하여 Cloud Storage 버킷을 만듭니다. bucket-name을 버킷 이름으로 바꿉니다.
gsutil mb -p ${PROJECT_ID} -c standard -l us-central1 -b on gs://bucket-name
Cloud Storage 버킷은 사용자가 모델 및 학습 결과를 학습시키기 위해 사용하는 데이터를 저장합니다.
ctpu up
도구는 Cloud TPU 서비스 계정에 대한 기본 권한을 설정합니다. 권한을 더 세분화해야 하는 경우 액세스 수준 권한을 참조하세요.버킷 위치는 가상 머신(VM) 및 TPU 노드와 동일한 리전에 있어야 합니다. VM 및 TPU 노드는 리전 내 구획인 특정 영역에 있습니다.
ctpu up
명령어를 사용하여 Compute Engine 리소스를 시작합니다.ctpu up --project=${PROJECT_ID} \ --zone=us-central1-b \ --vm-only \ --machine-type=n1-standard-8 \ --tf-version=2.9.1 \ --name=inception-tutorial
명령어 플래그 설명
CTPU 유틸리티에 대한 자세한 내용은 CTPU 참조를 확인하세요.
프롬프트가 표시되면 y를 눌러서 Cloud TPU 리소스를 만듭니다.
Compute Engine VM에 로그인했는지 확인하려면 셸 프롬프트가
username@projectname
에서username@vm-name
으로 변경되어야 합니다. Compute Engine 인스턴스에 연결되어 있지 않으면 다음 명령어를 실행하여 수행할 수 있습니다.gcloud compute ssh inception-tutorial --zone=us-central1-b
여기에서
(vm)$
프리픽스는 Compute Engine VM 인스턴스에서 명령어를 실행해야 한다는 의미입니다.저장소 버킷의 환경 변수를 만듭니다. bucket-name을 Cloud Storage 버킷 이름으로 바꿉니다.
(vm)$ export STORAGE_BUCKET=gs://bucket-name
TPU 이름의 환경 변수를 만듭니다.
(vm)$ export TPU_NAME=inception-tutorial
학습 데이터 세트
학습 애플리케이션을 사용하려면 Cloud Storage에서 학습 데이터에 액세스할 수 있어야 합니다. 학습 애플리케이션 역시 학습 도중 Cloud Storage 버킷을 사용하여 체크포인트를 저장합니다.
ImageNet은 이미지 데이터베이스입니다. 이 데이터베이스의 이미지는 계층 구조로 구성되며, 계층 구조의 각 노드는 수백 또는 수천 개의 이미지로 표현됩니다.
이 튜토리얼에서는 fake_imagenet 데이터 세트라는 전체 ImageNet 데이터세트의 데모 버전을 사용합니다. 이 데이터 세트를 사용하면 전체 ImageNet 데이터베이스를 다운로드하고 모델을 실행하는 데 필요한 스토리지 또는 시간을 들이지 않고 튜토리얼을 테스트할 수 있습니다. 전체 ImageNet 데이터 세트를 대신 사용해도 됩니다.
DATA_DIR
환경 변수는 학습시킬 데이터 세트를 지정하는 데 사용됩니다.
fake_imagenet 데이터 세트는 Cloud TPU 사용 방법을 이해하는 데만 유용합니다. 정확성 숫자와 저장된 모델은 의미가 없습니다.
fake_imagenet 데이터 세트는 Cloud Storage의 다음 위치에 있습니다.
gs://cloud-tpu-test-datasets/fake_imagenet
(선택사항) 텐서보드 설정
텐서보드는 TensorFlow 데이터를 시각적으로 표현하도록 설계된 도구 모음을 제공합니다. 텐서보드를 모니터링에 사용하면 처리 시 병목현상을 식별할 수 있으며 성능을 향상시킬 수 있습니다.
모델 출력을 모니터링할 필요가 없으면 텐서보드 설정 단계를 건너뛸 수 있습니다.
모델의 출력과 성능을 모니터링하려면 가이드를 따라 텐서보드를 설정합니다.
모델 실행
이제 ImageNet 데이터를 사용하여 Inception v3 모델에 대한 학습 및 평가 작업을 수행할 준비가 되었습니다.
Inception v3 모델은 Compute Engine VM의 /usr/share/tpu/models/experimental/inception/
디렉터리에 사전 설치됩니다.
다음 단계에서 프리픽스 (vm)$
는 Compute Engine VM에서 명령어를 실행해야 한다는 의미입니다.
다음 값 중 하나가 포함된
DATA_DIR
환경 변수를 설정합니다.fake_imagenet 데이터 세트를 사용하는 경우:
(vm)$ export DATA_DIR=gs://cloud-tpu-test-datasets/fake_imagenet
Cloud Storage 버킷에 학습 데이터 세트를 업로드한 경우:
(vm)$ export DATA_DIR=${STORAGE_BUCKET}/data
Inception v3 모델을 실행합니다.
(vm)$ python /usr/share/tpu/models/experimental/inception/inception_v3.py \ --tpu=$TPU_NAME \ --learning_rate=0.165 \ --train_steps=250000 \ --iterations=500 \ --use_tpu=True \ --use_data=real \ --mode=train_and_eval \ --train_steps_per_eval=2000 \ --data_dir=${DATA_DIR} \ --model_dir=${STORAGE_BUCKET}/inception
--tpu
는 Cloud TPU의 이름을 지정합니다.ctpu
는 이 이름을 Compute Engine VM에 환경 변수(TPU_NAME
)로 전달합니다.--use_data
는 학습 중에 프로그램에서 사용해야 하는 데이터 유형을 fake 또는 real 중에서 지정합니다. 기본값은 fake입니다.--data_dir
은 학습 입력을 위한 Cloud Storage 경로를 지정합니다. fake_imagenet 데이터를 사용하는 경우 이 매개변수는 무시됩니다.--model_dir
은 모델 학습 중에 체크포인트와 요약이 저장되는 디렉터리를 지정합니다. 폴더가 없는 경우에는 프로그램에서 하나 만듭니다. Cloud TPU를 사용하는 경우model_dir
는 Cloud Storage 경로(gs://...
)여야 합니다. 폴더를 다시 사용하여 현재 체크포인트 데이터를 로드하고 추가 체크포인트를 저장할 수 있습니다. 체크포인트를 작성하고 로드하려면 동일한 TensorFlow 버전을 사용해야 합니다.
예상 결과
Inception v3은 299x299 이미지에서 작동합니다. 기본 학습 배치 크기는 1,024로서 각 반복이 1,024개의 이미지에서 이루어진다는 의미입니다.
--mode
플래그를 사용하여 train, eval, train_and_eval의 세 가지 작업 모드 중 하나를 선택할 수 있습니다.
--mode=train
또는--mode=eval
은 학습 전용 또는 평가 전용 작업 중 하나를 지정합니다.--mode=train_and_eval
은 학습과 평가를 모두 수행하는 하이브리드 작업을 지정합니다.
학습 전용 작업은 train_steps
에 정의된 특정 단계 수만큼 실행되며 원하는 경우 전체 학습 세트를 진행할 수 있습니다.
Train_and_eval 작업은 학습과 평가 과정을 계속 순환합니다. 각 학습 주기는 train_steps_per_eval
동안 실행되고 평가 작업이 이어집니다(해당 지점까지 학습된 가중치 사용).
train_steps
의 floor 함수를 train_steps_per_eval
로 나눈 값을 사용하여 학습 주기 수를 계산할 수 있습니다.
floor(train_steps / train_steps_per_eval)
기본적으로 Estimator API 기반 모델은 일정 개수의 단계마다 손실 값을 보고합니다. 보고 형식은 step = 15440, loss = 12.6237
과 같습니다.
논의: 모델에 대한 TPU별 수정
TPU에 사용할 수 있는 Estimator API 기반 모델을 가져오기 위한 수정 작업은 의외로 간단합니다. 프로그램은 다음과 같은 라이브러리를 가져옵니다.
from google.third_party.tensorflow.contrib.tpu.python.tpu import tpu_config
from google.third_party.tensorflow.contrib.tpu.python.tpu import tpu_estimator
from google.third_party.tensorflow.contrib.tpu.python.tpu import tpu_optimizer
CrossShardOptimizer 함수는 다음과 같이 옵티마이저를 래핑합니다.
if FLAGS.use_tpu:
optimizer = tpu_optimizer.CrossShardOptimizer(optimizer)
모델을 정의하는 함수는 다음을 사용하여 에스티메이터 사양을 반환합니다.return tpu_estimator.TPUEstimatorSpec(
mode=mode, loss=loss, train_op=train_op, eval_metrics=eval_metrics)
기본 함수는 다음을 사용하여 에스티메이터 호환 구성을 정의합니다.
run_config = tpu_config.RunConfig(
master=tpu_grpc_url,
evaluation_master=tpu_grpc_url,
model_dir=FLAGS.model_dir,
save_checkpoints_secs=FLAGS.save_checkpoints_secs,
save_summary_steps=FLAGS.save_summary_steps,
session_config=tf.ConfigProto(
allow_soft_placement=True,
log_device_placement=FLAGS.log_device_placement),
tpu_config=tpu_config.TPUConfig(
iterations_per_loop=iterations,
num_shards=FLAGS.num_shards,
per_host_input_for_training=per_host_input_for_training))
프로그램은 다음과 같이 정의된 구성 및 모델 정의 함수를 사용하여 에스티메이터 객체를 생성합니다.
inception_classifier = tpu_estimator.TPUEstimator(
model_fn=inception_model_fn,
use_tpu=FLAGS.use_tpu,
config=run_config,
params=params,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=eval_batch_size,
batch_axis=(batch_axis, 0))
학습 전용 작업은 학습 함수만 호출하면 됩니다.
inception_classifier.train(
input_fn=imagenet_train.input_fn, steps=FLAGS.train_steps)
평가 전용 작업은 사용 가능한 체크포인트에서 데이터를 가져오고 새로운 체크포인트가 사용 가능해질 때까지 대기합니다.
for checkpoint in get_next_checkpoint():
eval_results = inception_classifier.evaluate(
input_fn=imagenet_eval.input_fn,
steps=eval_steps,
hooks=eval_hooks,
checkpoint_path=checkpoint)
train_and_eval
옵션을 선택하면 학습 및 평가 작업이 동시에 실행됩니다. 평가 중에 학습 가능한 변수가 사용 가능한 최신 체크포인트에서 로드됩니다. 학습 및 평가 주기는 다음 플래그에 지정한 대로 반복됩니다.
for cycle in range(FLAGS.train_steps // FLAGS.train_steps_per_eval):
inception_classifier.train(
input_fn=imagenet_train.input_fn, steps=FLAGS.train_steps_per_eval)
eval_results = inception_classifier.evaluate(
input_fn=imagenet_eval.input_fn, steps=eval_steps, hooks=eval_hooks)
If you used the fake\_imagenet dataset to train the model, proceed to
[clean up](#clean-up).
## Using the full Imagenet dataset {: #full-dataset }
The ImageNet dataset consists of three parts, training data, validation data,
and image labels.
The training data contains 1000 categories and 1.2 million images, packaged for
easy downloading. The validation and test data are not contained in the ImageNet
training data (duplicates have been removed).
The validation and test data consists of 150,000 photographs, collected from
[Flickr](https://www.flickr.com/) and other search engines, hand labeled with
the presence or absence of 1000 object categories. The 1000 object categories
contain both internal nodes and leaf nodes of ImageNet, but do not overlap with
each other. A random subset of 50,000 of the images with labels has been
released as validation data along with a list of the 1000 categories. The
remaining images are used for evaluation and have been released without labels.
### Steps to pre-processing the full ImageNet dataset
There are five steps to preparing the full ImageNet dataset for use by a Machine
Learning model:
1. Verify that you have space on the download target.
1. Set up the target directories.
1. Register on the ImageNet site and request download permission.
1. Download the dataset to local disk or Compute Engine VM.
Note: Downloading the Imagenet dataset to a Compute Engine VM takes
considerably longer than downloading to your local machine (approximately 40
hours versus 7 hours). If you download the dataset to your local
machine, you must copy the files to a Compute Engine VM to pre-process them.
You must then upload the files to Cloud Storage before using them to train
your model. Copying the training and validation files from your local machine to the VM
takes about 13 hours. The recommended approach is to download the dataset to
a VM.
1. Run the pre-processing and upload script.
### Verify space requirements
Whether you download the dataset to your local machine or to a Compute Engine
VM, you need about 300GB of space available on the download target. On a VM, you
can check your available storage with the `df -ha` command.
Note: If you use `gcloud compute` to set up your VM, it will allocate 250 GB by
default.
You can increase the size of the VM disk using one of the following methods:
* Specify the `--disk-size` flag on the `gcloud compute` command line with the
size, in GB, that you want allocated.
* Follow the Compute Engine guide to [add a disk][add-disk] to your
VM.
* Set **When deleting instance** to **Delete disk** to ensure that the
disk is removed when you remove the VM.
* Make a note of the path to your new disk. For example: `/mnt/disks/mnt-dir`.
### Set up the target directories
On your local machine or Compute Engine VM, set up the directory structure to
store the downloaded data.
* Create and export a home directory for the ImageNet dataset.
Create a directory, for example, `imagenet` under your home directory on
your local machine or VM. Under this directory, create two sub directories:
`train` and `validation`. Export the home directory as IMAGENET_HOME:
<pre class="prettyprint lang-sh tat-dataset">
export IMAGENET_HOME=~/imagenet
</pre>
### Register and request permission to download the dataset
* Register on the [Imagenet website](http://image-net.org/). You cannot
download the dataset until ImageNet confirms your registration and sends you
a confirmation email. If you do not get the confirmation email within a
couple of days, contact [ImageNet support](mailto:support@image-net.org) to
see why your registration has not been confirmed. Once your registration is
confirmed, you can download the dataset. The Cloud TPU tutorials that use the
ImageNet dataset use the images from the ImageNet Large Scale Visual
Recognition Challenge 2012 (ILSVRC2012).
### Download the ImageNet dataset
1. From the [LSRVC 2012 download site](https://image-net.org/challenges/LSVRC/2012/2012-downloads.php),
go to the Images section on the page and right-click
"Training images (Task 1 & 2)". The URL to download
the largest part of the training set. Save the URL.
Right-click "Training images (Task 3)" to get the URL for the second
training set. Save the URL.
Right-click "Validation images (all tasks)" to get the URL for the
validation dataset. Save the URL.
If you download the ImageNet files to your local machine, you need to copy
the directories on your local machine to the corresponding `$IMAGENET_HOME`
directory on your Compute Engine VM. Copying the ImageNet dataset from
local host to your VM takes approximately 13 hours.
The following command copies the files under
$IMAGENET_HOME on your local machine to <var>~/imagenet</var> on your VM (<var>username@vm-name</var>):
<pre class="prettyprint lang-sh tat-dataset">
gcloud compute scp --recurse $IMAGENET_HOME <var>username@vm-name</var>:~/imagenet
</pre>
1. From $IMAGENET_HOME, use `wget` to download the training and validation files
using the saved URLs.
The "Training images (Task 1 & 2)" file is the large training set. It is
138 GB and if you are downloading to a Compute Engine VM using the Cloud
Shell, the download takes approximately 40 hours. If the Cloud Shell loses its
connection to the VM, you can prepend `nohup` to the command or use
[screen](https://linuxize.com/post/how-to-use-linux-screen/).
<pre class="prettyprint lang-sh tat-dataset">
cd $IMAGENET_HOME \
nohup wget http://image-net.org/challenges/LSVRC/2012/dd31405981ef5f776aa17412e1f0c112/ILSVRC2012_img_train.tar
</pre>
This command downloads a large tar file: ILSVRC2012_img_train.tar.
From $IMAGENET_HOME on the VM, extract the individual training directories
into the `$IMAGENET_HOME/train` directory using the following command. The
extraction takes between 1 - 3 hours.
<pre class="prettyprint lang-sh tat-dataset">
tar xf ILSVRC2012_img_train.tar
</pre>
Extract the individual training tar files located in the $IMAGENET_HOME/train
directory, as shown in the following script:
<pre class="prettyprint lang-sh tat-dataset">
cd $IMAGENET_HOME/train
for f in *.tar; do
d=`basename $f .tar`
mkdir $d
tar xf $f -C $d
done
</pre>
Delete the tar files after you have extracted them to free up disk space.
The "Training images (Task 3)" file is 728 MB and takes just a few minutes
to download so you do not need to take precautions against losing the Cloud
Shell connection.
When you download this file, it extracts the individual training directories
into the existing `$IMAGENET_HOME/train` directory.
<pre class="prettyprint lang-sh tat-dataset">
wget http://www.image-net.org/challenges/LSVRC/2012/dd31405981ef5f776aa17412e1f0c112/ILSVRC2012_img_train_t3.tar
</pre>
When downloading the "Validation images (all tasks)" file, your Cloud Shell may disconnect.
You can use `nohup` or [screen](https://linuxize.com/post/how-to-use-linux-screen/) to
prevent Cloud Shell from disconnecting.
<pre class="prettyprint lang-sh tat-dataset">
wget http://www.image-net.org/challenges/LSVRC/2012/dd31405981ef5f776aa17412e1f0c112/ILSVRC2012_img_val.tar
</pre>
This download takes about 30 minutes. When you download this file, it
extracts the individual validation directories into the
`$IMAGENET_HOME/validation` directory.
If you downloaded the validation files to your local machine, you need to
copy the `$IMAGENET_HOME/validation` directory on your local machine to the
`$IMAGENET_HOME/validation` directory on your Compute Engine VM. This copy
operation takes about 30 minutes.
Download the labels file.
<pre class="prettyprint lang-sh tat-dataset">
wget -O $IMAGENET_HOME/synset_labels.txt \
https://raw.githubusercontent.com/tensorflow/models/master/research/inception/inception/data/imagenet_2012_validation_synset_labels.txt
</pre>
If you downloaded the labels file to your local machine, you need to copy it
to the `$IMAGENET_HOME` directory on your local machine to `$IMAGENET_HOME`
on your Compute Engine VM. This copy operation takes a few seconds.
The training subdirectory names (for example, n03062245) are "WordNet IDs"
(wnid). The [ImageNet API](https://image-net.org/download-attributes.php)
shows the mapping of WordNet IDs to their associated validation labels in the
`synset_labels.txt` file. A synset in this context is a visually similar
group of images.
### Process the Imagenet dataset and, optionally, upload to Cloud Storage
1. Download the `imagenet_to_gcs.py` script from GitHub:
<pre class="prettyprint lang-sh tat-dataset">
wget https://raw.githubusercontent.com/tensorflow/tpu/master/tools/datasets/imagenet_to_gcs.py
</pre>
1. If you are uploading the dataset to Cloud Storage, specify the storage
bucket location to upload the ImageNet dataset:
<pre class="lang-sh prettyprint tat-client-exports">
export STORAGE_BUCKET=gs://<var>bucket-name</var>
</pre>
1. If you are uploading the dataset to your local machine or VM, specify a data
directory to hold the dataset:
<pre class="lang-sh prettyprint tat-client-exports">
<span class="no-select">(vm)$ </span>export DATA_DIR=$IMAGENET_HOME/<var>dataset-directory</var>
</pre>
1. Run the script to pre-process the raw dataset as TFRecords and upload it to
Cloud Storage using the following command:
Note: If you don't want to upload to Cloud Storage, specify `--nogcs_upload`
as another parameter and leave off the `--project` and `--gcs_output_path`
parameters.
<pre class="prettypring lang-sh tat-dataset">
python3 imagenet_to_gcs.py \
--project=$PROJECT \
--gcs_output_path=$STORAGE_BUCKET \
--raw_data_dir=$IMAGENET_HOME \
--local_scratch_dir=$IMAGENET_HOME/tf_records
</pre>
Note: Downloading and preprocessing the data can take 10 or more hours,
depending on your network and computer speed. Do not interrupt the script.
The script generates a set of directories (for both training and validation) of
the form:
${DATA_DIR}/train-00000-of-01024
${DATA_DIR}/train-00001-of-01024
...
${DATA_DIR}/train-01023-of-01024
and
${DATA_DIR}/validation-00000-of-00128
S{DATA_DIR}/validation-00001-of-00128
...
${DATA_DIR}/validation-00127-of-00128
After the data has been uploaded to your Cloud bucket, run your model and set
`--data_dir=${DATA_DIR}`.
## Clean up {: #clean-up }
To avoid incurring charges to your GCP account for the resources used
in this topic:
1. Disconnect from the Compute Engine VM:
<pre class="lang-sh prettyprint tat-skip">
<span class="no-select">(vm)$ </span>exit
</pre>
Your prompt should now be `username@projectname`, showing you are in the
Cloud Shell.
1. In your Cloud Shell, run `ctpu delete` with the --zone flag you used when
you set up the Cloud TPU to delete your
Compute Engine VM and your Cloud TPU:
<pre class="lang-sh prettyprint tat-resource-setup">
<span class="no-select">$ </span>ctpu delete [optional: --zone]
</pre>
Important: If you set the TPU resources name when you ran `ctpu up`, you must
specify that name with the `--name` flag when you run `ctpu delete` in
order to shut down your TPU resources.
1. Run `ctpu status` to make sure you have no instances allocated to avoid
unnecessary charges for TPU usage. The deletion might take several minutes.
A response like the one below indicates there are no more allocated
instances:
<pre class="lang-sh prettyprint tat-skip">
<span class="no-select">$ </span>ctpu status --zone=europe-west4-a
</pre>
<pre class="lang-sh prettyprint tat-skip">
2018/04/28 16:16:23 WARNING: Setting zone to "--zone=europe-west4-a"
No instances currently exist.
Compute Engine VM: --
Cloud TPU: --
</pre>
1. Run `gsutil` as shown, replacing <var>bucket-name</var> with the name of the
Cloud Storage bucket you created for this tutorial:
<pre class="lang-sh prettyprint tat-resource-setup">
<span class="no-select">$ </span>gsutil rm -r gs://<var>bucket-name</var>
</pre>
Note: For free storage limits and other pricing information, see the
[Cloud Storage pricing guide](/storage/pricing).
## Inception v4
The Inception v4 model is a deep neural network model that uses Inception v3
building blocks to achieve higher accuracy than Inception v3. It is described in
the paper "Inception-v4, Inception-ResNet and the Impact of Residual Connections
on Learning" by Szegedy et. al.
The Inception v4 model is pre-installed on your Compute Engine VM, in
the `/usr/share/tpu/models/experimental/inception/` directory.
In the following steps, a prefix of `(vm)$` means you should run the command on
your Compute Engine VM:
1. If you have TensorBoard running in your Cloud Shell tab, you need another tab
to work in. Open another tab in your Cloud Shell, and use `ctpu` in the new
shell to connect to your Compute Engine VM:
<pre class="lang-sh prettyprint">
<span class="no-select">$ </span>ctpu up --project=${PROJECT_ID} </pre>
1. Set up a `DATA_DIR` environment variable containing one of the following
values:
* If you are using the fake\_imagenet dataset:
<pre class="prettyprint lang-sh">
<span class="no-select">(vm)$ </span>export DATA_DIR=gs://cloud-tpu-test-datasets/fake_imagenet
</pre>
* If you have uploaded a set of training data to your Cloud Storage
bucket:
<pre class="prettyprint lang-sh">
<span class="no-select">(vm)$ </span>export DATA_DIR=${STORAGE_BUCKET}/data
</pre>
1. Run the Inception v4 model:
<pre class="lang-sh prettyprint">
<span class="no-select">(vm)$ </span>python /usr/share/tpu/models/experimental/inception/inception_v4.py \
--tpu=$TPU_NAME \
--learning_rate=0.36 \
--train_steps=1000000 \
--iterations=500 \
--use_tpu=True \
--use_data=real \
--train_batch_size=256 \
--mode=train_and_eval \
--train_steps_per_eval=2000 \
--data_dir=${DATA_DIR} \
--model_dir=${STORAGE_BUCKET}/inception</pre>
* `--tpu` specifies the name of the Cloud TPU. `ctpu`
passes this name to the Compute Engine VM as an environment
variable (`TPU_NAME`).
* `--use_data` specifies which type of data the program must use during
training, either fake or real. The default value is fake.
* `--train_batch_size` specifies the train batch size to be 256. As the
Inception v4 model is larger than Inception v3, it must be run at a
smaller batch size per TPU core.
* `--data_dir` specifies the Cloud Storage path for training input.
The application ignores this parameter when you're using fake\_imagenet
data.
* `--model_dir` specifies the directory where checkpoints and
summaries are stored during model training. If the folder is missing, the
program creates one. When using a Cloud TPU, the `model_dir`
must be a Cloud Storage path (`gs://...`). You can reuse an existing
folder to load current checkpoint data and to store additional
checkpoints as long as the previous checkpoints were created using TPU of
the same size and TensorFlow version.
Clean up
What's next
## What's next {: #whats-next }
The TensorFlow Cloud TPU tutorials generally train the model using a
sample dataset. The results of this training are not usable
for inference. To use a model for inference, you can train the data on a
publicly available dataset or your own data set. TensorFlow models
trained on Cloud TPUs generally require datasets to be in
[TFRecord](https://www.tensorflow.org/tutorials/load_data/tfrecord) format.
You can use the [dataset conversion tool sample](https://cloud.google.com/tpu/docs/classification-data-conversion) to convert an image classification dataset into TFRecord format. If you are not using an image classification model, you will have to convert your dataset to [TFRecord](https://www.tensorflow.org/tutorials/load_data/tfrecord) format yourself. For more information, see [TFRecord and tf.Example](https://www.tensorflow.org/tutorials/load_data/tfrecord).
### Hyperparameter tuning
To improve the model's performance with your dataset, you can tune
the model's hyperparameters. You can find information about hyperparameters
common to all TPU supported models on [GitHub](https://github.com/tensorflow/tpu/tree/master/models/hyperparameters).
Information about model-specific hyperparameters can be found in the
[source code](https://github.com/tensorflow/tpu/tree/master/models/official)
for each model. For more information on hyperparameter tuning, see
[Overview of hyperparameter tuning](https://cloud.google.com/ai-platform/training/docs/hyperparameter-tuning-overview),
[Using the Hyperparameter tuning service](https://cloud.google.com/ai-platform/training/docs/using-hyperparameter-tuning),
and [Tune hyperparameters](https://developers.google.com/machine-learning/guides/text-classification/step-5).
### Inference
Once you have trained your model you can use it for inference
(also called prediction). [AI Platform](https://cloud.google.com/ai-platform/docs/technical-overview)
is a cloud-based solution for developing,
[training](https://cloud.google.com/ai-platform/training/docs),
and [deploying](https://cloud.google.com/ai-platform/prediction/docs/deploying-models)
machine learning models. Once a model is deployed, you can use the
[AI Platform Prediction service](https://cloud.google.com/ai-platform/prediction/docs).
* Go in depth with an [advanced view](/tpu/docs/inception-v3-advanced)
of Inception v3 on Cloud TPU.
* Learn more about
[`ctpu`](https://github.com/tensorflow/tpu/tree/master/tools/ctpu), including
how to install it on a local machine.
* Explore the [TPU tools in
TensorBoard](/tpu/docs/cloud-tpu-tools){: track-type="gettingStarted" track-name="tutorialLink" track-metadata-position="nextSteps"}.