mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
58 KiB
58 KiB
In [ ]:
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.In [ ]:
! pip3 install google-cloud-storageIn [ ]:
import os
if not os.getenv("AUTORUN"):
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)In [ ]:
PROJECT_ID = "[your-project-id]" # @param {type:"string"}In [ ]:
if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]":
# Get your GCP project id from gcloud
shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT_ID = shell_output[0]
print("Project ID:", PROJECT_ID)In [ ]:
! gcloud config set project $PROJECT_IDIn [ ]:
REGION = "us-central1" # @param {type: "string"}In [ ]:
from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")In [ ]:
import os
import sys
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your Google Cloud account. This provides access
# to your Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
# If on Vertex, then don't execute this code
if not os.path.exists("/opt/deeplearning/metadata/env_version"):
if "google.colab" in sys.modules:
from google.colab import auth as google_auth
google_auth.authenticate_user()
# If you are running this tutorial in a notebook locally, replace the string
# below with the path to your service account key and run this cell to
# authenticate your Google Cloud account.
else:
%env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json
# Log in to your account on Google Cloud
! gcloud auth loginIn [ ]:
BUCKET_NAME = "[your-bucket-name]" # @param {type:"string"}In [ ]:
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "[your-bucket-name]":
BUCKET_NAME = PROJECT_ID + "aip-" + TIMESTAMPIn [ ]:
! gsutil mb -l $REGION gs://$BUCKET_NAMEIn [ ]:
! gsutil ls -al gs://$BUCKET_NAMEIn [ ]:
import json
import os
import sys
import time
from googleapiclient import discoveryIn [ ]:
# Vertex location root path for your dataset, model and endpoint resources
PARENT = "projects/" + PROJECT_ID + "/locations/" + REGIONIn [ ]:
client = discovery.build("ml", "v1")In [ ]:
# Make folder for python training script
! rm -rf custom
! mkdir custom
# Add package information
! touch custom/README.md
setup_cfg = "[egg_info]\n\
tag_build =\n\
tag_date = 0"
! echo "$setup_cfg" > custom/setup.cfg
setup_py = "import setuptools\n\
setuptools.setup(\n\
install_requires=[\n\
],\n\
packages=setuptools.find_packages())"
! echo "$setup_py" > custom/setup.py
pkg_info = "Metadata-Version: 1.0\n\
Name: Custom Census Income\n\
Version: 0.0.0\n\
Summary: Demonstration training script\n\
Home-page: www.google.com\n\
Author: Google\n\
Author-email: aferlitsch@google.com\n\
License: Public\n\
Description: Demo\n\
Platform: Vertex AI"
! echo "$pkg_info" > custom/PKG-INFO
# Make the training subfolder
! mkdir custom/trainer
! touch custom/trainer/__init__.pyIn [ ]:
%%writefile custom/trainer/task.py
# Single Instance Training for Census Income
from sklearn.ensemble import RandomForestClassifier
import joblib
from sklearn.feature_selection import SelectKBest
from sklearn.pipeline import FeatureUnion
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import LabelBinarizer
import datetime
import pandas as pd
from google.cloud import storage
import numpy as np
import argparse
import os
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--model-dir', dest='model_dir',
default=os.getenv('AIP_MODEL_DIR'), type=str, help='Model dir.')
args = parser.parse_args()
print('Python Version = {}'.format(sys.version))
# Public bucket holding the census data
bucket = storage.Client().bucket('cloud-samples-data')
# Path to the data inside the public bucket
blob = bucket.blob('ai-platform/sklearn/census_data/adult.data')
# Download the data
blob.download_to_filename('adult.data')
# Define the format of your input data including unused columns (These are the columns from the census data files)
COLUMNS = (
'age',
'workclass',
'fnlwgt',
'education',
'education-num',
'marital-status',
'occupation',
'relationship',
'race',
'sex',
'capital-gain',
'capital-loss',
'hours-per-week',
'native-country',
'income-level'
)
# Categorical columns are columns that need to be turned into a numerical value to be used by scikit-learn
CATEGORICAL_COLUMNS = (
'workclass',
'education',
'marital-status',
'occupation',
'relationship',
'race',
'sex',
'native-country'
)
# Load the training census dataset
with open('./adult.data', 'r') as train_data:
raw_training_data = pd.read_csv(train_data, header=None, names=COLUMNS)
# Remove the column we are trying to predict ('income-level') from our features list
# Convert the Dataframe to a lists of lists
train_features = raw_training_data.drop('income-level', axis=1).values.tolist()
# Create our training labels list, convert the Dataframe to a lists of lists
train_labels = (raw_training_data['income-level'] == ' >50K').values.tolist()
# Since the census data set has categorical features, we need to convert
# them to numerical values. We'll use a list of pipelines to convert each
# categorical column and then use FeatureUnion to combine them before calling
# the RandomForestClassifier.
categorical_pipelines = []
# Each categorical column needs to be extracted individually and converted to a numerical value.
# To do this, each categorical column will use a pipeline that extracts one feature column via
# SelectKBest(k=1) and a LabelBinarizer() to convert the categorical value to a numerical one.
# A scores array (created below) will select and extract the feature column. The scores array is
# created by iterating over the COLUMNS and checking if it is a CATEGORICAL_COLUMN.
for i, col in enumerate(COLUMNS[:-1]):
if col in CATEGORICAL_COLUMNS:
# Create a scores array to get the individual categorical column.
# Example:
# data = [39, 'State-gov', 77516, 'Bachelors', 13, 'Never-married', 'Adm-clerical',
# 'Not-in-family', 'White', 'Male', 2174, 0, 40, 'United-States']
# scores = [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
#
# Returns: [['State-gov']]
# Build the scores array.
scores = [0] * len(COLUMNS[:-1])
# This column is the categorical column we want to extract.
scores[i] = 1
skb = SelectKBest(k=1)
skb.scores_ = scores
# Convert the categorical column to a numerical value
lbn = LabelBinarizer()
r = skb.transform(train_features)
lbn.fit(r)
# Create the pipeline to extract the categorical feature
categorical_pipelines.append(
('categorical-{}'.format(i), Pipeline([
('SKB-{}'.format(i), skb),
('LBN-{}'.format(i), lbn)])))
# Create pipeline to extract the numerical features
skb = SelectKBest(k=6)
# From COLUMNS use the features that are numerical
skb.scores_ = [1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0]
categorical_pipelines.append(('numerical', skb))
# Combine all the features using FeatureUnion
preprocess = FeatureUnion(categorical_pipelines)
# Create the classifier
classifier = RandomForestClassifier()
# Transform the features and fit them to the classifier
classifier.fit(preprocess.transform(train_features), train_labels)
# Create the overall model as a single pipeline
pipeline = Pipeline([
('union', preprocess),
('classifier', classifier)
])
# Split path into bucket and subdirectory
bucket = args.model_dir.split('/')[2]
subdir = args.model_dir.split('/')[-1]
# Write model to a local file
joblib.dump(pipeline, 'model.joblib')
# Upload the model to GCS
bucket = storage.Client().bucket(bucket)
blob = bucket.blob(subdir + '/model.joblib')
blob.upload_from_filename('model.joblib')
In [ ]:
! rm -f custom.tar custom.tar.gz
! tar cvf custom.tar custom
! gzip custom.tar
! gsutil cp custom.tar.gz gs://$BUCKET_NAME/census.tar.gzIn [ ]:
JOB_NAME = "custom_job_SKL" + TIMESTAMP
training_input = {
"scaleTier": "BASIC",
"packageUris": ["gs://" + BUCKET_NAME + "/census.tar.gz"],
"pythonModule": "trainer.task",
"args": ["--model-dir=" + "gs://{}/{}".format(BUCKET_NAME, JOB_NAME)],
"region": REGION,
"runtimeVersion": "2.4",
"pythonVersion": "3.7",
}
body = {"jobId": JOB_NAME, "trainingInput": training_input}
request = client.projects().jobs().create(parent="projects/" + PROJECT_ID)
request.body = body
print(json.dumps(json.loads(request.to_json()), indent=2))
request = client.projects().jobs().create(parent="projects/" + PROJECT_ID, body=body)In [ ]:
result = request.execute()In [ ]:
print(json.dumps(result, indent=2))In [ ]:
# The short numeric ID for the custom training job
custom_training_short_id = result["jobId"]
# The full unique ID for the custom training job
custom_training_id = "projects/" + PROJECT_ID + "/jobs/" + result["jobId"]
print(custom_training_id)In [ ]:
request = client.projects().jobs().get(name=custom_training_id)
result = request.execute()In [ ]:
print(json.dumps(result, indent=2))In [ ]:
while True:
response = client.projects().jobs().get(name=custom_training_id).execute()
if response["state"] != "SUCCEEDED":
print("Training job has not completed:", response["state"])
if response["state"] == "FAILED":
break
else:
break
time.sleep(60)
# model artifact output directory on Google Cloud Storage
model_artifact_dir = response["trainingInput"]["args"][0].split("=")[-1]
print("artifact location " + model_artifact_dir)In [ ]:
body = {"name": "custom_job_SKL" + TIMESTAMP}
request = client.projects().models().create(parent="projects/" + PROJECT_ID)
request.body = json.loads(json.dumps(body, indent=2))
print(json.dumps(json.loads(request.to_json()), indent=2))
request = client.projects().models().create(parent="projects/" + PROJECT_ID, body=body)In [ ]:
result = request.execute()In [ ]:
print(json.dumps(result, indent=2))In [ ]:
model_id = result["name"]In [ ]:
version = {
"name": "custom_job_SKL" + TIMESTAMP,
"deploymentUri": model_artifact_dir,
"runtimeVersion": "2.1",
"framework": "SCIKIT_LEARN",
"pythonVersion": "3.7",
"machineType": "mls1-c1-m2",
}
request = client.projects().models().versions().create(parent=model_id)
request.body = version
print(json.dumps(json.loads(request.to_json()), indent=2))
request = client.projects().models().versions().create(parent=model_id, body=version)In [ ]:
result = request.execute()In [ ]:
print(json.dumps(result, indent=2))In [ ]:
# The full unique ID for the model version
model_version_name = result["metadata"]["version"]["name"]
print(model_version_name)In [ ]:
while True:
response = (
client.projects().models().versions().get(name=model_version_name).execute()
)
if response["state"] == "READY":
print("Model version created.")
break
time.sleep(60)In [ ]:
INSTANCES = [
[
25,
"Private",
226802,
"11th",
7,
"Never-married",
"Machine-op-inspct",
"Own-child",
"Black",
"Male",
0,
0,
40,
"United-States",
],
[
38,
"Private",
89814,
"HS-grad",
9,
"Married-civ-spouse",
"Farming-fishing",
"Husband",
"White",
"Male",
0,
0,
50,
"United-States",
],
[
28,
"Local-gov",
336951,
"Assoc-acdm",
12,
"Married-civ-spouse",
"Protective-serv",
"Husband",
"White",
"Male",
0,
0,
40,
"United-States",
],
[
44,
"Private",
160323,
"Some-college",
10,
"Married-civ-spouse",
"Machine-op-inspct",
"Husband",
"Black",
"Male",
7688,
0,
40,
"United-States",
],
[
18,
"?",
103497,
"Some-college",
10,
"Never-married",
"?",
"Own-child",
"White",
"Female",
0,
0,
30,
"United-States",
],
[
34,
"Private",
198693,
"10th",
6,
"Never-married",
"Other-service",
"Not-in-family",
"White",
"Male",
0,
0,
30,
"United-States",
],
[
29,
"?",
227026,
"HS-grad",
9,
"Never-married",
"?",
"Unmarried",
"Black",
"Male",
0,
0,
40,
"United-States",
],
[
63,
"Self-emp-not-inc",
104626,
"Prof-school",
15,
"Married-civ-spouse",
"Prof-specialty",
"Husband",
"White",
"Male",
3103,
0,
32,
"United-States",
],
[
24,
"Private",
369667,
"Some-college",
10,
"Never-married",
"Other-service",
"Unmarried",
"White",
"Female",
0,
0,
40,
"United-States",
],
[
55,
"Private",
104996,
"7th-8th",
4,
"Married-civ-spouse",
"Craft-repair",
"Husband",
"White",
"Male",
0,
0,
10,
"United-States",
],
]In [ ]:
request = client.projects().predict(name=model_version_name)
request.body = json.loads(json.dumps({"instances": INSTANCES}, indent=2))
print(json.dumps(json.loads(request.to_json()), indent=2))
request = client.projects().predict(
name=model_version_name, body={"instances": INSTANCES}
)In [ ]:
result = request.execute()In [ ]:
print(json.dumps(result, indent=2))In [ ]:
request = client.projects().models().versions().delete(name=model_version_name)In [ ]:
response = request.execute()In [ ]:
print(json.dumps(response, indent=2))Warning:
Output truncated. This notebook contains too many cells to display efficiently.