<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Classifying Images with pre-built TF Container on Vertex AI
Introduction
In this notebook, you learn how to implement different image models on MNIST using the tf.keras API.
Learning objectives
Understand how to build a Dense Neural Network (DNN) for image classification.
Understand how to use dropout (DNN) for image classification.
Understand how to use Convolutional Neural Networks (CNN).
Know how to deploy and use an image classifcation model using Google Cloud's Vertex AI.
Each learning objective will correspond to a #TODO in the student lab notebook -- try to complete this notebook first and then review the solution notebook
Configuring the parameters
First, configure the parameters below to match your own Google Cloud project details.
If you don’t want to change the region, leave all settings as they are. Otherwise, update the region as you want, leave other settings as they are and run the cell.
Step3:  Building a dynamic model
This part of notebook demonstrates how to implement DNN and CNN models on MNIST using the tf.keras API. 
In the previous notebook, “classifying_images_with_a_nn_and_dnn_model.ipynb”, you run the code directly from the notebook. In this notebook, you see that you can also package your notebook as a python module on Vertex AI.
The boilerplate structure for this module has already been set up in the folder mnist_models. The module lives in the sub-folder, trainer, and is designated as a python package with the empty init.py (mnist_models/trainer/init.py) file. It still needs the model and a trainer to run it, so let's make them.
Start with the trainer file first. This file parses command line arguments to feed into the model.
Step6:  Next, group non-model functions into a util file to keep the model file simple. Use the scale and load_dataset functions to scale images from a 0-255 int range to a 0-1 float range and load MNIST dataset into a tf.data.Dataset.
Step10:  Now you can code the models. The tf.keras API accepts an array of layers into a model object, so you can create a dictionary of layers based on the different model types you want to use. mnist_models/trainer/model.py file has three functions
Step11:  Local Training
After completing the set up, you can run locally to test the code. Some of the previous tests have been copied over into a testing script mnist_models/trainer/test.py to make sure the model still passes our previous checks. On line 13, you can specify which model types you would like to check. line 14 and line 15 have the number of epochs and steps per epoch respectively.
Run the code below to check your models against the unit tests. If you see "OK" at the end when it's finished running, congrats! You've passed the tests!
Step12:  Now you know that your models are working as expected. Now ,you can run it on Google Cloud within Vertex AI. You can run it as a python module locally first using the command line.
The below cell transfers some of your variables to the command line and creates a job directory including a timestamp.
Step13:  The cell below runs the local version of the code. The epochs and steps_per_epoch flag can be changed to run for longer or shorter, as defined in your mnist_models/trainer/task.py file.
Step14:  Training on the cloud
For this model, you use a Tensorflow pre-built container on Vertex AI, as you do not have any particular additional prerequisites. You use setuptools for this, and store the created source distribution on Cloud Storage by using “gsutil cp”.
Step15:  Then, you can start the Vertex AI Custom Job using the pre-built container. You can pass your source distribution URI using the --python-package-uris flag.
Step16:  After submitting the following job, view the status in Vertex AI > Training and select Custom Jobs tab. Wait for the job to finish.
Step17:  Deploying and predicting with model
Once you have a model you're proud of, let's deploy it! All you need to do is to upload the created model artifact from Cloud Storage to Vertex AI as a model, create a new endpoint, and deploy the model to the endpoint. It can take 15-20 minutes to complete. Make a note of ENDPOINT_RESOURCENAME for further use.
Step18:  To predict with the model, take one of the example images.
Write a .json file with image data to send to a Vertex AI deployed model.
Step19:  Finally, you can send it to the prediction service. The output will have a 1 in the index of the corresponding digit it is predicting. Congrats! You've completed the lab!
<ASSISTANT_TASK:>
Python Code:
from datetime import datetime
import os
REGION = 'us-central1'
PROJECT = !(gcloud config get-value core/project)
PROJECT = PROJECT[0]
BUCKET =  PROJECT
MODEL_TYPE = "cnn"  # "linear", "dnn", "dnn_dropout", or "cnn"
# Do not change these
os.environ["PROJECT"] = PROJECT
os.environ["BUCKET"] = BUCKET
os.environ["REGION"] = REGION
os.environ["MODEL_TYPE"] = MODEL_TYPE
Explanation: Classifying Images with pre-built TF Container on Vertex AI
Introduction
In this notebook, you learn how to implement different image models on MNIST using the tf.keras API.
Learning objectives
Understand how to build a Dense Neural Network (DNN) for image classification.
Understand how to use dropout (DNN) for image classification.
Understand how to use Convolutional Neural Networks (CNN).
Know how to deploy and use an image classifcation model using Google Cloud's Vertex AI.
Each learning objective will correspond to a #TODO in the student lab notebook -- try to complete this notebook first and then review the solution notebook
Configuring the parameters
First, configure the parameters below to match your own Google Cloud project details.
If you don’t want to change the region, leave all settings as they are. Otherwise, update the region as you want, leave other settings as they are and run the cell.
End of explanation
%%writefile mnist_models/trainer/task.py
import argparse
import json
import os
import sys
from . import model
def _parse_arguments(argv):
    Parses command-line arguments.
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--model_type',
        help='Which model type to use',
        type=str, default='linear')
    parser.add_argument(
        '--epochs',
        help='The number of epochs to train',
        type=int, default=10)
    parser.add_argument(
        '--steps_per_epoch',
        help='The number of steps per epoch to train',
        type=int, default=100)
    parser.add_argument(
        '--job-dir',
        help='Directory where to save the given model',
        type=str, default='mnist_models/')
    return parser.parse_known_args(argv)
def main():
    Parses command line arguments and kicks off model training.
    args = _parse_arguments(sys.argv[1:])[0]
    # Configure path for hyperparameter tuning.
    trial_id = json.loads(
        os.environ.get('TF_CONFIG', '{}')).get('task', {}).get('trial', '')
    output_path = args.job_dir if not trial_id else args.job_dir + '/'
    model_layers = model.get_layers(args.model_type)
    image_model = model.build_model(model_layers, args.job_dir)
    model_history = model.train_and_evaluate(
        image_model, args.epochs, args.steps_per_epoch, args.job_dir)
if __name__ == '__main__':
    main()
Explanation: Building a dynamic model
This part of notebook demonstrates how to implement DNN and CNN models on MNIST using the tf.keras API. 
In the previous notebook, “classifying_images_with_a_nn_and_dnn_model.ipynb”, you run the code directly from the notebook. In this notebook, you see that you can also package your notebook as a python module on Vertex AI.
The boilerplate structure for this module has already been set up in the folder mnist_models. The module lives in the sub-folder, trainer, and is designated as a python package with the empty init.py (mnist_models/trainer/init.py) file. It still needs the model and a trainer to run it, so let's make them.
Start with the trainer file first. This file parses command line arguments to feed into the model.
End of explanation
%%writefile mnist_models/trainer/util.py
import tensorflow as tf
def scale(image, label):
    Scales images from a 0-255 int range to a 0-1 float range
    image = tf.cast(image, tf.float32)
    image /= 255
    image = tf.expand_dims(image, -1)
    return image, label
def load_dataset(
        data, training=True, buffer_size=5000, batch_size=100, nclasses=10):
    Loads MNIST dataset into a tf.data.Dataset
    (x_train, y_train), (x_test, y_test) = data
    x = x_train if training else x_test
    y = y_train if training else y_test
    # One-hot encode the classes
    y = tf.keras.utils.to_categorical(y, nclasses)
    dataset = tf.data.Dataset.from_tensor_slices((x, y))
    dataset = dataset.map(scale).batch(batch_size)
    if training:
        dataset = dataset.shuffle(buffer_size).repeat()
    return dataset
Explanation: Next, group non-model functions into a util file to keep the model file simple. Use the scale and load_dataset functions to scale images from a 0-255 int range to a 0-1 float range and load MNIST dataset into a tf.data.Dataset.
End of explanation
%%writefile mnist_models/trainer/model.py
import os
import shutil
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.callbacks import TensorBoard
from tensorflow.keras.layers import (
    Conv2D, Dense, Dropout, Flatten, MaxPooling2D, Softmax)
from . import util
# Image Variables
WIDTH = 28
HEIGHT = 28
def get_layers(
        model_type,
        nclasses=10,
        hidden_layer_1_neurons=400,
        hidden_layer_2_neurons=100,
        dropout_rate=0.25,
        num_filters_1=64,
        kernel_size_1=3,
        pooling_size_1=2,
        num_filters_2=32,
        kernel_size_2=3,
        pooling_size_2=2):
    Constructs layers for a keras model based on a dict of model types.
    model_layers = {
        'linear': [
            Flatten(),
            Dense(nclasses),
            Softmax()
        ],
        'dnn': [
            # TODO 1: Your code here
        ],
        'dnn_dropout': [
            # TODO 2: Your code here
        ],
        'cnn': [
            # TODO 3: Your code here
        ]
    }
    return model_layers[model_type]
def build_model(layers, output_dir):
    Compiles keras model for image classification.
    model = Sequential(layers)
    model.compile(optimizer='adam',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])
    return model
def train_and_evaluate(model, num_epochs, steps_per_epoch, output_dir):
    Compiles keras model and loads data into it for training.
    mnist = tf.keras.datasets.mnist.load_data()
    train_data = util.load_dataset(mnist)
    validation_data = util.load_dataset(mnist, training=False)
    callbacks = []
    if output_dir:
        tensorboard_callback = TensorBoard(log_dir=output_dir)
        callbacks = [tensorboard_callback]
    history = model.fit(
        train_data,
        validation_data=validation_data,
        epochs=num_epochs,
        steps_per_epoch=steps_per_epoch,
        verbose=2,
        callbacks=callbacks)
    if output_dir:
        export_path = os.path.join(output_dir, 'keras_export')
        model.save(export_path, save_format='tf')
    return history
Explanation: Now you can code the models. The tf.keras API accepts an array of layers into a model object, so you can create a dictionary of layers based on the different model types you want to use. mnist_models/trainer/model.py file has three functions: get_layers, build_model and train_and_evaluate. 
In get_layers function: Youl build the structure of our model in get_layers with four different layers:
First, you define a linear model.
Second, you define the Keras layers for a DNN model.
Third, you define the Keras layers for a dropout model.
Lastly, you define the Keras layers for a CNN model.
In the build_model function: You compile the model, specifying an optimizer to use, the loss to minimize, and metrics to report. 
Finally in the train_and_evaluate function, you compile your Keras model by loading data into it for training.
Note that these models progressively build on each other. Look at the imported tensorflow.keras.layers modules and the default values for the variables defined in get_layers for guidance.
End of explanation
!python3 -m mnist_models.trainer.test
Explanation: Local Training
After completing the set up, you can run locally to test the code. Some of the previous tests have been copied over into a testing script mnist_models/trainer/test.py to make sure the model still passes our previous checks. On line 13, you can specify which model types you would like to check. line 14 and line 15 have the number of epochs and steps per epoch respectively.
Run the code below to check your models against the unit tests. If you see "OK" at the end when it's finished running, congrats! You've passed the tests!
End of explanation
current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
model_type = 'cnn'
os.environ["MODEL_TYPE"] = model_type
os.environ["JOB_DIR"] = "mnist_models/models/{}_{}/".format(
    model_type, current_time)
Explanation: Now you know that your models are working as expected. Now ,you can run it on Google Cloud within Vertex AI. You can run it as a python module locally first using the command line.
The below cell transfers some of your variables to the command line and creates a job directory including a timestamp.
End of explanation
%%bash
python3 -m mnist_models.trainer.task \
    --job-dir=$JOB_DIR \
    --epochs=5 \
    --steps_per_epoch=50 \
    --model_type=$MODEL_TYPE
Explanation: The cell below runs the local version of the code. The epochs and steps_per_epoch flag can be changed to run for longer or shorter, as defined in your mnist_models/trainer/task.py file.
End of explanation
%%writefile mnist_models/setup.py
from setuptools import find_packages
from setuptools import setup
setup(
    name='mnist_trainer',
    version='0.1',
    packages=find_packages(),
    include_package_data=True,
    description='MNIST model training application.'
)
%%bash
cd mnist_models
python ./setup.py sdist --formats=gztar
cd ..
gsutil cp mnist_models/dist/mnist_trainer-0.1.tar.gz gs://${BUCKET}/mnist/
Explanation: Training on the cloud
For this model, you use a Tensorflow pre-built container on Vertex AI, as you do not have any particular additional prerequisites. You use setuptools for this, and store the created source distribution on Cloud Storage by using “gsutil cp”.
End of explanation
current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
model_type = 'cnn'
os.environ["MODEL_TYPE"] = model_type
os.environ["JOB_DIR"] = "gs://{}/mnist_{}_{}/".format(
    BUCKET, model_type, current_time)
os.environ["JOB_NAME"] = "mnist_{}_{}".format(
    model_type, current_time)
Explanation: Then, you can start the Vertex AI Custom Job using the pre-built container. You can pass your source distribution URI using the --python-package-uris flag.
End of explanation
%%bash
echo $JOB_DIR $REGION $JOB_NAME
PYTHON_PACKAGE_URIS=gs://${BUCKET}/mnist/mnist_trainer-0.1.tar.gz
MACHINE_TYPE=n1-standard-4
REPLICA_COUNT=1
PYTHON_PACKAGE_EXECUTOR_IMAGE_URI="us-docker.pkg.dev/vertex-ai/training/tf-cpu.2-3:latest"
PYTHON_MODULE=trainer.task
    
WORKER_POOL_SPEC="machine-type=$MACHINE_TYPE,\
replica-count=$REPLICA_COUNT,\
executor-image-uri=$PYTHON_PACKAGE_EXECUTOR_IMAGE_URI,\
python-module=$PYTHON_MODULE"
gcloud ai custom-jobs create \
  --region=${REGION} \
  --display-name=$JOB_NAME \
  --python-package-uris=$PYTHON_PACKAGE_URIS \
  --worker-pool-spec=$WORKER_POOL_SPEC \
  --args="--job-dir=$JOB_DIR,--model_type=$MODEL_TYPE"
%%bash
SAVEDMODEL_DIR=${JOB_DIR}keras_export
echo $SAVEDMODEL_DIR
gsutil ls $SAVEDMODEL_DIR
Explanation: After submitting the following job, view the status in Vertex AI > Training and select Custom Jobs tab. Wait for the job to finish.
End of explanation
%%bash
TIMESTAMP=$(date -u +%Y%m%d_%H%M%S)
MODEL_DISPLAYNAME=mnist_$TIMESTAMP
ENDPOINT_DISPLAYNAME=mnist_endpoint_$TIMESTAMP
IMAGE_URI="us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-3:latest"
SAVEDMODEL_DIR=${JOB_DIR}keras_export
echo $SAVEDMODEL_DIR
# Model
MODEL_RESOURCENAME=$(gcloud ai models upload \
    --region=$REGION \
    --display-name=$MODEL_DISPLAYNAME \
    --container-image-uri=$IMAGE_URI \
    --artifact-uri=$SAVEDMODEL_DIR \
    --format="value(model)")
echo "MODEL_DISPLAYNAME=${MODEL_DISPLAYNAME}"
echo "MODEL_RESOURCENAME=${MODEL_RESOURCENAME}"
# Endpoint
ENDPOINT_RESOURCENAME=$(gcloud ai endpoints create \
  --region=$REGION \
  --display-name=$ENDPOINT_DISPLAYNAME \
  --format="value(name)")
echo "ENDPOINT_DISPLAYNAME=${ENDPOINT_DISPLAYNAME}"
echo "ENDPOINT_RESOURCENAME=${ENDPOINT_RESOURCENAME}"
# Deployment
DEPLOYED_MODEL_DISPLAYNAME=${MODEL_DISPLAYNAME}_deployment
MACHINE_TYPE=n1-standard-2
gcloud ai endpoints deploy-model $ENDPOINT_RESOURCENAME \
  --region=$REGION \
  --model=$MODEL_RESOURCENAME \
  --display-name=$DEPLOYED_MODEL_DISPLAYNAME \
  --machine-type=$MACHINE_TYPE \
  --min-replica-count=1 \
  --max-replica-count=1 \
  --traffic-split=0=100
Explanation: Deploying and predicting with model
Once you have a model you're proud of, let's deploy it! All you need to do is to upload the created model artifact from Cloud Storage to Vertex AI as a model, create a new endpoint, and deploy the model to the endpoint. It can take 15-20 minutes to complete. Make a note of ENDPOINT_RESOURCENAME for further use.
End of explanation
import json, codecs
import tensorflow as tf
import matplotlib.pyplot as plt
HEIGHT = 28
WIDTH = 28
IMGNO = 12
mnist = tf.keras.datasets.mnist.load_data()
(x_train, y_train), (x_test, y_test) = mnist
test_image = x_test[IMGNO]
jsondata = # TODO 4: Your code here
json.dump(jsondata, codecs.open("test.json", "w", encoding = "utf-8"))
plt.imshow(test_image.reshape(HEIGHT, WIDTH));
!cat test.json
Explanation: To predict with the model, take one of the example images.
Write a .json file with image data to send to a Vertex AI deployed model.
End of explanation
%%bash
ENDPOINT_RESOURCENAME=#Insert ENDPOINT_RESOURCENAME from above
gcloud ai endpoints predict $ENDPOINT_RESOURCENAME \
    --region=$REGION \
    --json-request=test.json
Explanation: Finally, you can send it to the prediction service. The output will have a 1 in the index of the corresponding digit it is predicting. Congrats! You've completed the lab!
End of explanation
<END_TASK>