<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Exporting a BigQuery ML Model for Online Prediction
Learning Objectives
Train and deploy a logistic regression model - also applies to DNN classifier, DNN regressor, k-means, linear regression, and matrix factorization models.
Train and deploy a Boosted Tree classifier model - also applies to Boosted Tree regressor model.
Train and deploy an AutoML classifier model - also applies to AutoML regressor model.
Introduction
In this notebook, you will learn how to export a BigQuery ML model and then deploy the model on AI Platform. You will use the iris table from the BigQuery public datasets and work through the three end-to-end scenarios.
Each learning objective will correspond to a #TODO in this student lab notebook -- try to complete this notebook first and then review the solution notebook.
Set up environment variables and load necessary libraries
Step1:  Check that the Google BigQuery library is installed and if not, install it.
Step2:  Note
Step3:  Set environment variables.
Set environment variables so that we can use them throughout the entire lab. We will be using our project name for our bucket, so you only need to change your project and region.
Step4:  Create a BigQuery Dataset and Google Cloud Storage Bucket
A BigQuery dataset is a container for tables, views, and models built with BigQuery ML. Let's create one called bqml_tutorial. We'll do the same for a GCS bucket for our project too.
Step5:  Train and deploy a logistic regression model
Train the model
Train a logistic regression model that predicts iris type using the BigQuery ML CREATE MODEL statement. This training job should take approximately 1 minute to complete.
Step6:  Export the model
Export the model to a Cloud Storage bucket using the bq command-line tool. For additional ways to export models, see Exporting BigQuery ML models. This extract job should take less than 1 minute to complete.
Step7:  Local deployment and serving
You can deploy exported TensorFlow models using the TensorFlow Serving Docker container. The following steps require you to install Docker.
Download the exported model files to a temporary directory
Step8:  Create a version subdirectory
This step sets a version number (1 in this case) for the model.
Step9:  Pull the docker image
Step10:  Run the Docker container
Step11:  Run the prediction
Step12:  Online deployment and serving
This section uses the gcloud command-line tool to deploy and run predictions against the exported model. For more details about deploying a model to AI Platform for online/batch predictions, see Deploying models.
Note
Step13:  Create a model version
Set the environment variables
Step14:  Create the version
Step15:  This step might take a few minutes to complete. You should see the message Creating version (this might take a few minutes).......
Get information about your new version.
Step16:  Online prediction
The details about running online predictions against a deployed model are available at Getting online predictions
Create a newline-delimited JSON file for inputs, for example instances.json file with the following content.
Step17:  Setup env variables for predict
Step18:  Run predict
Step19:  Train and deploy a Boosted Tree classifier model
Train the model
Train a Boosted Tree classifier model that predicts iris type using the BigQuery ML CREATE MODEL statement. This training job should take approximately 7 minutes to complete.
Step20:  Export the model
Export the model to a Cloud Storage bucket using the bq command-line tool. For additional ways to export models, see Exporting BigQuery ML models.
Step21:  Local deployment and serving
In the exported files, there is a main.py file for local run.
Download the exported model files to a local directory
Step22:  Extract predictor.py
Step23:  Install XGBoost library
Install the XGBoost library - version 0.82 or later.
Run the prediction
Step24:  Online deployment and serving
This section uses the gcloud command-line tool to deploy and run predictions against the exported model.
For more details about deploying a model to AI Platform for online/batch predictions using custom routines, see Deploying models.
Note
Step25:  Create a model version
Set the environment variables
Step26:  Create the version
Step27:  This step might take a few minutes to complete. You should see the message Creating version (this might take a few minutes).......
Get information about your new version.
Step28:  Online prediction
For more details about running online predictions against a deployed model, see Requesting predictions.
Create a newline-delimited JSON file for inputs. For example, instances.json file with the following content. Ignore if already created.
Step29:  Setup env variables for predict
Step30:  Run predict
Step31:  Train and deploy an AutoML classifier model
Train the model
Train an AutoML classifier model that predicts iris type using the BigQuery ML CREATE MODEL statement. AutoML models need at least 1000 rows of input data. Because ml_datasets.iris only has 150 rows, we duplicate the data 10 times. This training job should take around 2 hours to complete.
Step32:  Export the model
Export the model to a Cloud Storage bucket using the bq command-line tool. For additional ways to export models, see Exporting BigQuery ML models.
Step33:  Local deployment and serving
For details about building AutoML containers, see Exporting models. The following steps require you to install Docker.
Copy exported model files to a local directory
Step34:  Pull AutoML Docker image
Step35:  Start Docker container
Step36:  Run the prediction
Create a newline-delimited JSON file for inputs. For example, input.json file with the following contents
Step37:  Make the predict call
<ASSISTANT_TASK:>
Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
Explanation: Exporting a BigQuery ML Model for Online Prediction
Learning Objectives
Train and deploy a logistic regression model - also applies to DNN classifier, DNN regressor, k-means, linear regression, and matrix factorization models.
Train and deploy a Boosted Tree classifier model - also applies to Boosted Tree regressor model.
Train and deploy an AutoML classifier model - also applies to AutoML regressor model.
Introduction
In this notebook, you will learn how to export a BigQuery ML model and then deploy the model on AI Platform. You will use the iris table from the BigQuery public datasets and work through the three end-to-end scenarios.
Each learning objective will correspond to a #TODO in this student lab notebook -- try to complete this notebook first and then review the solution notebook.
Set up environment variables and load necessary libraries
End of explanation
!pip install --user google-cloud-bigquery==1.25.0
Explanation: Check that the Google BigQuery library is installed and if not, install it.
End of explanation
import os
from google.cloud import bigquery
Explanation: Note: Restart your kernel to use updated packages.
Kindly ignore the deprecation warnings and incompatibility errors related to google-cloud-storage.
Import necessary libraries.
End of explanation
%%bash
export PROJECT=$(gcloud config list project --format "value(core.project)")
echo "Your current GCP Project Name is: "$PROJECT
# TODO: Change environment variables
PROJECT = "cloud-training-demos"  # REPLACE WITH YOUR PROJECT NAME
BUCKET = "BUCKET"  # REPLACE WITH YOUR BUCKET NAME, DEFAULT BUCKET WILL BE PROJECT ID
REGION = "us-central1"  # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
# Do not change these
os.environ["BUCKET"] = PROJECT if BUCKET == "BUCKET" else BUCKET # DEFAULT BUCKET WILL BE PROJECT ID
os.environ["REGION"] = REGION
if PROJECT == "cloud-training-demos":
    print("Don't forget to update your PROJECT name! Currently:", PROJECT)
Explanation: Set environment variables.
Set environment variables so that we can use them throughout the entire lab. We will be using our project name for our bucket, so you only need to change your project and region.
End of explanation
%%bash
## Create a BigQuery dataset bqml_tutorial
    
    bq --location=US mk --dataset \
        --description "bqml_tutorial" \
        $PROJECT:bqml_tutorial
    echo "Here are your current datasets:"
    bq ls
Explanation: Create a BigQuery Dataset and Google Cloud Storage Bucket
A BigQuery dataset is a container for tables, views, and models built with BigQuery ML. Let's create one called bqml_tutorial. We'll do the same for a GCS bucket for our project too.
End of explanation
%%bash
bq query --use_legacy_sql=false \
  'CREATE MODEL `bqml_tutorial.iris_model`
  OPTIONS (model_type="logistic_reg",
      max_iterations=10, input_label_cols=["species"])
  AS SELECT
    *
  FROM
    `bigquery-public-data.ml_datasets.iris`;'
Explanation: Train and deploy a logistic regression model
Train the model
Train a logistic regression model that predicts iris type using the BigQuery ML CREATE MODEL statement. This training job should take approximately 1 minute to complete.
End of explanation
%%bash
bq extract -m bqml_tutorial.iris_model gs://$BUCKET/iris_model
Explanation: Export the model
Export the model to a Cloud Storage bucket using the bq command-line tool. For additional ways to export models, see Exporting BigQuery ML models. This extract job should take less than 1 minute to complete.
End of explanation
%%bash
mkdir tmp_dir
gsutil cp -r gs://$BUCKET/iris_model tmp_dir
Explanation: Local deployment and serving
You can deploy exported TensorFlow models using the TensorFlow Serving Docker container. The following steps require you to install Docker.
Download the exported model files to a temporary directory
End of explanation
%%bash
mkdir -p serving_dir/iris_model/1
cp -r tmp_dir/iris_model/* serving_dir/iris_model/1
rm -r tmp_dir
Explanation: Create a version subdirectory
This step sets a version number (1 in this case) for the model.
End of explanation
%%bash
docker pull tensorflow/serving
Explanation: Pull the docker image
End of explanation
%%bash
docker run -p 8500:8500 --network="host" --mount type=bind,source=`pwd`/serving_dir/iris_model,target=/models/iris_model -e MODEL_NAME=iris_model -t tensorflow/serving &
Explanation: Run the Docker container
End of explanation
%%bash
curl -d '{"instances": [{"sepal_length":5.0, "sepal_width":2.0, "petal_length":3.5, "petal_width":1.0}]}' -X POST http://localhost:8501/v1/models/iris_model:predict
Explanation: Run the prediction
End of explanation
MODEL_NAME="IRIS_MODEL"
gcloud ai-platform models create $MODEL_NAME
Explanation: Online deployment and serving
This section uses the gcloud command-line tool to deploy and run predictions against the exported model. For more details about deploying a model to AI Platform for online/batch predictions, see Deploying models.
Note: Execute the following commands in the Cloud Shell of Cloud Platform Console till the Run predict command. Click Activate Cloud Shell icon to open the cloud shell and click Continue.
Create a model resource
End of explanation
# Replace the BUCKET_NAME with your bucket name.
MODEL_DIR="gs://<BUCKET_NAME>/iris_model"
VERSION_NAME="v1"
FRAMEWORK="TENSORFLOW"
Explanation: Create a model version
Set the environment variables
End of explanation
gcloud ai-platform versions create $VERSION_NAME --model=$MODEL_NAME --origin=$MODEL_DIR --runtime-version=2.1 --framework=$FRAMEWORK
Explanation: Create the version
End of explanation
gcloud ai-platform versions describe $VERSION_NAME --model $MODEL_NAME
Explanation: This step might take a few minutes to complete. You should see the message Creating version (this might take a few minutes).......
Get information about your new version.
End of explanation
{"sepal_length":5.0, "sepal_width":2.0, "petal_length":3.5, "petal_width":1.0}
{"sepal_length":5.3, "sepal_width":3.7, "petal_length":1.5, "petal_width":0.2}
Explanation: Online prediction
The details about running online predictions against a deployed model are available at Getting online predictions
Create a newline-delimited JSON file for inputs, for example instances.json file with the following content.
End of explanation
INPUT_DATA_FILE="instances.json"
Explanation: Setup env variables for predict
End of explanation
gcloud ai-platform predict --model $MODEL_NAME --version $VERSION_NAME --json-instances $INPUT_DATA_FILE
Explanation: Run predict
End of explanation
%%bash
bq query --use_legacy_sql=false \
 'CREATE MODEL `bqml_tutorial.boosted_tree_iris_model`
 OPTIONS (model_type="boosted_tree_classifier",
 max_iterations=10, input_label_cols=["species"])
 AS SELECT
 *
 FROM
 `bigquery-public-data.ml_datasets.iris`;'
Explanation: Train and deploy a Boosted Tree classifier model
Train the model
Train a Boosted Tree classifier model that predicts iris type using the BigQuery ML CREATE MODEL statement. This training job should take approximately 7 minutes to complete.
End of explanation
%%bash
bq extract --destination_format ML_XGBOOST_BOOSTER -m bqml_tutorial.boosted_tree_iris_model gs://$BUCKET/boosted_tree_iris_model
Explanation: Export the model
Export the model to a Cloud Storage bucket using the bq command-line tool. For additional ways to export models, see Exporting BigQuery ML models.
End of explanation
%%bash
mkdir serving_dir
gsutil cp -r gs://$BUCKET/boosted_tree_iris_model serving_dir
Explanation: Local deployment and serving
In the exported files, there is a main.py file for local run.
Download the exported model files to a local directory
End of explanation
%%bash
tar -xvf serving_dir/boosted_tree_iris_model/xgboost_predictor-0.1.tar.gz -C serving_dir/boosted_tree_iris_model/
Explanation: Extract predictor.py
End of explanation
%%bash
pip3 install xgboost
%%bash
cd serving_dir/boosted_tree_iris_model/
python main.py '[{"sepal_length":5.0, "sepal_width":2.0, "petal_length":3.5, "petal_width":1.0}]'
Explanation: Install XGBoost library
Install the XGBoost library - version 0.82 or later.
Run the prediction
End of explanation
MODEL_NAME="BOOSTED_TREE_IRIS_MODEL"
gcloud ai-platform models create $MODEL_NAME
Explanation: Online deployment and serving
This section uses the gcloud command-line tool to deploy and run predictions against the exported model.
For more details about deploying a model to AI Platform for online/batch predictions using custom routines, see Deploying models.
Note: Execute the following commands in the Cloud Shell of Cloud Platform Console till the Run predict command.
Create a model resource
End of explanation
# Replace the BUCKET_NAME with your bucket name.
MODEL_DIR="gs://<BUCKET_NAME>/boosted_tree_iris_model"
VERSION_NAME="v1"
Explanation: Create a model version
Set the environment variables
End of explanation
gcloud beta ai-platform versions create $VERSION_NAME --model=$MODEL_NAME --origin=$MODEL_DIR --package-uris=${MODEL_DIR}/xgboost_predictor-0.1.tar.gz --prediction-class=predictor.Predictor --runtime-version=2.1
Explanation: Create the version
End of explanation
gcloud ai-platform versions describe $VERSION_NAME --model $MODEL_NAME
Explanation: This step might take a few minutes to complete. You should see the message Creating version (this might take a few minutes).......
Get information about your new version.
End of explanation
{"sepal_length":5.0, "sepal_width":2.0, "petal_length":3.5, "petal_width":1.0}
{"sepal_length":5.3, "sepal_width":3.7, "petal_length":1.5, "petal_width":0.2}
Explanation: Online prediction
For more details about running online predictions against a deployed model, see Requesting predictions.
Create a newline-delimited JSON file for inputs. For example, instances.json file with the following content. Ignore if already created.
End of explanation
INPUT_DATA_FILE="instances.json"
Explanation: Setup env variables for predict
End of explanation
gcloud ai-platform predict --model $MODEL_NAME --version $VERSION_NAME --json-instances $INPUT_DATA_FILE
Explanation: Run predict
End of explanation
%%bash
bq query --use_legacy_sql=false \
  'CREATE MODEL `bqml_tutorial.automl_iris_model`
  OPTIONS (model_type="automl_classifier",
      budget_hours=1, input_label_cols=["species"])
  AS SELECT
    * EXCEPT(multiplier)
  FROM
    `bigquery-public-data.ml_datasets.iris`, unnest(GENERATE_ARRAY(1, 10)) as multiplier;'
Explanation: Train and deploy an AutoML classifier model
Train the model
Train an AutoML classifier model that predicts iris type using the BigQuery ML CREATE MODEL statement. AutoML models need at least 1000 rows of input data. Because ml_datasets.iris only has 150 rows, we duplicate the data 10 times. This training job should take around 2 hours to complete.
End of explanation
%%bash
bq extract -m bqml_tutorial.automl_iris_model gs://$BUCKET/automl_iris_model
Explanation: Export the model
Export the model to a Cloud Storage bucket using the bq command-line tool. For additional ways to export models, see Exporting BigQuery ML models.
End of explanation
%%bash
mkdir automl_serving_dir
gsutil cp -r gs://$BUCKET/automl_iris_model/* automl_serving_dir/
Explanation: Local deployment and serving
For details about building AutoML containers, see Exporting models. The following steps require you to install Docker.
Copy exported model files to a local directory
End of explanation
%%bash
docker pull gcr.io/cloud-automl-tables-public/model_server
Explanation: Pull AutoML Docker image
End of explanation
%%bash
docker run -v `pwd`/automl_serving_dir:/models/default/0000001 -p 8080:8080 -it gcr.io/cloud-automl-tables-public/model_server
Explanation: Start Docker container
End of explanation
{"instances": [{"sepal_length":5.0, "sepal_width":2.0, "petal_length":3.5, "petal_width":1.0},
{"sepal_length":5.3, "sepal_width":3.7, "petal_length":1.5, "petal_width":0.2}]}
Explanation: Run the prediction
Create a newline-delimited JSON file for inputs. For example, input.json file with the following contents:
End of explanation
%%bash
curl -X POST --data @input.json http://localhost:8080/predict
Explanation: Make the predict call
End of explanation
<END_TASK>