mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
22 KiB
22 KiB
In [ ]:
# Copyright 2022 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 [ ]:
! pip install --upgrade --quiet google-cloud-aiplatform \
tensorflow==2.11 \
matplotlib \
pandas \
'numpy<2.0.0'In [ ]:
import sys
if "google.colab" in sys.modules:
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)In [ ]:
import sys
if "google.colab" in sys.modules:
from google.colab import auth
auth.authenticate_user()In [ ]:
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
LOCATION = "us-central1" # @param {type:"string"}In [ ]:
import matplotlib.pyplot as plt
import pandas as pd
from google.cloud import aiplatform
from tensorflow.python.keras import Sequential, layers
from tensorflow.python.keras.utils import data_utilsIn [ ]:
EXPERIMENT_NAME = "my-experiment-name-unique" # @param {type:"string"}In [ ]:
def read_data(uri):
dataset_path = data_utils.get_file("auto-mpg.data", uri)
column_names = [
"MPG",
"Cylinders",
"Displacement",
"Horsepower",
"Weight",
"Acceleration",
"Model Year",
"Origin",
]
raw_dataset = pd.read_csv(
dataset_path,
names=column_names,
na_values="?",
comment="\t",
sep=" ",
skipinitialspace=True,
)
dataset = raw_dataset.dropna()
dataset["Origin"] = dataset["Origin"].map(
lambda x: {1: "USA", 2: "Europe", 3: "Japan"}.get(x)
)
dataset = pd.get_dummies(dataset, prefix="", prefix_sep="")
return dataset
dataset = read_data(
"http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
)In [ ]:
def train_test_split(dataset, split_frac=0.8, random_state=0):
train_dataset = dataset.sample(frac=split_frac, random_state=random_state)
test_dataset = dataset.drop(train_dataset.index)
train_labels = train_dataset.pop("MPG")
test_labels = test_dataset.pop("MPG")
return train_dataset, test_dataset, train_labels, test_labels
train_dataset, test_dataset, train_labels, test_labels = train_test_split(dataset)In [ ]:
def normalize_dataset(train_dataset, test_dataset):
train_stats = train_dataset.describe()
train_stats = train_stats.transpose()
def norm(x):
return (x - train_stats["mean"]) / train_stats["std"]
normed_train_data = norm(train_dataset)
normed_test_data = norm(test_dataset)
return normed_train_data, normed_test_data
normed_train_data, normed_test_data = normalize_dataset(train_dataset, test_dataset)In [ ]:
def train(
train_data,
train_labels,
num_units=64,
activation="relu",
dropout_rate=0.0,
validation_split=0.2,
epochs=1000,
):
model = Sequential(
[
layers.Dense(
num_units,
activation=activation,
input_shape=[len(train_dataset.keys())],
),
layers.Dropout(rate=dropout_rate),
layers.Dense(num_units, activation=activation),
layers.Dense(1),
]
)
model.compile(loss="mse", optimizer="adam", metrics=["mae", "mse"])
print(model.summary())
history = model.fit(
train_data, train_labels, epochs=epochs, validation_split=validation_split
)
return model, historyIn [ ]:
aiplatform.init(project=PROJECT_ID, location=LOCATION, experiment=EXPERIMENT_NAME)In [ ]:
parameters = [
{"num_units": 16, "epochs": 3, "dropout_rate": 0.1},
{"num_units": 16, "epochs": 10, "dropout_rate": 0.1},
{"num_units": 16, "epochs": 10, "dropout_rate": 0.2},
{"num_units": 32, "epochs": 10, "dropout_rate": 0.1},
{"num_units": 32, "epochs": 10, "dropout_rate": 0.2},
]
for i, params in enumerate(parameters):
aiplatform.start_run(run=f"auto-mpg-lcl-run-{i}")
aiplatform.log_params(params)
model, history = train(
normed_train_data,
train_labels,
num_units=params["num_units"],
activation="relu",
epochs=params["epochs"],
dropout_rate=params["dropout_rate"],
)
for metric, values in history.history.items():
try:
aiplatform.log_metrics({metric: values[-1]})
except:
aiplatform.log_metrics({metric: 0.0})
loss, mae, mse = model.evaluate(normed_test_data, test_labels, verbose=2)
try:
aiplatform.log_metrics({"eval_loss": loss, "eval_mae": mae, "eval_mse": mse})
except:
aiplatform.log_metrics({"eval_loss": 0.0, "eval_mae": 0.0, "eval_mse": 0.0})In [ ]:
experiment_df = aiplatform.get_experiment_df()
experiment_dfIn [ ]:
plt.rcParams["figure.figsize"] = [15, 5]
ax = pd.plotting.parallel_coordinates(
experiment_df.reset_index(level=0),
"run_name",
cols=[
"param.num_units",
"param.dropout_rate",
"param.epochs",
"metric.loss",
"metric.val_loss",
"metric.eval_loss",
],
color=["blue", "green", "pink", "red"],
)
ax.set_yscale("symlog")
ax.legend(bbox_to_anchor=(1.0, 0.5))In [ ]:
print("Vertex AI Experiments:")
print(
f"https://console.cloud.google.com/ai/platform/experiments/experiments?folder=&organizationId=&project={PROJECT_ID}"
)In [ ]:
from google.cloud import aiplatform
# delete experiment and runs associated with experiment
experiment_name = (EXPERIMENT_NAME,)
project = (PROJECT_ID,)
location = (LOCATION,)
delete_backing_tensorboard_runs = (True,)
experiment = aiplatform.Experiment(
experiment_name=EXPERIMENT_NAME, project=PROJECT_ID, location=LOCATION
)
experiment.delete(delete_backing_tensorboard_runs=delete_backing_tensorboard_runs)