Skip to content
This repository was archived by the owner on Oct 4, 2024. It is now read-only.

Commit 2c32c51

Browse files
committed
sentiment analysis notebook changes for SDK v2 etc.
1 parent 3199d6a commit 2c32c51

File tree

1 file changed

+20
-100
lines changed

1 file changed

+20
-100
lines changed

tf-sentiment-script-mode/sentiment-analysis.ipynb

Lines changed: 20 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@
66
"source": [
77
"# Sentiment Analysis with TensorFlow 2\n",
88
"\n",
9-
"Amazon SageMaker provides both built-in algorithms and an easy path to train your own custom models. Although the built-in algorithms cover many domains (computer vision, natural language processing etc.) and are easy to use (just provide your data), sometimes training a custom model is the preferred approach. This notebook will focus on training a custom model using TensorFlow 2. \n",
9+
"Amazon SageMaker provides both (1) built-in algorithms and (2) an easy path to train your own custom models. Although the built-in algorithms cover many domains (computer vision, natural language processing etc.) and are easy to use (just provide your data), sometimes training a custom model is the preferred approach. This notebook will focus on training a custom model using TensorFlow 2. \n",
1010
"\n",
11-
"Sentiment analysis is a very common text analytics task that involves determining whether a text sample is positive or negative about its subject. There are several different algorithms for performing this task, including statistical algorithms and deep learning algorithms. With respect to deep learning, a 1D Convolutional Neural Net (CNN) is sometimes used for this purpose. In this notebook we'll use a CNN built with TensorFlow 2 to perform sentiment analysis in Amazon SageMaker on the IMDB dataset, which consists of movie reviews labeled as having positive or negative sentiment. Three aspects of Amazon SageMaker will be demonstrated:\n",
11+
"Sentiment analysis is a very common text analytics task that determines whether a text sample is positive or negative about its subject. There are several different algorithms for performing this task, including older statistical algorithms and newer deep learning algorithms. With respect to deep learning, a 1D Convolutional Neural Net (CNN) is sometimes used for this purpose. In this notebook we'll use a CNN built with TensorFlow 2 to perform sentiment analysis in Amazon SageMaker on the IMDb dataset, which consists of movie reviews labeled as having positive or negative sentiment. Several aspects of Amazon SageMaker will be demonstrated:\n",
1212
"\n",
1313
"- How to use a SageMaker prebuilt TensorFlow 2 container with a custom model training script similar to one you would use outside SageMaker. This feature is known as Script Mode. \n",
14-
"- Local Mode training: this allows you to prototype and test your code on a low-cost notebook instance before creating a full scale training job on more powerful and expensive instances.\n",
15-
"- Hosted training: for full scale training on a complete dataset. \n",
16-
"- Distributed training: using a single, multi-GPU instance to speed up training. \n",
17-
"- Batch Transform for offline, asynchronous predictions on large batches of data. \n",
14+
"- Hosted training: for full scale training on a complete dataset on a separate, larger and more powerful SageMaker-managed GPU instance. \n",
15+
"- Distributed training: using multiple GPUs to speed up training. \n",
16+
"- Batch Transform: for offline, asynchronous predictions on large batches of data. \n",
17+
"- Instance type choices: many different kinds of CPU and GPU instances are available in SageMaker, and are applicable to different use cases.\n",
1818
"\n",
1919
"# Prepare the dataset\n",
2020
"\n",
@@ -54,7 +54,7 @@
5454
"cell_type": "markdown",
5555
"metadata": {},
5656
"source": [
57-
"Training data for both Local Mode training and hosted Training must be saved as files. Accordingly, we'll save the padded data to files, locally for now, and later to Amazon S3."
57+
"Next, we'll save the padded data to files, locally for now, and later to Amazon S3."
5858
]
5959
},
6060
{
@@ -86,33 +86,13 @@
8686
"cell_type": "markdown",
8787
"metadata": {},
8888
"source": [
89-
"# Local Mode Training & Git Integration\n",
89+
"# SageMaker Training\n",
9090
"\n",
91-
"Amazon SageMaker’s Local Mode training feature is a convenient way to make sure your code is working as expected before moving on to full scale, hosted training. With Local Mode, you can run quick tests with just a sample of training data, and/or a small number of epochs (passes over the full training set), while avoiding the time and expense of attempting full scale hosted training using possibly buggy code. \n",
91+
"With our dataset prepared, we're now ready to set up a SageMaker hosted training job. The core concept of SageMaker hosted training is to use more powerful compute resources separate from the less powerful, lower cost notebook instance that you use for prototyping. Hosted training spins up one or more instances (i.e. a cluster) for training, and then tears the cluster down when training is complete, with billing per second for cluster up time. In general, hosted training is preferred for doing actual large-scale training on more powerful instances, especially for distributed training on a single large instance with multiple GPUs, or multiple instances each having multiple GPUs. \n",
9292
"\n",
93-
"### Prepare for Local Mode\n",
94-
"\n",
95-
"To train in Local Mode, it is necessary to have docker-compose or nvidia-docker-compose (for GPU) installed. Running the following script will install docker-compose or nvidia-docker-compose and configure the notebook environment for you."
96-
]
97-
},
98-
{
99-
"cell_type": "code",
100-
"execution_count": null,
101-
"metadata": {},
102-
"outputs": [],
103-
"source": [
104-
"!wget -q https://raw.githubusercontent.com/aws-samples/amazon-sagemaker-script-mode/master/local_mode_setup.sh\n",
105-
"!wget -q https://raw.githubusercontent.com/aws-samples/amazon-sagemaker-script-mode/master/daemon.json \n",
106-
"!/bin/bash ./local_mode_setup.sh"
107-
]
108-
},
109-
{
110-
"cell_type": "markdown",
111-
"metadata": {},
112-
"source": [
11393
"### Git Configuration\n",
11494
"\n",
115-
"Now we need a training script that can be used to train the model in Amazon SageMaker. In this example, we'll use Git integration. That is, you can specify a training script that is stored in a GitHub, AWS CodeCommit or another Git repository as the entry point so that you don't have to download the scripts locally. If you do so, any source directory and dependencies should be in the same repo if they are needed.\n",
95+
"To begin, we need a training script that can be used to train the model in Amazon SageMaker. In this example, we'll use Git integration. That is, you can specify a training script that is stored in a GitHub, AWS CodeCommit or another Git repository as the entry point so that you don't have to download the scripts locally. For this purpose, the source directory and dependencies should be in the same repository.\n",
11696
"\n",
11797
"To use Git integration, pass a dict `git_config` as a parameter when you create an Amazon SageMaker Estimator object. In the `git_config` parameter, you specify the fields `repo`, `branch` and `commit` to locate the specific repo you want to use. If you do not specify `commit` in `git_config`, the latest commit of the specified repo and branch will be used by default. Also, if authentication is required to access the repo, you can specify fields `2FA_enabled`, `username`, `password` and `token` accordingly.\n",
11898
"\n",
@@ -133,66 +113,6 @@
133113
"cell_type": "markdown",
134114
"metadata": {},
135115
"source": [
136-
"### Local Mode Estimator setup\n",
137-
"\n",
138-
"The next step is to set up a TensorFlow Estimator for Local Mode training. The Estimator will be used to configure and start a training job. A key parameters for the Estimator is the `train_instance_type`, which is the kind of hardware on which training will run. In the case of Local Mode, we simply set this parameter to `local_gpu` to invoke Local Mode training on the GPU, or to `local` if the instance has a CPU. Other parameters of note are the algorithm’s hyperparameters, which are passed in as a dictionary, and a Boolean parameter indicating that we are using Script Mode."
139-
]
140-
},
141-
{
142-
"cell_type": "code",
143-
"execution_count": null,
144-
"metadata": {},
145-
"outputs": [],
146-
"source": [
147-
"import sagemaker\n",
148-
"from sagemaker.tensorflow import TensorFlow\n",
149-
"\n",
150-
"\n",
151-
"model_dir = '/opt/ml/model'\n",
152-
"train_instance_type = 'local'\n",
153-
"hyperparameters = {'epochs': 1, 'batch_size': 64, 'learning_rate': 0.01}\n",
154-
"local_estimator = TensorFlow(\n",
155-
" git_config=git_config,\n",
156-
" source_dir='tf-sentiment-script-mode',\n",
157-
" entry_point='sentiment.py',\n",
158-
" model_dir=model_dir,\n",
159-
" train_instance_type=train_instance_type,\n",
160-
" train_instance_count=1,\n",
161-
" hyperparameters=hyperparameters,\n",
162-
" role=sagemaker.get_execution_role(),\n",
163-
" base_job_name='tf-sentiment',\n",
164-
" framework_version='2.1',\n",
165-
" py_version='py3',\n",
166-
" script_mode=True)"
167-
]
168-
},
169-
{
170-
"cell_type": "markdown",
171-
"metadata": {},
172-
"source": [
173-
"Now we'll briefly train the model in Local Mode. Since this is just to make sure the code is working, we'll train for only one epoch. On a notebook instance using a general purpose CPU-based instance type such as m5.xlarge, this one epoch will take about 3 or 4 minutes. As you'll see from the logs below the cell when training is complete, even when trained for only one epoch, the accuracy of the model on training data is around 80%. "
174-
]
175-
},
176-
{
177-
"cell_type": "code",
178-
"execution_count": null,
179-
"metadata": {},
180-
"outputs": [],
181-
"source": [
182-
"inputs = {'train': f'file://{train_dir}',\n",
183-
" 'test': f'file://{test_dir}'}\n",
184-
"\n",
185-
"local_estimator.fit(inputs)"
186-
]
187-
},
188-
{
189-
"cell_type": "markdown",
190-
"metadata": {},
191-
"source": [
192-
"# Hosted Training\n",
193-
"\n",
194-
"After we've confirmed our code is working using Local Mode training, we can move on to use SageMaker's hosted training, which typically uses more powerful compute resources separate from your less powerful, lower cost notebook instance. Hosted training spins up one or more instances (i.e. a cluster) for training, and then tears the cluster down when training is complete. In general, hosted training is preferred for doing actual large-scale training on more powerful instances, especially for distributed training on a single instance with multiple GPUs or multiple instances each having multiple GPUs. \n",
195-
"\n",
196116
"### Upload data to S3\n",
197117
"\n",
198118
"Before starting hosted training, the data must be present in storage that can be accessed by SageMaker. The storage options are: Amazon S3 (object storage service), Amazon EFS (elastic NFS file system service), and Amazon FSx for Lustre (high-performance file system service). For this example, we'll upload the data to S3. "
@@ -222,9 +142,9 @@
222142
"cell_type": "markdown",
223143
"metadata": {},
224144
"source": [
225-
"### Hosted training Estimator setup\n",
145+
"### Estimator setup\n",
226146
"\n",
227-
"With the training data now in S3, we're ready to set up an Estimator object for hosted training. It is similar to the Local Mode Estimator, except the `train_instance_type` has been set to a ML instance type instead of a local type for Local Mode. Additionally, we've increased the number of epochs for actual training, as opposed to just testing the code in Local Mode."
147+
"With the training data now in S3, we're ready to set up an Estimator object for hosted training. Most of the Estimator parameters are self-explantory; further discussion of the instance type selection is below. The parameters most likely to change between different training jobs, the algorithm hyperparameters, are passed in as a dictionary."
228148
]
229149
},
230150
{
@@ -244,8 +164,8 @@
244164
" source_dir='tf-sentiment-script-mode',\n",
245165
" entry_point='sentiment.py',\n",
246166
" model_dir=model_dir,\n",
247-
" train_instance_type=train_instance_type,\n",
248-
" train_instance_count=1,\n",
167+
" instance_type=train_instance_type,\n",
168+
" instance_count=1,\n",
249169
" hyperparameters=hyperparameters,\n",
250170
" role=sagemaker.get_execution_role(),\n",
251171
" base_job_name='tf-sentiment',\n",
@@ -260,9 +180,9 @@
260180
"source": [
261181
"### Distributed training on a single multi-GPU instance\n",
262182
"\n",
263-
"The instance type selected above, p3.8xlarge, contains four GPUs based on NVIDIA's V100 Tensor Core architecture. This presents an opportunity to do distributed training within a single multi-GPU instance, utilizing all four GPUs to reduce total training time compared to using a single GPU. Although using multiple instances also is a possibility, using a single multi-GPU instance may be more performant because it avoids extra network traffic necessary to coordinate multiple instances. For larger datasets and more complex models, using multiple instances may be a necessity, however, that is not the case here.\n",
183+
"The SageMaker instance type selected above, p3.8xlarge, contains four GPUs based on NVIDIA's V100 Tensor Core architecture. This presents an opportunity to do distributed training within a single multi-GPU instance, utilizing all four GPUs to reduce total training time compared to using a single GPU. Although using multiple instances also is a possibility, using a single multi-GPU instance may be more performant because it avoids extra network traffic necessary to coordinate multiple instances. For larger datasets and more complex models, using multiple instances may be a necessity, however, that is not the case here.\n",
264184
"\n",
265-
"To utilize all four GPUs on the instance, you don't need to do anything special in Amazon SageMaker: TensorFlow 2 itself will handle the details under the hood. TensorFlow 2 includes several native distribution strategies, including MirroredStrategy, which is well-suited for training a model using multiple GPUs on a single instance. To enable MirroredStrategy, simply add the following lines of code in your training script before you define and compile the model:\n",
185+
"To utilize all four GPUs on the instance, you don't need to do anything special in Amazon SageMaker: TensorFlow 2 itself will handle the details under the hood. TensorFlow 2 includes several native distribution strategies, including MirroredStrategy, which is well-suited for training a model using multiple GPUs on a single instance. To enable MirroredStrategy, we simply add the following lines of code in the training script before defining and compiling the model (this has already been done for this example):\n",
266186
"\n",
267187
"```python\n",
268188
"def get_model(learning_rate):\n",
@@ -281,7 +201,7 @@
281201
" return model\n",
282202
"```\n",
283203
"\n",
284-
"Additionally, the batch size was increased in the Estimator hyperparameters to account for the fact that batches are divided among multiple GPUs. If you are interested in reviewing the rest of the training code, it is at the GitHub repository referenced above in the `git_config` variable. "
204+
"Additionally, the batch size is increased in the Estimator hyperparameters to account for the fact that batches are divided among multiple GPUs. If you are interested in reviewing the rest of the training code, it is at the GitHub repository referenced above in the `git_config` variable. "
285205
]
286206
},
287207
{
@@ -290,7 +210,7 @@
290210
"source": [
291211
"### Start the hosted training job\n",
292212
"\n",
293-
"With the change in training instance type and increase in epochs, we simply call `fit` to start the actual hosted training. The training job should take around 5 minutes, including the time needed to spin up the training instance. At the end of hosted training, you'll see from the logs below the cell that accuracy on the training set has greatly increased, and accuracy on the validation set is approaching 90%. "
213+
"We simply call `fit` to start the actual hosted training. The training job should take around 5 minutes, including the time needed to spin up the training instance. At the end of hosted training, you'll see from the logs below the code cell that validation accuracy is approaching 90%, and the number of billable seconds (which should be in the neighborhood of 180). "
294214
]
295215
},
296216
{
@@ -306,7 +226,7 @@
306226
"cell_type": "markdown",
307227
"metadata": {},
308228
"source": [
309-
"Although the training accuracy has improved, the validation accuracy plateaued, so the model might be overfitting now: it could be less able to generalize to data it has not yet seen. This is the case even though we are employing dropout as a regularization technique to reduce the possibility of overfitting. (See the training script at the GitHub repository referenced above.) For a production model, further experimentation would be necessary.\n",
229+
"The validation accuracy appears to have plateaued, so the model might be overfitting: it might be less able to generalize to data it has not yet seen. This is the case even though we are employing dropout as a regularization technique to reduce the possibility of overfitting. (See the training script at the GitHub repository referenced above.) For a production model, further experimentation would be necessary.\n",
310230
"\n",
311231
"TensorFlow 2's tf.keras API provides a convenient way to capture the history of model training. When the model was saved after training, the history was saved alongside it. To retrieve the history, we first download the trained model from the S3 bucket where SageMaker stored it. Models trained by SageMaker are always accessible in this way to be run anywhere. Next, we can unzip it to gain access to the history data structure, and then simply load the history as JSON:"
312232
]
@@ -522,7 +442,7 @@
522442
"name": "python",
523443
"nbconvert_exporter": "python",
524444
"pygments_lexer": "ipython3",
525-
"version": "3.6.6"
445+
"version": "3.6.10"
526446
}
527447
},
528448
"nbformat": 4,

0 commit comments

Comments
 (0)