markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Simple examplesSay we have a class: | class ProductionClass(object):
def method(self, *args):
# This does something we do not want to actually run in the test
# ...
pass | _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
To mock the `ProductionClass.method` do this: | from unittest.mock import MagicMock
thing = ProductionClass()
thing.method = MagicMock(return_value=3)
thing.method(3, 4, 5, key='value')
thing.method.assert_called_with(3, 4, 5, key='value')
| _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
More practical use case- Mocking a module or system call- Mocking an object or method- Remember that after testing you want to restore original state- Use `mock.patch` An example- Write code to remove generated files from LaTeX compilation, i.e. remove the *.aux, *.log, *.pdf etc.Here is a simple attempt: | # clean_tex.py
import os
def cleanup(tex_file_pth):
base = os.path.splitext(tex_file_pth)[0]
for ext in ('.aux', '.log'):
f = base + ext
if os.path.exists(f):
os.remove(f)
| _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
Testing this with mock | import mock
@mock.patch('clean_tex.os.remove')
def test_cleanup_removes_extra_files(mock_remove):
cleanup('foo.tex')
expected = [mock.call('foo.' + x) for x in ('aux', 'log')]
mock_remove.assert_has_calls(expected)
| _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
- Note the mocked argument that is passed.- Note that we did not mock `os.remove`- Mock where the object is looked up Doing more | import mock
@mock.patch('clean_tex.os.path')
@mock.patch('clean_tex.os.remove')
def test_cleanup_does_not_fail_when_files_dont_exist(mock_remove, mock_path):
# Setup the mock_path to return False
mock_path.exists.return_value = False
cleanup('foo.tex')
mock_remove.assert_not_called() | _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
- Note the order of the passed arguments- Note the name of the method Patching instance methodsUse `mock.patch.object` to patch an instance method | @mock.patch.object(ProductionClass, 'method')
def test_method(mock_method):
obj = ProductionClass()
obj.method(1)
mock_method.assert_called_once_with(1)
| _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
Mock works as a context manager: | with mock.patch.object(ProductionClass, 'method') as mock_method:
obj = ProductionClass()
obj.method(1)
mock_method.assert_called_once_with(1)
| _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
More articles on mock- See more here https://docs.python.org/3/library/unittest.mock.html- https://www.toptal.com/python/an-introduction-to-mocking-in-python PytestOffers many useful and convenient features that are useful Odds and ends Linters- `pyflakes`- `flake8` IPython goodies- Use `%run`- Use `%pdb`- `%debug` De... | from IPython.core.debugger import Tracer; Tracer()() | _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
Support Vector Regression with MinMaxScaler Required Packages | import warnings
import numpy as np
import pandas as pd
import seaborn as se
import matplotlib.pyplot as plt
from sklearn.svm import SVR
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.metrics import r2_score... | _____no_output_____ | Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
InitializationFilepath of CSV file | file_path= "" | _____no_output_____ | Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
List of features which are required for model training . | features = [] | _____no_output_____ | Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
Target feature for prediction. | target='' | _____no_output_____ | Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
Data FetchingPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. | df=pd.read_csv(file_path)
df.head() | _____no_output_____ | Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
Feature SelectionsIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.We will assign all the required input features to... | X=df[features]
Y=df[target] | _____no_output_____ | Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
Data PreprocessingSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the da... | def NullClearner(df):
if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])):
df.fillna(df.mean(),inplace=True)
return df
elif(isinstance(df, pd.Series)):
df.fillna(df.mode()[0],inplace=True)
return df
else:return df
def EncodeX(df):
return pd.get_dummies(df) | _____no_output_____ | Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
Calling preprocessing functions on the feature and target set. | x=X.columns.to_list()
for i in x:
X[i]=NullClearner(X[i])
X=EncodeX(X)
Y=NullClearner(Y)
X.head() | _____no_output_____ | Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
Correlation MapIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. | f,ax = plt.subplots(figsize=(18, 18))
matrix = np.triu(X.corr())
se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)
plt.show() | _____no_output_____ | Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
Data SplittingThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of th... | x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123) | _____no_output_____ | Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
ModelSupport vector machines (SVMs) are a set of supervised learning methods used for classification, regression and outliers detection.A Support Vector Machine is a discriminative classifier formally defined by a separating hyperplane. In other terms, for a given known/labelled data points, the SVM outputs an appropr... | model=make_pipeline(MinMaxScaler(),SVR())
model.fit(x_train,y_train) | _____no_output_____ | Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
Model AccuracyWe will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model.> **score**: The **score** function returns the coefficient of determination R2 of the prediction. | print("Accuracy score {:.2f} %\n".format(model.score(x_test,y_test)*100)) | Accuracy score 42.32 %
| Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
> **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. > **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) b... | y_pred=model.predict(x_test)
print("R2 Score: {:.2f} %".format(r2_score(y_test,y_pred)*100))
print("Mean Absolute Error {:.2f}".format(mean_absolute_error(y_test,y_pred)))
print("Mean Squared Error {:.2f}".format(mean_squared_error(y_test,y_pred))) | R2 Score: 42.32 %
Mean Absolute Error 0.48
Mean Squared Error 0.38
| Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
Prediction PlotFirst, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis.For the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis. | plt.figure(figsize=(14,10))
plt.plot(range(20),y_test[0:20], color = "green")
plt.plot(range(20),model.predict(x_test[0:20]), color = "red")
plt.legend(["Actual","prediction"])
plt.title("Predicted vs True Value")
plt.xlabel("Record number")
plt.ylabel(target)
plt.show() | _____no_output_____ | Apache-2.0 | Regression/Support Vector Machine/SVR_MinMaxScaler.ipynb | PrajwalNimje1997/ds-seed |
Vertex AI client library: Custom training image classification model for online prediction for A/B testing Run in Colab View on GitHub OverviewThis tutorial demonstrates how to use the Vertex AI Python client library to train and deploy a custom image classification model for ... | import sys
if "google.colab" in sys.modules:
USER_FLAG = ""
else:
USER_FLAG = "--user"
! pip3 install -U google-cloud-aiplatform $USER_FLAG | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Install the latest GA version of *google-cloud-storage* library as well. | ! pip3 install -U google-cloud-storage $USER_FLAG | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Restart the kernelOnce you've installed the Vertex AI client library and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages. | import os
if not os.getenv("IS_TESTING"):
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True) | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Before you begin GPU runtime*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU** Set up your Google Cloud project**The following steps are required, regardless of your notebook environment.**1. [Select or create a Google Cloud proje... | PROJECT_ID = "[your-project-id]" # @param {type:"string"}
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:",... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
RegionYou can also change the `REGION` variable, which is used for operationsthroughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.- Americas: `us-central1`- Europe: `europe-west4`- Asia Pacific: `asia-east1`You may not use a multi-regi... | REGION = "us-central1" # @param {type: "string"} | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
TimestampIf you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial. | from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Authenticate your Google Cloud account**If you are using Vertex AI Notebooks**, your environment is already authenticated. Skip this step.**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.**Otherwise**, follow these steps:In the Cloud Consol... | import os
import sys
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your GCP account. This provides access to your
# Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
# If on AI Platform, then don't execute this code
if not os.p... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Create a Cloud Storage bucket**The following steps are required, regardless of your notebook environment.**When you submit a custom training job using the Vertex AI client library, you upload a Python packagecontaining your training code to a Cloud Storage bucket. Vertex AI runsthe code from this package. In this tuto... | BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"}
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]":
BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket. | ! gsutil mb -l $REGION $BUCKET_NAME | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Finally, validate access to your Cloud Storage bucket by examining its contents: | ! gsutil ls -al $BUCKET_NAME | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Set up variablesNext, set up some variables used throughout the tutorial. Import libraries and define constants Import Vertex AI client libraryImport the Vertex AI client library into our Python environment. | import os
import sys
import time
import google.cloud.aiplatform_v1 as aip
from google.protobuf import json_format
from google.protobuf.json_format import MessageToJson, ParseDict
from google.protobuf.struct_pb2 import Struct, Value | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Vertex AI constantsSetup up the following constants for Vertex AI:- `API_ENDPOINT`: The Vertex AI API service endpoint for dataset, model, job, pipeline and endpoint services.- `PARENT`: The Vertex AI location root path for dataset, model, job, pipeline and endpoint resources. | # API service endpoint
API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION)
# Vertex AI location root path for your dataset, model and endpoint resources
PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Hardware AcceleratorsSet the hardware accelerators (e.g., GPU), if any, for training and prediction.Set the variables `TRAIN_GPU/TRAIN_NGPU` and `DEPLOY_GPU/DEPLOY_NGPU` to use a container image supporting a GPU and the number of GPUs allocated to the virtual machine (VM) instance. For example, to use a GPU container ... | if os.getenv("IS_TESTING_TRAIN_GPU"):
TRAIN_GPU, TRAIN_NGPU = (
aip.AcceleratorType.NVIDIA_TESLA_K80,
int(os.getenv("IS_TESTING_TRAIN_GPU")),
)
else:
TRAIN_GPU, TRAIN_NGPU = (aip.AcceleratorType.NVIDIA_TESLA_K80, 1)
if os.getenv("IS_TESTING_DEPOLY_GPU"):
DEPLOY_GPU, DEPLOY_NGPU = (
... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Container (Docker) imageNext, we will set the Docker container images for training and prediction - TensorFlow 1.15 - `gcr.io/cloud-aiplatform/training/tf-cpu.1-15:latest` - `gcr.io/cloud-aiplatform/training/tf-gpu.1-15:latest` - TensorFlow 2.1 - `gcr.io/cloud-aiplatform/training/tf-cpu.2-1:latest` - `gcr.io/c... | if os.getenv("IS_TESTING_TF"):
TF = os.getenv("IS_TESTING_TF")
else:
TF = "2-1"
if TF[0] == "2":
if TRAIN_GPU:
TRAIN_VERSION = "tf-gpu.{}".format(TF)
else:
TRAIN_VERSION = "tf-cpu.{}".format(TF)
if DEPLOY_GPU:
DEPLOY_VERSION = "tf2-gpu.{}".format(TF)
else:
DEPLOY... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Machine TypeNext, set the machine type to use for training and prediction.- Set the variables `TRAIN_COMPUTE` and `DEPLOY_COMPUTE` to configure the compute resources for the VMs you will use for for training and prediction. - `machine type` - `n1-standard`: 3.75GB of memory per vCPU. - `n1-highmem`: 6.5GB of ... | if os.getenv("IS_TESTING_TRAIN_MACHINE"):
MACHINE_TYPE = os.getenv("IS_TESTING_TRAIN_MACHINE")
else:
MACHINE_TYPE = "n1-standard"
VCPU = "4"
TRAIN_COMPUTE = MACHINE_TYPE + "-" + VCPU
print("Train machine type", TRAIN_COMPUTE)
if os.getenv("IS_TESTING_DEPLOY_MACHINE"):
MACHINE_TYPE = os.getenv("IS_TESTING_... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
TutorialNow you are ready to start creating your own custom model and training for CIFAR10. Set up clientsThe Vertex AI client library works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the Vertex AI server.You will use different c... | # client options same for all services
client_options = {"api_endpoint": API_ENDPOINT}
def create_job_client():
client = aip.JobServiceClient(client_options=client_options)
return client
def create_model_client():
client = aip.ModelServiceClient(client_options=client_options)
return client
def cre... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Train a modelThere are two ways you can train a custom model using a container image:- **Use a Google Cloud prebuilt container**. If you use a prebuilt container, you will additionally specify a Python package to install into the container image. This Python package contains your code for training a custom model.- **U... | if TRAIN_GPU:
machine_spec = {
"machine_type": TRAIN_COMPUTE,
"accelerator_type": TRAIN_GPU,
"accelerator_count": TRAIN_NGPU,
}
else:
machine_spec = {"machine_type": TRAIN_COMPUTE, "accelerator_count": 0} | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Prepare your disk specification(optional) Now define the disk specification for your custom training job. This tells Vertex AI what type and size of disk to provision in each machine instance for the training. - `boot_disk_type`: Either SSD or Standard. SSD is faster, and Standard is less expensive. Defaults to SSD. ... | DISK_TYPE = "pd-ssd" # [ pd-ssd, pd-standard]
DISK_SIZE = 200 # GB
disk_spec = {"boot_disk_type": DISK_TYPE, "boot_disk_size_gb": DISK_SIZE} | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Examine the training package Package layoutBefore you start the training, you will look at how a Python package is assembled for a custom training job. When unarchived, the package contains the following directory/file layout.- PKG-INFO- README.md- setup.cfg- setup.py- trainer - \_\_init\_\_.py - task.pyThe files `s... | # Make folder for Python training script
! rm -rf custom
! mkdir custom
# Add package information
! touch custom/README.md
setup_cfg = "[egg_info]\n\ntag_build =\n\ntag_date = 0"
! echo "$setup_cfg" > custom/setup.cfg
setup_py = "import setuptools\n\nsetuptools.setup(\n\n install_requires=[\n\n 'tensorflow... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Task.py contentsIn the next cell, you write the contents of the training script task.py. We won't go into detail, it's just there for you to browse. In summary:- Get the directory where to save the model artifacts from the command line (`--model_dir`), and if not specified, then from the environment variable `AIP_MODE... | %%writefile custom/trainer/task.py
# Single, Mirror and Multi-Machine Distributed Training for CIFAR-10
import tensorflow_datasets as tfds
import tensorflow as tf
from tensorflow.python.client import device_lib
import argparse
import os
import sys
tfds.disable_progress_bar()
parser = argparse.ArgumentParser()
parser.... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Store training script on your Cloud Storage bucketNext, you package the training folder into a compressed tar ball, and then store it in your Cloud Storage bucket. | ! rm -f custom.tar custom.tar.gz
! tar cvf custom.tar custom
! gzip custom.tar
! gsutil cp custom.tar.gz $BUCKET_NAME/trainer_cifar10.tar.gz | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Define the worker pool specification for Model ANext, you define the worker pool specification for your custom training job. The worker pool specification will consist of the following:- `replica_count`: The number of instances to provision of this machine type.- `machine_spec`: The hardware specification.- `disk_spec... | JOB_NAME = "custom_job_A" + TIMESTAMP
MODEL_DIR = "{}/{}".format(BUCKET_NAME, JOB_NAME)
MODEL_DIR_A = MODEL_DIR
if not TRAIN_NGPU or TRAIN_NGPU < 2:
TRAIN_STRATEGY = "single"
else:
TRAIN_STRATEGY = "mirror"
EPOCHS = 20
STEPS = 100
DIRECT = True
if DIRECT:
CMDARGS = [
"--model-dir=" + MODEL_DIR,
... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Assemble a job specificationNow assemble the complete description for the custom job specification:- `display_name`: The human readable name you assign to this custom job.- `job_spec`: The specification for the custom job. - `worker_pool_specs`: The specification for the machine VM instances. - `base_output_dire... | if DIRECT:
job_spec = {"worker_pool_specs": worker_pool_spec}
else:
job_spec = {
"worker_pool_specs": worker_pool_spec,
"base_output_directory": {"output_uri_prefix": MODEL_DIR},
}
custom_job = {"display_name": JOB_NAME, "job_spec": job_spec} | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Train the modelNow start the training of your custom training job on Vertex AI. Use this helper function `create_custom_job`, which takes the following parameter:-`custom_job`: The specification for the custom job.The helper function calls job client service's `create_custom_job` method, with the following parameters:... | def create_custom_job(custom_job):
response = clients["job"].create_custom_job(parent=PARENT, custom_job=custom_job)
print("name:", response.name)
print("display_name:", response.display_name)
print("state:", response.state)
print("create_time:", response.create_time)
print("update_time:", respo... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Now get the unique identifier for the custom job you created. | # The full unique ID for the custom job
job_id = response.name
# The short numeric ID for the custom job
job_short_id = job_id.split("/")[-1]
print(job_id) | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Get information on a custom jobNext, use this helper function `get_custom_job`, which takes the following parameter:- `name`: The Vertex AI fully qualified identifier for the custom job.The helper function calls the job client service's`get_custom_job` method, with the following parameter:- `name`: The Vertex AI fully... | def get_custom_job(name, silent=False):
response = clients["job"].get_custom_job(name=name)
if silent:
return response
print("name:", response.name)
print("display_name:", response.display_name)
print("state:", response.state)
print("create_time:", response.create_time)
print("updat... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Wait for training to completeTraining the above model may take upwards of 20 minutes time.Once your model is done training, you can calculate the actual time it took to train the model by subtracting `end_time` from `start_time`. For your model, we will need to know the location of the saved model, which the Python sc... | while True:
response = get_custom_job(job_id, True)
if response.state != aip.JobState.JOB_STATE_SUCCEEDED:
print("Training job has not completed:", response.state)
model_path_to_deploy_A = None
if response.state == aip.JobState.JOB_STATE_FAILED:
break
else:
if not... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Define the worker pool specification for Model BNext, you define the worker pool specification for your custom training job. The worker pool specification will consist of the following:- `replica_count`: The number of instances to provision of this machine type.- `machine_spec`: The hardware specification.- `disk_spec... | JOB_NAME = "custom_job_B" + TIMESTAMP
MODEL_DIR = "{}/{}".format(BUCKET_NAME, JOB_NAME)
MODEL_DIR_B = MODEL_DIR
if not TRAIN_NGPU or TRAIN_NGPU < 2:
TRAIN_STRATEGY = "single"
else:
TRAIN_STRATEGY = "mirror"
EPOCHS = 20
STEPS = 100
DIRECT = True
if DIRECT:
CMDARGS = [
"--model-dir=" + MODEL_DIR,
... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Assemble a job specificationNow assemble the complete description for the custom job specification:- `display_name`: The human readable name you assign to this custom job.- `job_spec`: The specification for the custom job. - `worker_pool_specs`: The specification for the machine VM instances. - `base_output_dire... | if DIRECT:
job_spec = {"worker_pool_specs": worker_pool_spec}
else:
job_spec = {
"worker_pool_specs": worker_pool_spec,
"base_output_directory": {"output_uri_prefix": MODEL_DIR},
}
custom_job = {"display_name": JOB_NAME, "job_spec": job_spec} | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Train the modelNow start the training of your custom training job on Vertex AI. Use this helper function `create_custom_job`, which takes the following parameter:-`custom_job`: The specification for the custom job.The helper function calls job client service's `create_custom_job` method, with the following parameters:... | def create_custom_job(custom_job):
response = clients["job"].create_custom_job(parent=PARENT, custom_job=custom_job)
print("name:", response.name)
print("display_name:", response.display_name)
print("state:", response.state)
print("create_time:", response.create_time)
print("update_time:", respo... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Now get the unique identifier for the custom job you created. | # The full unique ID for the custom job
job_id = response.name
# The short numeric ID for the custom job
job_short_id = job_id.split("/")[-1]
print(job_id) | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Wait for training to completeTraining the above model may take upwards of 20 minutes time.Once your model is done training, you can calculate the actual time it took to train the model by subtracting `end_time` from `start_time`. For your model, we will need to know the location of the saved model, which the Python sc... | while True:
response = get_custom_job(job_id, True)
if response.state != aip.JobState.JOB_STATE_SUCCEEDED:
print("Training job has not completed:", response.state)
model_path_to_deploy_B = None
if response.state == aip.JobState.JOB_STATE_FAILED:
break
else:
if not... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Load the saved modelYour model instances are stored in a TensorFlow SavedModel format in a Cloud Storage bucket. Let's go ahead and load them from the Cloud Storage bucket, and then you can do some things, like evaluate the model, and do a prediction.To load, you use the TF.Keras `model.load_model()` method passing it... | import tensorflow as tf
model_A = tf.keras.models.load_model(MODEL_DIR_A)
model_B = tf.keras.models.load_model(MODEL_DIR_B) | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Evaluate the modelNow find out how good the model is. Load evaluation dataYou will load the CIFAR10 test (holdout) data from `tf.keras.datasets`, using the method `load_data()`. This will return the dataset as a tuple of two elements. The first element is the training data and the second is the test data. Each element... | import numpy as np
from tensorflow.keras.datasets import cifar10
(_, _), (x_test, y_test) = cifar10.load_data()
x_test = (x_test / 255.0).astype(np.float32)
print(x_test.shape, y_test.shape) | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Adding client instance to model outputs.For A/B testing, each model needs to output two items in addition to the prediction:- The model instance, whether it is A or B.- An identifier for the client session where the prediction request originates from.The model identifier is already baked into the prediction result ret... | import tensorflow as tf
from tensorflow.keras import Input, Model
from tensorflow.keras.layers import Lambda
softmax = model_A.outputs[0]
outputs = Lambda(lambda z: (z, tf.convert_to_tensor([tf.constant(0)])))(softmax)
wrapper_model_A = Model(model_A.inputs, outputs)
softmax = model_B.outputs[0]
outputs = Lambda(lamb... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Local PredictionLet's now do a local prediction with one of your wrapper A/B models. You will pass three instances (images) for prediction, and get back:- The softmax prediction for each instance request.- The model A/B identifier. In this case 0 for A. | wrapper_model_A.predict(x_test[0:3]) | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Serving function for image dataTo pass images to the prediction service, you encode the compressed (e.g., JPEG) image bytes into base 64 -- which makes the content safe from modification while transmitting binary data over the network. Since this deployed model expects input data as raw (uncompressed) bytes, you need ... | CONCRETE_INPUT = "numpy_inputs"
def _preprocess(bytes_input):
decoded = tf.io.decode_jpeg(bytes_input, channels=3)
decoded = tf.image.convert_image_dtype(decoded, tf.float32)
resized = tf.image.resize(decoded, size=(32, 32))
rescale = tf.cast(resized / 255.0, tf.float32)
return rescale
@tf.funct... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Upload the modelUse this helper function `upload_model` to upload your model, stored in SavedModel format, up to the `Model` service, which will instantiate a Vertex AI `Model` resource instance for your model. Once you've done that, you can use the `Model` resource instance in the same way as any other Vertex AI `Mod... | IMAGE_URI = DEPLOY_IMAGE
def upload_model(display_name, image_uri, model_uri):
model = {
"display_name": display_name,
"metadata_schema_uri": "",
"artifact_uri": model_uri,
"container_spec": {
"image_uri": image_uri,
"command": [],
"args": [],
... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Deploy the `Model` resourceNow deploy the trained Vertex AI custom `Model` resource. This requires two steps:1. Create an `Endpoint` resource for deploying the `Model` resource to.2. Deploy the `Model` resource to the `Endpoint` resource. Create an `Endpoint` resourceUse this helper function `create_endpoint` to crea... | ENDPOINT_NAME = "cifar10_endpoint-" + TIMESTAMP
def create_endpoint(display_name):
endpoint = {"display_name": display_name}
response = clients["endpoint"].create_endpoint(parent=PARENT, endpoint=endpoint)
print("Long running operation:", response.operation.name)
result = response.result(timeout=300)... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Now get the unique identifier for the `Endpoint` resource you created. | # The full unique ID for the endpoint
endpoint_id = result.name
# The short numeric ID for the endpoint
endpoint_short_id = endpoint_id.split("/")[-1]
print(endpoint_id) | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Compute instance scalingYou have several choices on scaling the compute instances for handling your online prediction requests:- Single Instance: The online prediction requests are processed on a single compute instance. - Set the minimum (`MIN_NODES`) and maximum (`MAX_NODES`) number of compute instances to one.- Ma... | MIN_NODES = 1
MAX_NODES = 1 | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Deploy `Model` resource to the `Endpoint` resourceUse this helper function `deploy_model` to deploy the `Model` resource to the `Endpoint` resource you created for serving predictions, with the following parameters:- `model`: The Vertex AI fully qualified model identifier of the model to upload (deploy) from the train... | DEPLOYED_NAME = "cifar10_deployed-" + TIMESTAMP
def deploy_model(
model, deployed_model_display_name, endpoint, traffic_split={"0": 100}
):
# Accelerators can be used only if the model specifies a GPU image.
if DEPLOY_GPU:
machine_spec = {
"machine_type": DEPLOY_COMPUTE,
"... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Make a online prediction requestNow do a online prediction to your deployed model. Get test itemYou will use an example out of the test (holdout) portion of the dataset as a test item. | test_image = x_test[0]
test_label = y_test[0]
print(test_image.shape) | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Prepare the request contentYou are going to send the CIFAR10 image as compressed JPG image, instead of the raw uncompressed bytes:- `cv2.imwrite`: Use openCV to write the uncompressed image to disk as a compressed JPEG image. - Denormalize the image data from \[0,1) range back to [0,255). - Convert the 32-bit floating... | import base64
import cv2
cv2.imwrite("tmp.jpg", (test_image * 255).astype(np.uint8))
bytes = tf.io.read_file("tmp.jpg")
b64str = base64.b64encode(bytes.numpy()).decode("utf-8") | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Send the prediction requestOk, now you have a test image. Use this helper function `predict_image`, which takes the following parameters:- `image`: The test image data as a numpy array.- `endpoint`: The Vertex AI fully qualified identifier for the `Endpoint` resource where the `Model` resource was deployed to.- `param... | def predict_image(image, endpoint, parameters_dict):
# The format of each instance should conform to the deployed model's prediction input schema.
instances_list = [{serving_input: {"b64": image}}]
instances = [json_format.ParseDict(s, Value()) for s in instances_list]
response = clients["prediction"].... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
Cleaning upTo clean up all GCP resources used in this project, you can [delete the GCPproject](https://cloud.google.com/resource-manager/docs/creating-managing-projectsshutting_down_projects) you used for the tutorial.Otherwise, you can delete the individual resources you created in this tutorial:- Dataset- Pipeline- ... | delete_dataset = True
delete_pipeline = True
delete_model = True
delete_endpoint = True
delete_batchjob = True
delete_customjob = True
delete_hptjob = True
delete_bucket = True
# Delete the dataset using the Vertex AI fully qualified identifier for the dataset
try:
if delete_dataset and "dataset_id" in globals():
... | _____no_output_____ | Apache-2.0 | ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_image_classification_online_ab_testing.ipynb | rastringer/ai-platform-samples |
This is Tensorflow 2 implementation of GoogleNet model based on the paper in the below linkhttps://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43022.pdfFew of the major differences between the paper and this implementation are1. Number of categories for classification here is 10 compared t... | #For any array manipulations
import numpy as np
#For plotting graphs
import matplotlib.pyplot as plt
# For loading data from the file system
import os
# For randomly selecting data from the dataset
import random
# For displaying the confusion matrix in a pretty way
import pandas
# loading tensorflow packages
import... | 2.5.0
| CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Initializations | from tensorflow.python.client import device_lib
def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU']
print("devices =" , tf.config.list_physical_devices())
print(get_available_gpus())
# Shape of the input images... | _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Data Loading and Preprocessing Procuring the dataset | path='/content/Linnaeus 5 256X256'
# Check if the folder with the dataset already exists, if not copy it from the saved location
if not os.path.isdir(path):
!cp '/content/drive/MyDrive/MachineLearning/Linnaeus 5 256X256.rar' '/content/'
get_ipython().system_raw("unrar x '/content/Linnaeus 5 256X256.rar'")
categ... | 5 categories found = ['dog', 'berry', 'other', 'bird', 'flower']
| CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Training and Validation Datasets |
train_image_dataset = tf.keras.preprocessing.image_dataset_from_directory(
os.path.join(path, 'train')
, labels='inferred'
, label_mode='categorical'
, class_names=categories
, batch_size=batch_size
, image_size=(256, 256)
, shuffle=True
, seed=2
, validation_spl... | images = (100, 224, 224, 3)
labels = <class 'tensorflow.python.framework.ops.EagerTensor'>
| CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Test Data | test_image_dataset = tf.keras.preprocessing.image_dataset_from_directory(
os.path.join(path, 'test')
, labels='inferred'
, label_mode='categorical'
, class_names=categories
, batch_size=batch_size
, image_size=(256, 256)
, seed=2
)
def test_data_crop_images(images, labels):... | Found 2000 files belonging to 5 classes.
| CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Building the GoogleNet Architecture Define the inception block | def inception_block(input, intermediate_filter_size, output_filter_size
, kernel_initializer, bias_initializer
, use_bias=True, name_prefix=''):
'''
input = input tensor that has to be opeerated on
intermediate_filter_size = dictionary that keys 3 and 5
{3: filter size... | _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Defining the Auxillary Branch block | def auxillary_branch(input, num_classes, kernel_initializer , bias_initializer
, filter_size = 128
, use_bias=True, name_prefix=''):
#initializer = RandomNormal(mean=0.5, stddev=0.1, seed = 7)
avg_pool = AveragePooling2D(pool_size=5, strides=3, padding... | _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Define the actual model | def build_googleNet(input_shape, size_factor=64, activation='elu'
, use_bias=True, num_classes=10):
'''
input_shape = tuple of 3 numbers (height, width, channels)
batch_size = number of images per batch
size_factor = int (default 64). As per the paper, this should be 64.
Since all the ... | Model: "googleNet"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
main... | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Model Figure | tf.keras.utils.plot_model(model) | _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Define Callbacks & Optimizer Learning Rate Modification | def lr_schedule(epoch, learning_rate):
#The paper talks about reducing the learning rate by 4% every 8 epochs
#Checking if 8 epochs are complete
if epoch > 7 and epoch%8 == 0 :
# Reducing the learning rate by 4%
#print("lr_schedule: epoch =",epoch)
return learning_rate* 0.96
else:
return learn... | _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Checkpoint Definition | checkpoint = tf.keras.callbacks.ModelCheckpoint(filepath = checkpoint_filePath
, monitor='val_loss'
, verbose = 1
, save_best_only = True
... | _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
EarlyStopping Definition | earlyStopper = tf.keras.callbacks.EarlyStopping(monitor='val_loss'
, min_delta = 0.0001
, patience = 9
, verbose=1
, restore_bes... | _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Define Callbacks list | callbacks = [earlyStopper
, checkpoint
, lrScheduler] | _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Define Optimizer | # The paper calls for an SGD with momentum of 0.9
optimizer = tf.keras.optimizers.SGD(learning_rate=1e-3, momentum=0.9)
#optimizer = tf.keras.optimizers.Adam(learning_rate=1e-5) | _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Compile the Model | #First phase of training will be with aux1 branch as output and ignoring the rest of the model
#aux1_model = Model(inputs=model.get_layer('main_input').input, outputs=model.get_layer('aux1_output').output)
#aux1_model.summary()
#aux1_model.reset_states()
model.compile(optimizer = optimizer
, loss = 'cat... | _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Train the Model | metrics = model.fit(training_datasource
, batch_size = batch_size
, epochs= 50
, callbacks = callbacks
, validation_data = validation_datasource
, shuffle=True
)
#tf.keras.models.save_model(model, checkpoint_filePath, save_format='h5') | _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Loss and Accuracy Plots |
acc = metrics.history['accuracy']
val_acc = metrics.history['val_accuracy']
loss = metrics.history['loss']
val_loss = metrics.history['val_loss']
epochs_range = range(len(metrics.history['accuracy']))
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epo... | _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Test the Model | predictions = []
actuals=[]
for i, (images, labels) in enumerate( test_datasource):
pred = model(images)
for j in range(len(labels)):
actuals.append( labels[j])
predictions.append(pred[j])
# Printing a few labels and predictions to ensure that there are no dead-Relus
for j in range(10):
print(labels[j].... | [0. 0. 0. 1. 0.] [5.2678269e-01 4.5223912e-04 1.5960732e-01 3.1243265e-01 7.2512066e-04]
[1. 0. 0. 0. 0.] [9.3688345e-01 3.9315761e-05 4.2963952e-02 2.0080591e-02 3.2674830e-05]
[1. 0. 0. 0. 0.] [5.6217247e-01 3.2935925e-05 6.1456640e-03 4.3134734e-01 3.0162817e-04]
[0. 1. 0. 0. 0.] [2.6929042e-08 9.9104989e-01... | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Confusion Matrix | import pandas as pd
pd.DataFrame(tf.math.confusion_matrix(
np.argmax(actuals, axis=1), np.argmax(predictions, axis=1), num_classes=num_classes, dtype=tf.dtypes.int32).numpy()
, columns = test_image_dataset.class_names
, index = test_image_dataset.class_names)
| _____no_output_____ | CC0-1.0 | DeepLearningForVisionSystems_Ch5_InceptionGoogleNet.ipynb | mkkadambi/machine-learning |
Implementing the Gradient Descent AlgorithmIn this lab, we'll implement the basic functions of the Gradient Descent algorithm to find the boundary in a small dataset. First, we'll start with some functions that will help us plot and visualize the data. | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#Some helper functions for plotting and drawing lines
def plot_points(X, y):
admitted = X[np.argwhere(y==1)]
rejected = X[np.argwhere(y==0)]
plt.scatter([s[0][0] for s in rejected], [s[0][1] for s in rejected], s = 25, color = 'blue', ... | _____no_output_____ | MIT | 4 - Neural Networks/1. Introduction To Neural Nets/1. Gradient Descent/GradientDescent.ipynb | 2series/Artificial-Intelligence |
Reading and plotting the data | data = pd.read_csv('data.csv', header=None)
X = np.array(data[[0,1]])
y = np.array(data[2])
plot_points(X,y)
plt.show() | _____no_output_____ | MIT | 4 - Neural Networks/1. Introduction To Neural Nets/1. Gradient Descent/GradientDescent.ipynb | 2series/Artificial-Intelligence |
TODO: Implementing the basic functionsHere is your turn to shine. Implement the following formulas, as explained in the text.- Sigmoid activation function$$\sigma(x) = \frac{1}{1+e^{-x}}$$- Output (prediction) formula$$\hat{y} = \sigma(w_1 x_1 + w_2 x_2 + b)$$- Error function$$Error(y, \hat{y}) = - y \log(\hat{y}) - (... | # Implement the following functions
# Activation (sigmoid) function
def sigmoid(x):
return (1 / (1 + np.exp(-x)))
# Output (prediction) formula
def output_formula(features, weights, bias):
return sigmoid(np.matmul(features, weights) + bias)
# Error (log-loss) formula
def error_formula(y, output):
re... | _____no_output_____ | MIT | 4 - Neural Networks/1. Introduction To Neural Nets/1. Gradient Descent/GradientDescent.ipynb | 2series/Artificial-Intelligence |
Training functionThis function will help us iterate the gradient descent algorithm through all the data, for a number of epochs. It will also plot the data, and some of the boundary lines obtained as we run the algorithm. | np.random.seed(44)
epochs = 100
learnrate = 0.01
def train(features, targets, epochs, learnrate, graph_lines=False):
errors = []
n_records, n_features = features.shape
last_loss = None
weights = np.random.normal(scale=1 / n_features**.5, size=n_features)
bias = 0
for e in range(epochs):
... | _____no_output_____ | MIT | 4 - Neural Networks/1. Introduction To Neural Nets/1. Gradient Descent/GradientDescent.ipynb | 2series/Artificial-Intelligence |
Time to train the algorithm!When we run the function, we'll obtain the following:- 10 updates with the current training loss and accuracy- A plot of the data and some of the boundary lines obtained. The final one is in black. Notice how the lines get closer and closer to the best fit, as we go through more epochs.- A ... | weights, bias, errors = train(X, y, epochs, learnrate, True)
train_plot(X, y, weights,bias)
train_err(errors) | _____no_output_____ | MIT | 4 - Neural Networks/1. Introduction To Neural Nets/1. Gradient Descent/GradientDescent.ipynb | 2series/Artificial-Intelligence |
hard-coded argumentsexplain GCN model | # get args from main_gnn CLI
class Argument(object):
name = "args"
args = Argument()
args.batch_size = 256
args.num_workers = 0
args.num_layers = 5
args.emb_dim = 600
args.drop_ratio = 0
args.graph_pooling = "sum"
args.checkpoint_dir = "models/gin-virtual/checkpoint"
args.device = 0
device = torch.device("cuda... | _____no_output_____ | MIT | examples/lsc/pcqm4m/.ipynb_checkpoints/triplet-loss-checkpoint.ipynb | edwardelson/ogb |
load model | from gnn import GNN
"""
LOAD Checkpoint data
"""
checkpoint = torch.load(os.path.join(args.checkpoint_dir, 'checkpoint.pt'))
checkpoint.keys()
gnn_name = "gin-virtual"
gnn_type = "gin"
virtual_node = True
model = GNN(gnn_type = gnn_type, virtual_node = virtual_node, **shared_params).to(device)
model.load_state_dict(che... | _____no_output_____ | MIT | examples/lsc/pcqm4m/.ipynb_checkpoints/triplet-loss-checkpoint.ipynb | edwardelson/ogb |
load data | ### importing OGB-LSC
from ogb.lsc import PygPCQM4MDataset, PCQM4MEvaluator
dataset = PygPCQM4MDataset(root = 'dataset/')
split_idx = dataset.get_idx_split()
split_idx["train"], split_idx["test"], split_idx["valid"]
valid_loader = DataLoader(dataset[split_idx["valid"]], batch_size=args.batch_size, shuffle=False, num_w... | _____no_output_____ | MIT | examples/lsc/pcqm4m/.ipynb_checkpoints/triplet-loss-checkpoint.ipynb | edwardelson/ogb |
triplet loss | """
load triplet dataset
"""
name = "valid"
anchor_loader = DataLoader(dataset[split_idx[name]], batch_size=args.batch_size, shuffle=True, num_workers = args.num_workers)
positive_loader = DataLoader(dataset[split_idx[name]], batch_size=args.batch_size, shuffle=True, num_workers = args.num_workers)
negative_loader = ... | _____no_output_____ | MIT | examples/lsc/pcqm4m/.ipynb_checkpoints/triplet-loss-checkpoint.ipynb | edwardelson/ogb |
predict | batch = list(valid_loader)[0]
data = batch[0]
data
batch = batch.to(device)
with torch.no_grad():
pred = model(batch).view(-1,)
pred
y_true = data.y.item()
y_pred = pred.item()
y_true, y_pred | _____no_output_____ | MIT | examples/lsc/pcqm4m/.ipynb_checkpoints/triplet-loss-checkpoint.ipynb | edwardelson/ogb |
plot sample | import networkx as nx
import matplotlib.pyplot as plt
def plotGraph(data, y_pred, y_true, ax, printnodelabel=False, printedgelabel=False):
edges = data.edge_index.T.tolist()
edges = np.array(edges)
edges = [(x[0][0], x[0][1], {"feat": str(x[1])}) for x in list(zip(edges.tolist(), data.edge_attr.tolist()))]... | _____no_output_____ | MIT | examples/lsc/pcqm4m/.ipynb_checkpoints/triplet-loss-checkpoint.ipynb | edwardelson/ogb |
perturb edge feature edge (5, 6, 2) possible dimensions | import ogb.utils as utils
edgeFeatDims = utils.features.get_bond_feature_dims()
edgeFeatDims
perturb_data_list = []
for _ in range(5000):
# clone original data
pData = data.clone()
# create random noise
randomNoise = np.random.randint(low=-4, high=4, size=data.edge_attr.shape)
randomNoise = to... | _____no_output_____ | MIT | examples/lsc/pcqm4m/.ipynb_checkpoints/triplet-loss-checkpoint.ipynb | edwardelson/ogb |
given fixed node features and topology, perturbing edge features don't disturb the output much perturb node features | nodeDims = utils.features.get_atom_feature_dims()
nodeDims
perturb_data_list = []
for _ in range(1000):
# clone original data
pData = data.clone()
# create random noise
randomNoise = np.random.randint(low=-1, high=1, size=data.x.shape)
randomNoise = torch.tensor(randomNoise)
# add edge_at... | _____no_output_____ | MIT | examples/lsc/pcqm4m/.ipynb_checkpoints/triplet-loss-checkpoint.ipynb | edwardelson/ogb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.