Files
aws--amazon-sagemaker-examples/frameworks/tensorflow/get_started_mnist_train.ipynb
T
Hongshan Li 0abd786f22 MNIST offline mode with MXNet/PyTorch/TensorFlow (#1787)
* mnist train and test notebooks tested on local mode

* added config.json for global config

* training notebook requires user to be in the same region as the public s3 bucket

* default to non-local mode

* Website preview (#1764)

* mnist train and test notebooks tested on local mode

* added config.json for global config

* training notebook requires user to be in the same region as the public s3 bucket

* default to non-local mode

* cleared output / added sym link to global config.json

* minor fix

* added swp file to gitignore;

* added updated mxnet examples

* train entry point tested

* train notebook ready

* train / inference tested

* inference.py not needed

* removed zombie cells / changed public model addr

* cleared outputs

* default to non-local mode

* default to non-local mode

* removed downloaded model

* default to nonlocal mode

* small bug fix

* Pytorch vpc (#1780)

* deleted training notebook

* train / deployment notebook tested in local mode

* default to non-local mode

* added utils

* changed rst

* removed a trained model

* Website preview (#1785)

* Notebook cleaned and data on S3 - XGBoost (#1713)

* Notebook cleaned and data on S3

* Cleared all cell outputs

* formatting a cell

* PR comments addressed

* PR comments addressed

* Instance type updated

* Bucket changed to prod regions bucket and citation added

* Deleted install instructions

* Cleaned up Linear Learner notebook (#1709)

* Cleaned up Linear Learner notebook

* directory name changed on S3

* PR comments addressed

* Updated instance type and kernel

* Bucket changed to prod bucket and citation added

* Changed parameter name as in SageMaker v2

* Update introduction_to_amazon_algorithms/linear_learner_abalone/Linear_Learner_Regression_csv_format.ipynb

Co-authored-by: Aaron Markham <markhama@amazon.com>

* Update introduction_to_amazon_algorithms/linear_learner_abalone/Linear_Learner_Regression_csv_format.ipynb

Co-authored-by: Aaron Markham <markhama@amazon.com>

* Update introduction_to_amazon_algorithms/linear_learner_abalone/Linear_Learner_Regression_csv_format.ipynb

Co-authored-by: Aaron Markham <markhama@amazon.com>

* Update introduction_to_amazon_algorithms/linear_learner_abalone/Linear_Learner_Regression_csv_format.ipynb

Co-authored-by: Aaron Markham <markhama@amazon.com>

* Update introduction_to_amazon_algorithms/linear_learner_abalone/Linear_Learner_Regression_csv_format.ipynb

Co-authored-by: Aaron Markham <markhama@amazon.com>

* Update introduction_to_amazon_algorithms/linear_learner_abalone/Linear_Learner_Regression_csv_format.ipynb

Co-authored-by: Aaron Markham <markhama@amazon.com>

Co-authored-by: Aaron Markham <markhama@amazon.com>

* Image classification notebook fix + data source on S3 (#1700)

* Fixing notebooks

* Cleared all outputs

* PR comments addressed and code cleaned

* Typo fix

* Added kernel type in description

* Fixed instance type to studio

* Added instance type

* Data bucket changed to prod bucket

* Download links added

* estimator parameter changed to be compatible with SageMaker v2

* Update introduction_to_amazon_algorithms/imageclassification_caltech/Image-classification-transfer-learning-highlevel.ipynb

Co-authored-by: Aaron Markham <markhama@amazon.com>

Co-authored-by: Aaron Markham <markhama@amazon.com>

* Small fix, notebook formatting, data on S3 - PCA (#1715)

* Small fix and notebook formatting

* Variable name changed

* Updated instance type and kernel

* Bucket changed to prod bucket

* Changed parameter name in Estimator as in SageMaker v2

* Added missing import

Co-authored-by: Aaron Markham <markhama@amazon.com>

* website: add getting started videos; rename featured examples to studio (#1758)

* add getting started videos; rename featured examples to studio

* vidoes for getting started; combine to same page

* refactor byo algo with pipe mode to be python3 and sdk v2 (#1690)

* Docs: Deleting working_with_redshift_data.ipynb

New notebook will cover this topic in more depth. Deleting to remove duplication. https://github.com/aws/amazon-sagemaker-examples/issues/1447

* add GT video, fix links, update copyright notice (#1763)

* train entry point tested

* train notebook ready

* train / inference tested

* inference.py not needed

* default to non-local mode

* default to non-local mode

* removed downloaded model

* removed a trained model

Co-authored-by: vivekmadan2 <53404938+vivekmadan2@users.noreply.github.com>
Co-authored-by: Aaron Markham <markhama@amazon.com>
Co-authored-by: Talia <31782251+TEChopra1000@users.noreply.github.com>

* add a line break

* editorial fix par style guide

* removed swp file

* fix json

* fixed typos

* bug fix

* better way to upload data

* deleted empty cell

* tensorflow / pytorch tested

* removed mxnet for more testing

* cleared output

* removed mxnet from rst

* minor fixes

Co-authored-by: vivekmadan2 <53404938+vivekmadan2@users.noreply.github.com>
Co-authored-by: Aaron Markham <markhama@amazon.com>
Co-authored-by: Talia <31782251+TEChopra1000@users.noreply.github.com>
2020-11-24 00:33:47 -08:00

388 lines
13 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Training a Tensorflow Model on MNIST\n",
"\n",
"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"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import json\n",
"\n",
"import sagemaker\n",
"from sagemaker.tensorflow import TensorFlow\n",
"from sagemaker import get_execution_role\n",
"\n",
"sess = sagemaker.Session()\n",
"\n",
"role = get_execution_role()\n",
"\n",
"output_path='s3://' + sess.default_bucket() + '/tensorflow/mnist'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## TensorFlow Estimator\n",
"\n",
"The `TensorFlow` class allows you to run your training script on SageMaker\n",
"infrastracture in a containerized environment. In this notebook, we\n",
"refer to this container as *training container*. \n",
"\n",
"You need to configure\n",
"it with the following parameters to set up the environment:\n",
"\n",
"- entry_point: A user defined python file to be used by the training container as the \n",
"instructions for training. We will further discuss this file in the next subsection\n",
"\n",
"- role: An IAM role to make AWS service requests\n",
"\n",
"- instance_type: The type of SageMaker instance to run your training script. \n",
"Set it to `local` if you want to run the training job on \n",
"the SageMaker instance you are using to run this notebook\n",
"\n",
"- model_dir: S3 bucket URI where the checkpoint data and models can be exported to during training (default: None). \n",
"To disable having model_dir passed to your training script, set `model_dir`=False\n",
"\n",
"- instance count: The number of instances you need to run your training job. \n",
"Multiple instances are needed for distributed training\n",
"\n",
"- output_path: \n",
"S3 bucket URI to save training output (model artifacts and output files)\n",
"\n",
"- framework_version: The version of TensorFlow you need to use.\n",
"\n",
"- py_version: The python version you need to use\n",
"\n",
"For more information, see [the API reference](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.EstimatorBase)\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Implement the entry point for training\n",
"\n",
"The entry point for training is a python script that provides all \n",
"the code for training a TensorFlow model. It is used by the SageMaker \n",
"TensorFlow Estimator (`TensorFlow` class above) as the entry point for running the training job.\n",
"\n",
"Under the hood, SageMaker TensorFlow Estimator downloads a docker image\n",
"with runtime environemnts \n",
"specified by the parameters you used to initiated the\n",
"estimator class and it injects the training script into the \n",
"docker image to be used as the entry point to run the container.\n",
"\n",
"In the rest of the notebook, we use *training image* to refer to the \n",
"docker image specified by the TensorFlow Estimator and *training container*\n",
"to refer to the container that runs the training image. \n",
"\n",
"This means your training script is very similar to a training script\n",
"you might run outside Amazon SageMaker, but it can access the useful environment \n",
"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",
"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",
"description of all environment variables your training script\n",
"can access to. \n",
"\n",
"In this example, we use the training script `code/train.py`\n",
"as the entry point for our TensorFlow Estimator. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pygmentize 'code/train.py'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Set hyperparameters\n",
"\n",
"In addition, TensorFlow estimator allows you to parse command line arguments\n",
"to your training script via `hyperparameters`.\n",
"\n",
"<span style=\"color:red\"> Note: local mode is not supported in SageMaker Studio. </span>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# set local_mode to be True if you want to run the training script\n",
"# on the machine that runs this notebook\n",
"\n",
"local_mode=True\n",
"\n",
"if local_mode:\n",
" instance_type='local'\n",
"else:\n",
" instance_type='ml.c4.xlarge'\n",
" \n",
"est = TensorFlow(\n",
" entry_point='train.py',\n",
" source_dir='code', # directory of your training script\n",
" role=role,\n",
" framework_version='2.3.0',\n",
" model_dir=False, # don't pass --model_dir to your training script\n",
" py_version='py37',\n",
" instance_type=instance_type,\n",
" instance_count=1,\n",
" output_path=output_path,\n",
" hyperparameters={\n",
" 'batch-size':512,\n",
" 'epochs':10,\n",
" 'learning-rate': 1e-3,\n",
" 'beta_1' : 0.9,\n",
" 'beta_2' : 0.999\n",
" \n",
" }\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The training container executes your training script like\n",
"\n",
"```\n",
"python train.py --batch-size 32 --epochs 10 --learning-rate 0.001\n",
" --beta_1 0.9 --beta_2 0.999\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Set up channels for training and testing data\n",
"\n",
"You need to tell `TensorFlow` estimator where to find your training and \n",
"testing data. It can be a link to an S3 bucket or it can be a path\n",
"in your local file system if you use local mode. In this example,\n",
"we download the MNIST data from a public S3 bucket and upload it \n",
"to your default bucket. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import logging\n",
"import boto3\n",
"from botocore.exceptions import ClientError\n",
"# Download training and testing data from a public S3 bucket\n",
"\n",
"def download_from_s3(data_dir='/tmp/data', train=True):\n",
" \"\"\"Download MNIST dataset and convert it to numpy array\n",
" \n",
" Args:\n",
" data_dir (str): directory to save the data\n",
" train (bool): download training set\n",
" \n",
" Returns:\n",
" None\n",
" \"\"\"\n",
" \n",
" if not os.path.exists(data_dir):\n",
" os.makedirs(data_dir)\n",
" \n",
" if train:\n",
" images_file = \"train-images-idx3-ubyte.gz\"\n",
" labels_file = \"train-labels-idx1-ubyte.gz\"\n",
" else:\n",
" images_file = \"t10k-images-idx3-ubyte.gz\"\n",
" labels_file = \"t10k-labels-idx1-ubyte.gz\"\n",
" \n",
" with open('code/config.json', 'r') as f:\n",
" config = json.load(f)\n",
"\n",
" # download objects\n",
" s3 = boto3.client('s3')\n",
" bucket = config['public_bucket']\n",
" for obj in [images_file, labels_file]:\n",
" key = os.path.join(\"datasets/image/MNIST\", obj)\n",
" dest = os.path.join(data_dir, obj)\n",
" if not os.path.exists(dest):\n",
" s3.download_file(bucket, key, dest)\n",
" return\n",
"\n",
"\n",
"download_from_s3('/tmp/data', True)\n",
"download_from_s3('/tmp/data', False)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# upload to the default bucket\n",
"\n",
"prefix = 'mnist'\n",
"bucket = sess.default_bucket()\n",
"loc = sess.upload_data(path='/tmp/data', bucket=bucket, key_prefix=prefix)\n",
"\n",
"channels = {\n",
" \"training\": loc,\n",
" \"testing\": loc\n",
"}\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The keys of the dictionary `channels` are parsed to the training image\n",
"and it creates the environment variable `SM_CHANNEL_<key name>`. \n",
"\n",
"In this example, `SM_CHANNEL_TRAINING` and `SM_CHANNEL_TESTING` are created in the training image (checkout \n",
"how `code/train.py` access these variables). For more information,\n",
"see: [SM_CHANNEL_{channel_name}](https://github.com/aws/sagemaker-training-toolkit/blob/master/ENVIRONMENT_VARIABLES.md#sm_channel_channel_name)\n",
"\n",
"If you want, you can create a channel for validation:\n",
"```\n",
"channels = {\n",
" 'training': train_data_loc,\n",
" 'validation': val_data_loc,\n",
" 'test': test_data_loc\n",
" }\n",
"```\n",
"You can then access this channel within your training script via\n",
"`SM_CHANNEL_VALIDATION`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Run the training script on SageMaker\n",
"Now, the training container has everything to execute your training\n",
"script. You can start the container by calling `fit` method."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"est.fit(inputs=channels)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Inspect and store model data\n",
"\n",
"Now, the training is finished, the model artifact has been saved in \n",
"the `output_path`. We "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tf_mnist_model_data = est.model_data\n",
"print(\"Model artifact saved at:\\n\", tf_mnist_model_data)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will store the variable `model_data` in the current notebook kernel. \n",
"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",
"endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%store tf_mnist_model_data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Test and debug the entry point before executing the training container\n",
"\n",
"The entry point `code/train.py` provided here has been tested and it can be executed in the training container. \n",
"When you develop your own training script, it is a good practice to simulate the container environment \n",
"in the local shell and test it before sending it to SageMaker, because debugging in a containerized environment\n",
"is rather cumbersome. The following script shows how you can test your training script:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pygmentize code/test_train.py"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In [the next notebook](get_started_mnist_deploy.ipynb) you will see how to deploy your \n",
"trained model artifacts to a SageMaker endpoint. "
]
}
],
"metadata": {
"instance_type": "ml.t3.medium",
"kernelspec": {
"display_name": "Python 3 (Data Science)",
"language": "python",
"name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-west-2:236514542706:image/datascience-1.0"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.6"
},
"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."
},
"nbformat": 4,
"nbformat_minor": 4
}