Skip to content

Commit 1063e2f

Browse files
author
Hongshan Li
committed
resume get_started_mnist_train.ipynb from remote
1 parent efb533e commit 1063e2f

File tree

1 file changed

+387
-0
lines changed

1 file changed

+387
-0
lines changed
Lines changed: 387 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,387 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"# Training a Tensorflow Model on MNIST\n",
8+
"\n",
9+
"MNIST is a widely used dataset for handwritten digit classification. It consists of 70,000 labeled 28x28 pixel grayscale images of hand-written digits. The dataset is split into 60,000 training images and 10,000 test images. There are 10 classes (one for each of the 10 digits). This tutorial will show how to train a Tensorflow V2 model on MNIST model on SageMaker.\n"
10+
]
11+
},
12+
{
13+
"cell_type": "code",
14+
"execution_count": null,
15+
"metadata": {},
16+
"outputs": [],
17+
"source": [
18+
"import os\n",
19+
"import json\n",
20+
"\n",
21+
"import sagemaker\n",
22+
"from sagemaker.tensorflow import TensorFlow\n",
23+
"from sagemaker import get_execution_role\n",
24+
"\n",
25+
"sess = sagemaker.Session()\n",
26+
"\n",
27+
"role = get_execution_role()\n",
28+
"\n",
29+
"output_path='s3://' + sess.default_bucket() + '/tensorflow/mnist'"
30+
]
31+
},
32+
{
33+
"cell_type": "markdown",
34+
"metadata": {},
35+
"source": [
36+
"## TensorFlow Estimator\n",
37+
"\n",
38+
"The `TensorFlow` class allows you to run your training script on SageMaker\n",
39+
"infrastracture in a containerized environment. In this notebook, we\n",
40+
"refer to this container as *training container*. \n",
41+
"\n",
42+
"You need to configure\n",
43+
"it with the following parameters to set up the environment:\n",
44+
"\n",
45+
"- entry_point: A user defined python file to be used by the training container as the \n",
46+
"instructions for training. We will further discuss this file in the next subsection\n",
47+
"\n",
48+
"- role: An IAM role to make AWS service requests\n",
49+
"\n",
50+
"- instance_type: The type of SageMaker instance to run your training script. \n",
51+
"Set it to `local` if you want to run the training job on \n",
52+
"the SageMaker instance you are using to run this notebook\n",
53+
"\n",
54+
"- model_dir: S3 bucket URI where the checkpoint data and models can be exported to during training (default: None). \n",
55+
"To disable having model_dir passed to your training script, set `model_dir`=False\n",
56+
"\n",
57+
"- instance count: The number of instances you need to run your training job. \n",
58+
"Multiple instances are needed for distributed training\n",
59+
"\n",
60+
"- output_path: \n",
61+
"S3 bucket URI to save training output (model artifacts and output files)\n",
62+
"\n",
63+
"- framework_version: The version of TensorFlow you need to use.\n",
64+
"\n",
65+
"- py_version: The python version you need to use\n",
66+
"\n",
67+
"For more information, see [the API reference](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.EstimatorBase)\n",
68+
"\n"
69+
]
70+
},
71+
{
72+
"cell_type": "markdown",
73+
"metadata": {},
74+
"source": [
75+
"## Implement the entry point for training\n",
76+
"\n",
77+
"The entry point for training is a python script that provides all \n",
78+
"the code for training a TensorFlow model. It is used by the SageMaker \n",
79+
"TensorFlow Estimator (`TensorFlow` class above) as the entry point for running the training job.\n",
80+
"\n",
81+
"Under the hood, SageMaker TensorFlow Estimator downloads a docker image\n",
82+
"with runtime environemnts \n",
83+
"specified by the parameters you used to initiated the\n",
84+
"estimator class and it injects the training script into the \n",
85+
"docker image to be used as the entry point to run the container.\n",
86+
"\n",
87+
"In the rest of the notebook, we use *training image* to refer to the \n",
88+
"docker image specified by the TensorFlow Estimator and *training container*\n",
89+
"to refer to the container that runs the training image. \n",
90+
"\n",
91+
"This means your training script is very similar to a training script\n",
92+
"you might run outside Amazon SageMaker, but it can access the useful environment \n",
93+
"variables provided by the training image. Checkout [the short list of environment variables provided by the SageMaker service](https://sagemaker.readthedocs.io/en/stable/frameworks/mxnet/using_mxnet.html?highlight=entry%20point) to see some common environment \n",
94+
"variables you might used. Checkout [the complete list of environment variables](https://github.com/aws/sagemaker-training-toolkit/blob/master/ENVIRONMENT_VARIABLES.md) for a complete \n",
95+
"description of all environment variables your training script\n",
96+
"can access to. \n",
97+
"\n",
98+
"In this example, we use the training script `code/train.py`\n",
99+
"as the entry point for our TensorFlow Estimator. "
100+
]
101+
},
102+
{
103+
"cell_type": "code",
104+
"execution_count": null,
105+
"metadata": {},
106+
"outputs": [],
107+
"source": [
108+
"!pygmentize 'code/train.py'"
109+
]
110+
},
111+
{
112+
"cell_type": "markdown",
113+
"metadata": {},
114+
"source": [
115+
"### Set hyperparameters\n",
116+
"\n",
117+
"In addition, TensorFlow estimator allows you to parse command line arguments\n",
118+
"to your training script via `hyperparameters`.\n",
119+
"\n",
120+
"<span style=\"color:red\"> Note: local mode is not supported in SageMaker Studio. </span>"
121+
]
122+
},
123+
{
124+
"cell_type": "code",
125+
"execution_count": null,
126+
"metadata": {},
127+
"outputs": [],
128+
"source": [
129+
"# set local_mode to be True if you want to run the training script\n",
130+
"# on the machine that runs this notebook\n",
131+
"\n",
132+
"local_mode=True\n",
133+
"\n",
134+
"if local_mode:\n",
135+
" instance_type='local'\n",
136+
"else:\n",
137+
" instance_type='ml.c4.xlarge'\n",
138+
" \n",
139+
"est = TensorFlow(\n",
140+
" entry_point='train.py',\n",
141+
" source_dir='code', # directory of your training script\n",
142+
" role=role,\n",
143+
" framework_version='2.3.0',\n",
144+
" model_dir=False, # don't pass --model_dir to your training script\n",
145+
" py_version='py37',\n",
146+
" instance_type=instance_type,\n",
147+
" instance_count=1,\n",
148+
" output_path=output_path,\n",
149+
" hyperparameters={\n",
150+
" 'batch-size':512,\n",
151+
" 'epochs':10,\n",
152+
" 'learning-rate': 1e-3,\n",
153+
" 'beta_1' : 0.9,\n",
154+
" 'beta_2' : 0.999\n",
155+
" \n",
156+
" }\n",
157+
")\n"
158+
]
159+
},
160+
{
161+
"cell_type": "markdown",
162+
"metadata": {},
163+
"source": [
164+
"The training container executes your training script like\n",
165+
"\n",
166+
"```\n",
167+
"python train.py --batch-size 32 --epochs 10 --learning-rate 0.001\n",
168+
" --beta_1 0.9 --beta_2 0.999\n",
169+
"```"
170+
]
171+
},
172+
{
173+
"cell_type": "markdown",
174+
"metadata": {},
175+
"source": [
176+
"## Set up channels for training and testing data\n",
177+
"\n",
178+
"You need to tell `TensorFlow` estimator where to find your training and \n",
179+
"testing data. It can be a link to an S3 bucket or it can be a path\n",
180+
"in your local file system if you use local mode. In this example,\n",
181+
"we download the MNIST data from a public S3 bucket and upload it \n",
182+
"to your default bucket. "
183+
]
184+
},
185+
{
186+
"cell_type": "code",
187+
"execution_count": null,
188+
"metadata": {},
189+
"outputs": [],
190+
"source": [
191+
"import logging\n",
192+
"import boto3\n",
193+
"from botocore.exceptions import ClientError\n",
194+
"# Download training and testing data from a public S3 bucket\n",
195+
"\n",
196+
"def download_from_s3(data_dir='/tmp/data', train=True):\n",
197+
" \"\"\"Download MNIST dataset and convert it to numpy array\n",
198+
" \n",
199+
" Args:\n",
200+
" data_dir (str): directory to save the data\n",
201+
" train (bool): download training set\n",
202+
" \n",
203+
" Returns:\n",
204+
" None\n",
205+
" \"\"\"\n",
206+
" \n",
207+
" if not os.path.exists(data_dir):\n",
208+
" os.makedirs(data_dir)\n",
209+
" \n",
210+
" if train:\n",
211+
" images_file = \"train-images-idx3-ubyte.gz\"\n",
212+
" labels_file = \"train-labels-idx1-ubyte.gz\"\n",
213+
" else:\n",
214+
" images_file = \"t10k-images-idx3-ubyte.gz\"\n",
215+
" labels_file = \"t10k-labels-idx1-ubyte.gz\"\n",
216+
" \n",
217+
" with open('code/config.json', 'r') as f:\n",
218+
" config = json.load(f)\n",
219+
"\n",
220+
" # download objects\n",
221+
" s3 = boto3.client('s3')\n",
222+
" bucket = config['public_bucket']\n",
223+
" for obj in [images_file, labels_file]:\n",
224+
" key = os.path.join(\"datasets/image/MNIST\", obj)\n",
225+
" dest = os.path.join(data_dir, obj)\n",
226+
" if not os.path.exists(dest):\n",
227+
" s3.download_file(bucket, key, dest)\n",
228+
" return\n",
229+
"\n",
230+
"\n",
231+
"download_from_s3('/tmp/data', True)\n",
232+
"download_from_s3('/tmp/data', False)\n"
233+
]
234+
},
235+
{
236+
"cell_type": "code",
237+
"execution_count": null,
238+
"metadata": {},
239+
"outputs": [],
240+
"source": [
241+
"# upload to the default bucket\n",
242+
"\n",
243+
"prefix = 'mnist'\n",
244+
"bucket = sess.default_bucket()\n",
245+
"loc = sess.upload_data(path='/tmp/data', bucket=bucket, key_prefix=prefix)\n",
246+
"\n",
247+
"channels = {\n",
248+
" \"training\": loc,\n",
249+
" \"testing\": loc\n",
250+
"}\n"
251+
]
252+
},
253+
{
254+
"cell_type": "markdown",
255+
"metadata": {},
256+
"source": [
257+
"The keys of the dictionary `channels` are parsed to the training image\n",
258+
"and it creates the environment variable `SM_CHANNEL_<key name>`. \n",
259+
"\n",
260+
"In this example, `SM_CHANNEL_TRAINING` and `SM_CHANNEL_TESTING` are created in the training image (checkout \n",
261+
"how `code/train.py` access these variables). For more information,\n",
262+
"see: [SM_CHANNEL_{channel_name}](https://github.com/aws/sagemaker-training-toolkit/blob/master/ENVIRONMENT_VARIABLES.md#sm_channel_channel_name)\n",
263+
"\n",
264+
"If you want, you can create a channel for validation:\n",
265+
"```\n",
266+
"channels = {\n",
267+
" 'training': train_data_loc,\n",
268+
" 'validation': val_data_loc,\n",
269+
" 'test': test_data_loc\n",
270+
" }\n",
271+
"```\n",
272+
"You can then access this channel within your training script via\n",
273+
"`SM_CHANNEL_VALIDATION`."
274+
]
275+
},
276+
{
277+
"cell_type": "markdown",
278+
"metadata": {},
279+
"source": [
280+
"## Run the training script on SageMaker\n",
281+
"Now, the training container has everything to execute your training\n",
282+
"script. You can start the container by calling `fit` method."
283+
]
284+
},
285+
{
286+
"cell_type": "code",
287+
"execution_count": null,
288+
"metadata": {
289+
"scrolled": true
290+
},
291+
"outputs": [],
292+
"source": [
293+
"est.fit(inputs=channels)"
294+
]
295+
},
296+
{
297+
"cell_type": "markdown",
298+
"metadata": {},
299+
"source": [
300+
"## Inspect and store model data\n",
301+
"\n",
302+
"Now, the training is finished, the model artifact has been saved in \n",
303+
"the `output_path`. We "
304+
]
305+
},
306+
{
307+
"cell_type": "code",
308+
"execution_count": null,
309+
"metadata": {},
310+
"outputs": [],
311+
"source": [
312+
"tf_mnist_model_data = est.model_data\n",
313+
"print(\"Model artifact saved at:\\n\", tf_mnist_model_data)"
314+
]
315+
},
316+
{
317+
"cell_type": "markdown",
318+
"metadata": {},
319+
"source": [
320+
"We will store the variable `model_data` in the current notebook kernel. \n",
321+
"In the [next notebook](get_started_with_mnist_deploy.ipynb), you will learn how to retrieve the model artifact and deploy to a SageMaker\n",
322+
"endpoint."
323+
]
324+
},
325+
{
326+
"cell_type": "code",
327+
"execution_count": null,
328+
"metadata": {},
329+
"outputs": [],
330+
"source": [
331+
"%store tf_mnist_model_data"
332+
]
333+
},
334+
{
335+
"cell_type": "markdown",
336+
"metadata": {},
337+
"source": [
338+
"## Test and debug the entry point before executing the training container\n",
339+
"\n",
340+
"The entry point `code/train.py` provided here has been tested and it can be executed in the training container. \n",
341+
"When you develop your own training script, it is a good practice to simulate the container environment \n",
342+
"in the local shell and test it before sending it to SageMaker, because debugging in a containerized environment\n",
343+
"is rather cumbersome. The following script shows how you can test your training script:"
344+
]
345+
},
346+
{
347+
"cell_type": "code",
348+
"execution_count": null,
349+
"metadata": {},
350+
"outputs": [],
351+
"source": [
352+
"!pygmentize code/test_train.py"
353+
]
354+
},
355+
{
356+
"cell_type": "markdown",
357+
"metadata": {},
358+
"source": [
359+
"In [the next notebook](get_started_mnist_deploy.ipynb) you will see how to deploy your \n",
360+
"trained model artifacts to a SageMaker endpoint. "
361+
]
362+
}
363+
],
364+
"metadata": {
365+
"instance_type": "ml.t3.medium",
366+
"kernelspec": {
367+
"display_name": "Python 3 (Data Science)",
368+
"language": "python",
369+
"name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-west-2:236514542706:image/datascience-1.0"
370+
},
371+
"language_info": {
372+
"codemirror_mode": {
373+
"name": "ipython",
374+
"version": 3
375+
},
376+
"file_extension": ".py",
377+
"mimetype": "text/x-python",
378+
"name": "python",
379+
"nbconvert_exporter": "python",
380+
"pygments_lexer": "ipython3",
381+
"version": "3.7.6"
382+
},
383+
"notice": "Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the \"license\" file accompanying this file. This file 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."
384+
},
385+
"nbformat": 4,
386+
"nbformat_minor": 4
387+
}

0 commit comments

Comments
 (0)