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 |
|---|---|---|---|---|---|
Determine ratio of positive ADE phrases compared to total dataset | df['label'].sum()/len(df) | _____no_output_____ | MIT | 1_data_prep.ipynb | marshmellow77/adverse-drug-effect-detection |
Initialise Sagemaker variables and create S3 bucket | from sagemaker.huggingface.processing import HuggingFaceProcessor
import sagemaker
from sagemaker import get_execution_role
sess = sagemaker.Session()
role = sagemaker.get_execution_role()
bucket = f"az-ade-{sess.account_id()}"
sess._create_s3_bucket_if_it_does_not_exist(bucket_name=bucket, region=sess._region_name) | _____no_output_____ | MIT | 1_data_prep.ipynb | marshmellow77/adverse-drug-effect-detection |
Save the name of the S3 bucket for later sessions | %store bucket | _____no_output_____ | MIT | 1_data_prep.ipynb | marshmellow77/adverse-drug-effect-detection |
Set up processing job | hf_processor = HuggingFaceProcessor(
role=role,
instance_type="ml.p3.2xlarge",
transformers_version='4.6',
base_job_name="az-ade",
pytorch_version='1.7',
instance_count=1,
)
from sagemaker.processing import ProcessingInput, ProcessingOutput
outputs=[
ProcessingOutput(output_name="train_... | _____no_output_____ | MIT | 1_data_prep.ipynb | marshmellow77/adverse-drug-effect-detection |
IllusTrip: Text to Video 3DPart of [Aphantasia](https://github.com/eps696/aphantasia) suite, made by Vadim Epstein [[eps696](https://github.com/eps696)] Based on [CLIP](https://github.com/openai/CLIP) + FFT/pixel ops from [Lucent](https://github.com/greentfrapp/lucent). 3D part by [deKxi](https://twitter.com/deKxi), ... | #@title General setup
!pip install ftfy==5.8 transformers
!pip install gputil ffpb
try:
!pip3 install googletrans==3.1.0a0
from googletrans import Translator, constants
translator = Translator()
except: pass
# !apt-get -qq install ffmpeg
work_dir = '/content/illustrip'
import os
os.makedirs(work_dir, exist_o... | _____no_output_____ | MIT | IllusTrip3D.ipynb | z-tasker/aphantasia |
**`content`** (what to draw) is your primary input; **`style`** (how to draw) is optional, if you want to separate such descriptions. If you load text file[s], the imagery will interpolate from line to line (ensure equal line counts for content and style lists, for their accordance). | #@title Google Drive [optional]
#@markdown Run this cell, if you want to store results on your Google Drive.
using_GDrive = True#@param{type:"boolean"}
if using_GDrive:
import os
from google.colab import drive
if not os.path.isdir('/G/MyDrive'):
drive.mount('/G', force_remount=True)
gdir = '/G/MyDrive'... | _____no_output_____ | MIT | IllusTrip3D.ipynb | z-tasker/aphantasia |
**`FFT`** method uses inverse FFT representation of the image. It allows flexible motion, but is either blurry (if smoothed) or noisy (if not). **`RGB`** method directly optimizes image pixels (without FFT parameterization). It's more clean and stable, when zooming in. There are few choices for CLIP `model` (results ... | #@title Run this cell to override settings, if needed
#@markdown [to roll back defaults, run "Main settings" cell again]
style_power = 1. #@param {type:"number"}
overscan = True #@param {type:"boolean"}
align = 'overscan' if overscan else 'uniform'
interpolate_topics = True #@param {type:"boolean"}
#@markdown > Look
... | _____no_output_____ | MIT | IllusTrip3D.ipynb | z-tasker/aphantasia |
`style_power` controls the strength of the style descriptions, comparing to the main input. `overscan` provides better frame coverage (needed for RGB method). `interpolate_topics` changes the subjects smoothly, otherwise they're switched by cut, making sharper transitions. Decrease **`samples`** if you face OOM (it'... | ### deKxi:: This whole cell contains most of whats needed,
# with just a few changes to hook it up via frame_transform
# (also glob_step now as global var)
# I highly recommend performing the frame transformations and depth *after* saving,
# (or just the depth warp if you prefer to keep the other affines as they are... | _____no_output_____ | MIT | IllusTrip3D.ipynb | z-tasker/aphantasia |
Generate | #@title Generate
if aug_transform == 'elastic':
trform_f = transforms.transforms_elastic
sample_decrease *= 0.95
elif aug_transform == 'custom':
trform_f = transforms.transforms_custom
sample_decrease *= 0.95
else:
trform_f = transforms.normalize()
if enforce != 0:
sample_decrease *= 0.5
samples = int(... | _____no_output_____ | MIT | IllusTrip3D.ipynb | z-tasker/aphantasia |
If video is not auto-downloaded after generation (for whatever reason), run this cell to do that: | files.download(tempdir + '.mp4')
if save_depth and DepthStrength > 0:
files.download(depthdir + '.mp4') | _____no_output_____ | MIT | IllusTrip3D.ipynb | z-tasker/aphantasia |
1) Get data in a pandas.DataFrame and plot it using matplotlib.pyplot | # Get data
# 1) directement sous forme de list python
GPU = [2048,2048,4096,4096,3072,6144,6144,8192,8192,8192,8192,11264,11264]
prix = [139.96,149.95,184.96,194.95,299.95,332.95,359.95,459.95,534.95,569.95,699.95,829.96,929.95]
data = pd.DataFrame({'x1':GPU,'y':prix})
# Remarque: On peut également enregistrer des d... | _____no_output_____ | MIT | notebook/linearRegression/GPUprice.ipynb | lbeaucourt/SIGMA-machine-learning |
2) Contruire un modéle pour nos données | # Définir notre hypothèse (fonction)
def hypothesis(x,theta):
return np.dot(x,theta)
# On génére aléatoirement une valeur de départ pour le paramètre theta1 de notre modèle
theta = np.random.rand()
# Fonction pour générer la droite représentant notre modèle
def getHypothesisForPLot(theta):
return pd.DataFram... | _____no_output_____ | MIT | notebook/linearRegression/GPUprice.ipynb | lbeaucourt/SIGMA-machine-learning |
3) Tester la pertinence de notre modèle: la fonction de coût | data.shape
# On définit notre fonction de coût: somme quadratique (eg: on somme les carré)
def costFunction(y,yhat):
return np.power(yhat - y,2).sum()*(2/y.shape[0])
# Prix prédis par notre modèle (avec un theta choisi pour illustrer) pour chaque exemple
theta = 0.07
yhat = hypothesis(data.x1,theta)
#Comment fonc... | _____no_output_____ | MIT | notebook/linearRegression/GPUprice.ipynb | lbeaucourt/SIGMA-machine-learning |
4) À quoi ressemble J(theta) en fonction de theta1 | # Calculons (brutalement) la valeur de J(theta) dans un intervale de valeur de theta1
# pour observer la forme de notre fonction de coût que nous allons chercher à minimiser
thetaRange = np.arange(-0.8,1,0.01)
costFctEvol = pd.DataFrame({'theta':thetaRange,
'cost':[costFunction(data.y,... | _____no_output_____ | MIT | notebook/linearRegression/GPUprice.ipynb | lbeaucourt/SIGMA-machine-learning |
5) La descente de Gradient | # La descente de gradient utilise la notion de dérivée,
# illustrée ici avec la fonction carré (qui doit nous en rappeler une autre!)
def fct(x):
return np.power(x,2)
def fctDeriv(x):
return 2*x
fctCarre = pd.DataFrame({'x':np.arange(-10,10,0.1),'y':[fct(x) for x in np.arange(-10,10,0.1)]})
fctCarreD =... | _____no_output_____ | MIT | notebook/linearRegression/GPUprice.ipynb | lbeaucourt/SIGMA-machine-learning |
6) Conclusion | # Afficher les résultat:
print('La descente de gradient a été réalisé en %i étapes.' % count)
print('theta = %f' % theta)
print('J(theta) = %f' % costFunction(data.y,yhat))
# Faisons une prédiction ....
newGPUs = [3072*1.5,11264*1.2]
for newGPU in newGPUs:
print("Notre nouvelle carte de %i Mo de GPU pourra se vend... | _____no_output_____ | MIT | notebook/linearRegression/GPUprice.ipynb | lbeaucourt/SIGMA-machine-learning |
7) Choix du taux d'apprentissage lambda | # On utilise donc une valeur de départ pour theta généré aléatoirement entre 0 et 1,
# la valeur du learning rate est fixé à 0.00000003
# Epsilon correspond à la précision que l'on veut atteindre pour stopper la descente de gradient
thetaInit = np.random.rand()
yhat1 = hypothesis(data.x1,thetaInit)
yhat2 = hypothe... | _____no_output_____ | MIT | notebook/linearRegression/GPUprice.ipynb | lbeaucourt/SIGMA-machine-learning |
Vertex client library: Custom training tabular regression model with pipeline for online prediction with training pipeline Run in Colab View on GitHub OverviewThis tutorial demonstrates how to use the Vertex client library for Python to train and deploy a custom tabular regres... | import os
import sys
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install -U google-cloud-aiplatform $USER_FLAG | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Restart the kernelOnce you've installed the Vertex client library and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages. | 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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
RegionYou can also change the `REGION` variable, which is used for operationsthroughout the rest of this notebook. Below are regions supported for Vertex. 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-regiona... | REGION = "us-central1" # @param {type: "string"} | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Authenticate your Google Cloud account**If you are using Google Cloud Notebook**, 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 Cons... | # 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 Google Cloud Notebook, then don't execute this code
if not os.path.exists("... | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 client library, you upload a Python packagecontaining your training code to a Cloud Storage bucket. Vertex runsthe code from this package. In this tutorial, ... | 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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Finally, validate access to your Cloud Storage bucket by examining its contents: | ! gsutil ls -al $BUCKET_NAME | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Set up variablesNext, set up some variables used throughout the tutorial. Import libraries and define constants Import Vertex client libraryImport the Vertex client library into our Python environment. | import time
from google.cloud.aiplatform import gapic 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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Vertex constantsSetup up the following constants for Vertex:- `API_ENDPOINT`: The Vertex API service endpoint for dataset, model, job, pipeline and endpoint services.- `PARENT`: The Vertex location root path for dataset, model, job, pipeline and endpoint resources. | # API service endpoint
API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION)
# Vertex location root path for your dataset, model and endpoint resources
PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
CustomJob constantsSet constants unique to CustomJob training:- Dataset Training Schemas: Tells the `Pipeline` resource service the task (e.g., classification) to train the model for. | CUSTOM_TASK_GCS_PATH = (
"gs://google-cloud-aiplatform/schema/trainingjob/definition/custom_task_1.0.0.yaml"
) | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
TutorialNow you are ready to start creating your own custom model and training for Boston Housing. Set up clientsThe Vertex 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 server.You will use different ... | # client options same for all services
client_options = {"api_endpoint": API_ENDPOINT}
def create_model_client():
client = aip.ModelServiceClient(client_options=client_options)
return client
def create_pipeline_client():
client = aip.PipelineServiceClient(client_options=client_options)
return client... | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Prepare your disk specification(optional) Now define the disk specification for your custom training job. This tells Vertex 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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Define the worker pool specificationNext, 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` : (optiona... | JOB_NAME = "custom_job_" + TIMESTAMP
MODEL_DIR = "{}/{}".format(BUCKET_NAME, JOB_NAME)
if not TRAIN_NGPU or TRAIN_NGPU < 2:
TRAIN_STRATEGY = "single"
else:
TRAIN_STRATEGY = "mirror"
EPOCHS = 20
STEPS = 100
PARAM_FILE = BUCKET_NAME + "/params.txt"
DIRECT = True
if DIRECT:
CMDARGS = [
"--model-dir... | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Task.py contentsIn the next cell, you write the contents of the training script task.py. I 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_MODEL... | %%writefile custom/trainer/task.py
# Single, Mirror and Multi-Machine Distributed Training for Boston Housing
import tensorflow_datasets as tfds
import tensorflow as tf
from tensorflow.python.client import device_lib
import numpy as np
import argparse
import os
import sys
tfds.disable_progress_bar()
parser = argparse... | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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_boston.tar.gz | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Train the model using a `TrainingPipeline` resourceNow start training of your custom training job using a training pipeline on Vertex. To train the your custom model, do the following steps:1. Create a Vertex `TrainingPipeline` resource for the `Dataset` resource.2. Execute the pipeline to start the training. Create a... | from google.protobuf import json_format
from google.protobuf.struct_pb2 import Value
MODEL_NAME = "custom_pipeline-" + TIMESTAMP
PIPELINE_DISPLAY_NAME = "custom-training-pipeline" + TIMESTAMP
training_task_inputs = json_format.ParseDict(
{"workerPoolSpecs": worker_pool_spec}, Value()
)
pipeline = {
"display_n... | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Create the training pipelineUse this helper function `create_pipeline`, which takes the following parameter:- `training_pipeline`: the full specification for the pipeline training job.The helper function calls the pipeline client service's `create_pipeline` method, which takes the following parameters:- `parent`: The ... | def create_pipeline(training_pipeline):
try:
pipeline = clients["pipeline"].create_training_pipeline(
parent=PARENT, training_pipeline=training_pipeline
)
print(pipeline)
except Exception as e:
print("exception:", e)
return None
return pipeline
response... | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Now save the unique identifier of the training pipeline you created. | # The full unique ID for the pipeline
pipeline_id = response.name
# The short numeric ID for the pipeline
pipeline_short_id = pipeline_id.split("/")[-1]
print(pipeline_id) | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Get information on a training pipelineNow get pipeline information for just this training pipeline instance. The helper function gets the job information for just this job by calling the the job client service's `get_training_pipeline` method, with the following parameter:- `name`: The Vertex fully qualified pipeline... | def get_training_pipeline(name, silent=False):
response = clients["pipeline"].get_training_pipeline(name=name)
if silent:
return response
print("pipeline")
print(" name:", response.name)
print(" display_name:", response.display_name)
print(" state:", response.state)
print(" training... | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
DeploymentTraining 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, you will need to know the fully qualified Vertex Model resource identifier, which the pipeli... | while True:
response = get_training_pipeline(pipeline_id, True)
if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED:
print("Training job has not completed:", response.state)
model_to_deploy_id = None
if response.state == aip.PipelineState.PIPELINE_STATE_FAILED:
ra... | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Load the saved modelYour model is stored in a TensorFlow SavedModel format in a Cloud Storage bucket. Now load it 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 the Cloud Storage path wher... | import tensorflow as tf
model = tf.keras.models.load_model(MODEL_DIR) | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Evaluate the modelNow let's find out how good the model is. Load evaluation dataYou will load the Boston Housing 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.... | import numpy as np
from tensorflow.keras.datasets import boston_housing
(_, _), (x_test, y_test) = boston_housing.load_data(
path="boston_housing.npz", test_split=0.2, seed=113
)
def scale(feature):
max = np.max(feature)
feature = (feature / max).astype(np.float32)
return feature
# Let's save one d... | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Perform the model evaluationNow evaluate how well the model in the custom job did. | model.evaluate(x_test, y_test) | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Upload the model for servingNext, you will upload your TF.Keras model from the custom job to Vertex `Model` service, which will create a Vertex `Model` resource for your custom model. During upload, you need to define a serving function to convert data to the format your model expects. If you send encoded data to Vert... | loaded = tf.saved_model.load(model_path_to_deploy)
serving_input = list(
loaded.signatures["serving_default"].structured_input_signature[1].keys()
)[0]
print("Serving function input:", serving_input) | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 `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 `Model` re... | 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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Get `Model` resource informationNow let's get the model information for just your model. Use this helper function `get_model`, with the following parameter:- `name`: The Vertex unique identifier for the `Model` resource.This helper function calls the Vertex `Model` client service's method `get_model`, with the followi... | def get_model(name):
response = clients["model"].get_model(name=name)
print(response)
get_model(model_to_deploy_id) | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Deploy the `Model` resourceNow deploy the trained Vertex 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 create ... | ENDPOINT_NAME = "boston_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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 fully qualified model identifier of the model to upload (deploy) from the training... | DEPLOYED_NAME = "boston_deployed-" + TIMESTAMP
def deploy_model(
model, deployed_model_display_name, endpoint, traffic_split={"0": 100}
):
if DEPLOY_GPU:
machine_spec = {
"machine_type": DEPLOY_COMPUTE,
"accelerator_type": DEPLOY_GPU,
"accelerator_count": DEPLOY_NG... | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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_item = x_test[0]
test_label = y_test[0]
print(test_item.shape) | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Send the prediction requestOk, now you have a test data item. Use this helper function `predict_data`, which takes the parameters:- `data`: The test data item as a numpy 1D array of floating point values.- `endpoint`: The Vertex fully qualified identifier for the `Endpoint` resource where the `Model` resource was depl... | def predict_data(data, endpoint, parameters_dict):
parameters = json_format.ParseDict(parameters_dict, Value())
# The format of each instance should conform to the deployed model's prediction input schema.
instances_list = [{serving_input: data.tolist()}]
instances = [json_format.ParseDict(s, Value()) ... | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
Undeploy the `Model` resourceNow undeploy your `Model` resource from the serving `Endpoint` resoure. Use this helper function `undeploy_model`, which takes the following parameters:- `deployed_model_id`: The model deployment identifier returned by the endpoint service when the `Model` resource was deployed to.- `endpo... | def undeploy_model(deployed_model_id, endpoint):
response = clients["endpoint"].undeploy_model(
endpoint=endpoint, deployed_model_id=deployed_model_id, traffic_split={}
)
print(response)
undeploy_model(deployed_model_id, endpoint_id) | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-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 fully qualified identifier for the dataset
try:
if delete_dataset and "dataset_id" in globals():
... | _____no_output_____ | Apache-2.0 | notebooks/community/gapic/custom/showcase_custom_tabular_regression_online_pipeline.ipynb | nayaknishant/vertex-ai-samples |
GRU 236* Operate on 16000 GenCode 34 seqs.* 5-way cross validation. Save best model per CV.* Report mean accuracy from final re-validation with best 5.* Use Adam with a learn rate decay schdule. | NC_FILENAME='ncRNA.gc34.processed.fasta'
PC_FILENAME='pcRNA.gc34.processed.fasta'
DATAPATH=""
try:
from google.colab import drive
IN_COLAB = True
PATH='/content/drive/'
drive.mount(PATH)
DATAPATH=PATH+'My Drive/data/' # must end in "/"
NC_FILENAME = DATAPATH+NC_FILENAME
PC_FILENAME = DATAPA... | _____no_output_____ | MIT | Workshop/GRU_236.ipynb | ShepherdCode/ShepherdML |
Build model | def compile_model(model):
adam_default_learn_rate = 0.001
schedule = tf.keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate = adam_default_learn_rate*10,
#decay_steps=100000, decay_rate=0.96, staircase=True)
decay_steps=10000, decay_rate=0.99, staircase=True)
# learn r... | _____no_output_____ | MIT | Workshop/GRU_236.ipynb | ShepherdCode/ShepherdML |
Load and partition sequences | # Assume file was preprocessed to contain one line per seq.
# Prefer Pandas dataframe but df does not support append.
# For conversion to tensor, must avoid python lists.
def load_fasta(filename,label):
DEFLINE='>'
labels=[]
seqs=[]
lens=[]
nums=[]
num=0
with open (filename,'r') as infile:
... | _____no_output_____ | MIT | Workshop/GRU_236.ipynb | ShepherdCode/ShepherdML |
Make K-mers | def make_kmer_table(K):
npad='N'*K
shorter_kmers=['']
for i in range(K):
longer_kmers=[]
for mer in shorter_kmers:
longer_kmers.append(mer+'A')
longer_kmers.append(mer+'C')
longer_kmers.append(mer+'G')
longer_kmers.append(mer+'T')
short... | _____no_output_____ | MIT | Workshop/GRU_236.ipynb | ShepherdCode/ShepherdML |
Cross validation | def do_cross_validation(X,y,given_model):
cv_scores = []
fold=0
splitter = ShuffleSplit(n_splits=SPLITS, test_size=0.1) #, random_state=37863)
for train_index,valid_index in splitter.split(X):
fold += 1
X_train=X[train_index] # use iloc[] for dataframe
y_train=y[train_index]
... | _____no_output_____ | MIT | Workshop/GRU_236.ipynb | ShepherdCode/ShepherdML |
Train on RNA lengths 200-1Kb | MINLEN=200
MAXLEN=1000
print("Load data from files.")
nc_seq=load_fasta(NC_FILENAME,0)
pc_seq=load_fasta(PC_FILENAME,1)
train_set=pd.concat((nc_seq,pc_seq),axis=0)
nc_seq=None
pc_seq=None
print("Ready: train_set")
#train_set
subset=make_slice(train_set,MINLEN,MAXLEN)# One array to two: X and y
print ("Data reshape")
(X... | _____no_output_____ | MIT | Workshop/GRU_236.ipynb | ShepherdCode/ShepherdML |
print daily message | day_info = {"day":u"1", "title":u"영광과 흑암", "song":u"하나님은 우리 아버지", "prayer":u"", "summary":u"", \
"verses": [u"창1:3", u"창1:14", u"창1:26,28,29", u"창2:19", u"창2:9", u"창2:17", u"창3:6-7", \
u"유1:6", u"벧후2:4", u"창3:17-18", u"왕하6:17", u"행26:18", u"롬1:19-20", u"요12:46", \
u"골1:13", u"단2:... | _____no_output_____ | Apache-2.0 | dev/make_markdown.ipynb | sungcheolkim78/py_kbible |
daily info file | import yaml
print(yaml.dump(day_info, allow_unicode=True))
with open('day1.yaml', "w") as f:
yaml.dump(day_info, f, allow_unicode=True)
yaml.load? | _____no_output_____ | Apache-2.0 | dev/make_markdown.ipynb | sungcheolkim78/py_kbible |
Visualizing and working with network graphs is a common problem in many different disciplines. HoloViews provides the ability to represent and visualize graphs very simply and easily with facilities for interactively exploring the nodes and edges of the graph, especially using the bokeh plotting interface.The ``Graph``... | # Declare abstract edges
N = 8
node_indices = np.arange(N, dtype=np.int32)
source = np.zeros(N, dtype=np.int32)
target = node_indices
padding = dict(x=(-1.2, 1.2), y=(-1.2, 1.2))
simple_graph = hv.Graph(((source, target),)).redim.range(**padding)
simple_graph | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
Accessing the nodes and edgesWe can easily access the ``Nodes`` and ``EdgePaths`` on the ``Graph`` element using the corresponding properties: | simple_graph.nodes + simple_graph.edgepaths | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
Supplying explicit pathsNext we will extend this example by supplying explicit edges: | def bezier(start, end, control, steps=np.linspace(0, 1, 100)):
return (1-steps)**2*start + 2*(1-steps)*steps*control+steps**2*end
x, y = simple_graph.nodes.array([0, 1]).T
paths = []
for node_index in node_indices:
ex, ey = x[node_index], y[node_index]
paths.append(np.column_stack([bezier(x[0], ex, 0), be... | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
Interactive features Hover and selection policiesThanks to Bokeh we can reveal more about the graph by hovering over the nodes and edges. The ``Graph`` element provides an ``inspection_policy`` and a ``selection_policy``, which define whether hovering and selection highlight edges associated with the selected node or... | bezier_graph.options(inspection_policy='edges') | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
In addition to changing the policy we can also change the colors used when hovering and selecting nodes: | %%opts Graph [tools=['hover', 'box_select']] (edge_hover_line_color='green' node_hover_fill_color='red')
bezier_graph.options(inspection_policy='nodes') | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
Additional informationWe can also associate additional information with the nodes and edges of a graph. By constructing the ``Nodes`` explicitly we can declare additional value dimensions, which are revealed when hovering and/or can be mapped to the color by specifying the ``color_index``. We can also associate additi... | %%opts Graph [color_index='Type' edge_color_index='Weight'] (cmap='Set1' edge_cmap='viridis')
node_labels = ['Output']+['Input']*(N-1)
np.random.seed(7)
edge_labels = np.random.rand(8)
nodes = hv.Nodes((x, y, node_indices, node_labels), vdims='Type')
graph = hv.Graph(((source, target, edge_labels), nodes, paths), vdim... | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
If you want to supply additional node information without speciying explicit node positions you may pass in a ``Dataset`` object consisting of various value dimensions. | %%opts Graph [color_index='Label'] (cmap='Set1')
node_info = hv.Dataset(node_labels, vdims='Label')
hv.Graph(((source, target), node_info)).redim.range(**padding) | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
Working with NetworkX NetworkX is a very useful library when working with network graphs and the Graph Element provides ways of importing a NetworkX Graph directly. Here we will load the Karate Club graph and use the ``circular_layout`` function provided by NetworkX to lay it out: | %%opts Graph [tools=['hover']]
G = nx.karate_club_graph()
hv.Graph.from_networkx(G, nx.layout.circular_layout).redim.range(**padding) | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
Animating graphs Like all other elements ``Graph`` can be updated in a ``HoloMap`` or ``DynamicMap``. Here we animate how the Fruchterman-Reingold force-directed algorithm lays out the nodes in real time. | %%opts Graph
G = nx.karate_club_graph()
def get_graph(iteration):
np.random.seed(10)
return hv.Graph.from_networkx(G, nx.spring_layout, iterations=iteration)
hv.HoloMap({i: get_graph(i) for i in range(5, 30, 5)},
kdims='Iterations').redim.range(x=(-1.2, 1.2), y=(-1.2, 1.2)) | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
Real world graphs As a final example let's look at a slightly larger graph. We will load a dataset of a Facebook network consisting a number of friendship groups identified by their ``'circle'``. We will load the edge and node data using pandas and then color each node by their friendship group using many of the thing... | %opts Nodes Graph [width=800 height=800 xaxis=None yaxis=None]
%%opts Graph [color_index='circle']
%%opts Graph (node_size=10 edge_line_width=1)
colors = ['#000000']+hv.Cycle('Category20').values
edges_df = pd.read_csv('../assets/fb_edges.csv')
fb_nodes = hv.Nodes(pd.read_csv('../assets/fb_nodes.csv')).sort()
fb_graph ... | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
Bundling graphs The datashader library provides algorithms for bundling the edges of a graph and HoloViews provides convenient wrappers around the libraries. Note that these operations need ``scikit-image`` which you can install using:```conda install scikit-image```or```pip install scikit-image``` | from holoviews.operation.datashader import datashade, bundle_graph
bundled = bundle_graph(fb_graph)
bundled | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
Datashading graphs For graphs with a large number of edges we can datashade the paths and display the nodes separately. This loses some of the interactive features but will let you visualize quite large graphs: | %%opts Nodes [color_index='circle'] (size=10 cmap=colors) Overlay [show_legend=False]
datashade(bundled, normalization='linear', width=800, height=800) * bundled.nodes | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
Applying selections Alternatively we can select the nodes and edges by an attribute that resides on either. In this case we will select the nodes and edges for a particular circle and then overlay just the selected part of the graph on the datashaded plot. Note that selections on the ``Graph`` itself will select all n... | %%opts Graph (node_fill_color='white')
datashade(bundle_graph(fb_graph), normalization='linear', width=800, height=800) *\
bundled.select(circle='circle15') | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
To select just nodes that are in 'circle15' set the ``selection_mode='nodes'`` overriding the default of 'edges': | bundled.select(circle='circle15', selection_mode='nodes') | _____no_output_____ | BSD-3-Clause | examples/user_guide/Network_Graphs.ipynb | jsignell/holoviews |
How have Airbnb prices changed due to COVID-19? Business Understanding This is the most recent data (Oct, 2020) taken from the official website Airbnb http://insideairbnb.com/get-the-data.htmlIn this Notebook, we'll look at this data, clean up, analyze, visualize, and model.And we will answer the following questions ... | #import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import geopandas as gpd
#ml libraries
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemb... | N:\Anaconda\lib\site-packages\numpy\lib\arraysetops.py:569: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
mask |= (ar1 == a)
| Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
Cleaning the Data Listing Data Frame First, let's look on Listing Data Frame. It is the biggest table. We won't need some columns because they don't make much sense for our purposes. So we will drop them. | sf_list = sf_list[['id', 'host_since', 'host_is_superhost', 'host_listings_count', 'host_response_time',
'host_response_rate', 'host_acceptance_rate','neighbourhood_cleansed', 'latitude', 'longitude',
'property_type', 'room_type', 'accommodates', 'bathrooms', 'bedrooms', 'beds', ... | _____no_output_____ | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
We have left the following columns:* __'id'__ — we'll use to join tables* __host_since__ and __last_review__ — datatype data, we transform to categorical* __'host_response_time'__ — categorical data* __host_is_superhost__ — boolean data* __'host_response_rate'__ and __'host_acceptance_rate'__ — as a percentage, we will... | #converting datatype of price column to integer
sf_list["price"] = sf_list["price"].apply(lambda string: ''.join(i for i in string if i.isdigit())[:-2])
sf_list["price"] = pd.to_numeric(sf_list["price"], downcast="integer")
#host_response_rate and host_acceptance_rate types to float
sf_list["host_response_rate"] = sf_... | Listing Data Frame
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 7274 entries, 0 to 7273
Data columns (total 31 columns):
id 7274 non-null int64
host_since 7274 non-null datetime64[ns]
host_is_superhost 7274 non-null int64
host_listings_count 7... | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
Amenities Data Frame Consider the data about the amenities. This column is a set of lists enclosed in strings. So I had to use the *eval*. If you know a more elegant method, please let me know.Then we'll add columns for each amenitie, remove the common and very rare amenities. | amenitiesList = []
for item in sf_list["amenities"].value_counts().reset_index()["index"]:
item = eval(item)
for i in item:
if i not in amenitiesList:
amenitiesList.append(i)
print("Total amenities: ", len(amenitiesList))
print(amenitiesList)
amenities_df = sf_list[["id", "amenities"]]
#we ... | (7274, 133)
| Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
Calendar Data Frame | sf_cal.head() | _____no_output_____ | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
This Data Frame has folowing columns:* __listing_id__ — id values, we'll use to join tables* __date__ — we need to change datatype to datetime* __available__ — it has to be boolean, so we need to change it* __minimum_nights, maximum_nights__ — we have same columns in Listing Data Frame, drop they later* __adjusted_pric... | #converting datatype of price and adjusted_price columns to integer
sf_cal["price"] = sf_cal["price"].apply(lambda string: stringToNumConverter(string))
sf_cal["price"] = pd.to_numeric(sf_cal["price"], downcast="integer")
sf_cal["adjusted_price"] = sf_cal["adjusted_price"].apply(lambda string: stringToNumConverter(str... | Calendar Data Frame
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2390652 entries, 0 to 2390651
Data columns (total 7 columns):
listing_id int64
date datetime64[ns]
available bool
price float64
adjusted_price float64
minimum_nights float64
maximum_nights float64
dtyp... | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
Data Understanding Let's analyze the data to answer the questions given at the beginning: 1. What correlates best with price? Does Amenities correlate with price? | amen_price_corr_neg = amenities_df.merge(sf_list[["id", "price"]], on="id").corr()[["id", "price"]].sort_values(by="price").head(10)
amen_price_corr_pos = amenities_df.merge(sf_list[["id", "price"]], on="id").corr()[["id", "price"]].sort_values(by="price").drop("price", axis=0).tail(10)
#negative correlation
amen_price... | _____no_output_____ | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
As you can see, air conditioning, gym, and building staff are highly correlated with price. The rest of the amenities correlate either weakly or not at all. Does Review Scores correlate with price? | plt.subplots(figsize=(9, 6))
sns.heatmap(sf_list[['review_scores_rating', 'review_scores_accuracy',
'review_scores_cleanliness', 'review_scores_checkin',
'review_scores_communication', 'review_scores_location',
'review_scores_value', "number_of_reviews", 'p... | _____no_output_____ | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
Review Scores correlate weakly with price, but they correlate well with each other. Does Housing Characteristics correlate with price? | plt.subplots(figsize=(9, 6))
sns.heatmap(sf_list[['accommodates', 'bathrooms', 'bedrooms', 'beds', 'price']].corr(),
annot=True, fmt=".2f") | _____no_output_____ | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
There is an obvious correlation. The more people you can accommodate, the more expensive it is to rent a room. Same about bedrooms and beds. But the number of bathrooms does not have a strong impact. Some more dependencies on the price, which we will use in modeling: | sf_list.groupby(["room_type"]).mean().reset_index()[["room_type","price"]].style.bar(color="#cd4a4c")
sf_list.groupby(["property_type"]).mean().reset_index()[["property_type","price"]].sort_values(by="price", ascending=False).style.bar(color="#cd4a4c")
sf_list.groupby(["host_response_time"]).mean().reset_index()[["host... | _____no_output_____ | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
How about Neighbourhoods? Let's find the most expensive neighbourhood. | #coordinates of San Francisco
sf_latitude, sf_longitude = 37.7647993, -122.4629897
#the necessary data for the map
sf_map = gpd.read_file("planning_neighborhoods/planning_neighborhoods.shp")
sf_neig_mean = sf_list.groupby(["neighbourhood_cleansed"]).mean().reset_index()
sf_map = sf_map.merge(sf_neig_mean, left_on="neig... | _____no_output_____ | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
As you can see from the map, the high price is more related to the location. The most expensive areas are Golden Gate Park and Financial District. If you look at my previous research, you understand that Golden Gate Park is quite safe, unlike the Financial District which pretty criminal. All this data can be used to pr... | per = sf_cal.date.dt.to_period("M")
g = sf_cal.groupby(per)
ax = sns.set_palette("viridis")
plt.figure(figsize=(16,6))
sns.barplot(x=g.mean().reset_index()["date"],
y=g.mean().reset_index()["price"])
plt.xlabel("Month", fontsize=20)
plt.ylabel("Price per night", fontsize=20)
plt.title("Average Price per... | _____no_output_____ | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
During the covid period, the average price per night rose by about $33. And it does not stop growing linearly. Next one is busyness. | ax = sns.set_palette("viridis")
plt.figure(figsize=(16,6))
sns.barplot(x=g.mean().reset_index()["date"],
y=g.mean().reset_index()["available"])
plt.xlabel("Month", fontsize=20)
plt.ylabel("Availability, proportion", fontsize=20)
plt.title("Average Availability in San Francisco", fontsize=25)
plt.show() | _____no_output_____ | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
September last year was quite popular (wonderful weather). Then the decline began. But with the onset of covid, the decline intensified and reached its peak (half of the housing is vacant) by May. As expected, the covid did not affect the Airbnb business in the best way. Prices have gone up and there are fewer customer... | sf_list["since_last_review"] = sf_list["last_review"].apply(lambda row : dateToCategorical(row))
sf_list["host_since_cat"] = sf_list["host_since"].apply(lambda row : dateToCategorical(row))
#drop all Nans in "price" columns
drop_sf_list = sf_list.dropna(subset=["price"], axis=0)
#create data frame with categorical valu... | _____no_output_____ | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
After all, we'll merge tree Data Frames: mean_sf_list, dummy_sf_list and amenities_df. | full_sf_list = dummy_sf_list.merge(amenities_df.drop(["amenities"], axis=1), on="id").merge(mean_sf_list, on="id") | _____no_output_____ | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
Data Modeling Let's start modeling. We will try several models and compare the results. | #preparation train and test data
X = full_sf_list.drop(["price"], axis=1)
y = full_sf_list["price"]
#scaling
scaler = StandardScaler()
X = pd.DataFrame(scaler.fit_transform(X), columns=list(X.columns))
#split into train and test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3, random_state=42)
... | _____no_output_____ | Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
Predicting Price AdaBoost regressor | adaboost_model = AdaBoostRegressor(n_estimators=20)
adaboost_model.fit(X_train, y_train)
#predict and score the model
y_test_preds = adaboost_model.predict(X_test)
y_train_preds = adaboost_model.predict(X_train)
#scoring model
test_r2 = round(r2_score(y_test, y_test_preds), 4)
train_r2 = round(r2_score(y_train, y_tra... | r-squared score for training set was 0.4804. r-squared score for test set was 0.4407.
MSE score for training set was 0.3275. MSE score for test set was 0.3551.
| Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
Gradient Boosting for regression | gradboost_model = GradientBoostingRegressor(n_estimators=300)
gradboost_model.fit(X_train, y_train)
#predict and score the model
y_test_preds = gradboost_model.predict(X_test)
y_train_preds = gradboost_model.predict(X_train)
#scoring model
test_r2 = round(r2_score(y_test, y_test_preds), 4)
train_r2 = round(r2_score(y... | r-squared score for training set was 0.8149. r-squared score for test set was 0.7033.
MSE score for training set was 0.1167. MSE score for test set was 0.1884.
| Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
Extreme Gradient Boosting | xgb_reg = xgb.XGBRegressor()
xgb_reg.fit(X_train, y_train)
y_train_preds = xgb_reg.predict(X_train)
y_test_preds = xgb_reg.predict(X_test)
#scoring model
test_r2 = round(r2_score(y_test, y_test_preds), 4)
train_r2 = round(r2_score(y_train, y_train_preds), 4)
test_mse = round(mean_squared_error(y_test, y_test_preds), ... | [16:43:04] WARNING: src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.
| Apache-2.0 | AirBNB_Analysis_San_Francisco.ipynb | zaveta/AirBNB-Analysis-San-Francisco |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.