Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cpd4.5/notebooks/python_sdk/experiments/autoai/Use AutoAI and timeseries data to predict COVID cases.ipynb
6405 views
Kernel: Python 3 (ipykernel)

Use AutoAI and timeseries data to predict COVID19 cases with ibm-watson-machine-learning

This notebook contains the steps and code to demonstrate support of AutoAI experiments for timeseries data sets in Watson Machine Learning service. It introduces commands for data retrieval, training experiments, persisting pipelines, testing pipelines, deploying pipelines, and scoring.

Some familiarity with Python is helpful. This notebook uses Python 3.9.

Learning goals

The learning goals of this notebook are:

  • Define Watson Machine Learning experiment for timeseries data sets.

  • Work with experiments to train AutoAI models.

  • Compare trained models quality and select the best one for further deployment.

  • Online deployment and score the trained model.

Contents

This notebook contains the following parts:

  1. Setup

  2. Timeseries data sets

  3. Optimizer definition

  4. Experiment Run

  5. Pipelines comparison

  6. Deploy and Score

  7. Clean up

  8. Summary and next steps

1. Set up the environment

Before you use the sample code in this notebook, you must perform the following setup tasks:

  • Contact with your Cloud Pack for Data administrator and ask him for your account credentials

Connection to WML

Authenticate the Watson Machine Learning service on IBM Cloud Pack for Data. You need to provide platform url, your username and api_key.

username = 'PASTE YOUR USERNAME HERE' api_key = 'PASTE YOUR API_KEY HERE' url = 'PASTE THE PLATFORM URL HERE'
wml_credentials = { "username": username, "apikey": api_key, "url": url, "instance_id": 'openshift', "version": '4.5' }

Alternatively you can use username and password to authenticate WML services.

wml_credentials = { "username": ***, "password": ***, "url": ***, "instance_id": 'openshift', "version": '4.5' }

Install and import the ibm-watson-machine-learning and dependecies

Note: ibm-watson-machine-learning documentation can be found here.

!pip install -U ibm-watson-machine-learning | tail -n 1 !pip install wget | tail -n 1 !pip install plotly | tail -n 1
from ibm_watson_machine_learning import APIClient client = APIClient(wml_credentials)

Working with spaces

First of all, you need to create a space that will be used for your work. If you do not have space already created, you can use {PLATFORM_URL}/ml-runtime/spaces?context=icp4data to create one.

  • Click New Deployment Space

  • Create an empty space

  • Go to space Settings tab

  • Copy space_id and paste it below

Tip: You can also use SDK to prepare the space for your work. More information can be found here.

Action: Assign space ID below

space_id = 'PASTE YOUR SPACE ID HERE'

You can use the list method to print all existing spaces.

client.spaces.list(limit=10)

To be able to interact with all resources available in Watson Machine Learning, you need to set the space which you will be using.

client.set.default_space(space_id)
'SUCCESS'

2. Timeseries data set

Training data sets

Define connection information to training data CSV file. This example uses the Poland COVID19 daily confirmed cases.

import os, wget, zipfile filename = 'poland_daily_cases_03_28_2021.csv' base_url = 'https://raw.githubusercontent.com/LukaszCmielowski/covid-19/master/' if not os.path.isfile(filename): wget.download(base_url + filename)
asset_details = client.data_assets.create('poland_daily_cases_03_28_2021.csv', filename) asset_details
client.data_assets.get_id(asset_details)
from ibm_watson_machine_learning.helpers import DataConnection, AssetLocation covid_daily_cases = DataConnection(data_asset_id=client.data_assets.get_id(asset_details)) training_data_reference=[covid_daily_cases]

Visualize the data

import plotly.express as px import pandas as pd df = pd.read_csv(filename) fig = px.line(df, x='date', y="daily_cases") fig.show()

3. Optimizer definition

Optimizer configuration

Provide the input information for AutoAI optimizer:

  • name - experiment name

  • prediction_type - type of the problem

  • prediction_columns - target columns names

  • scoring - optimization metric

from ibm_watson_machine_learning.experiment import AutoAI experiment = AutoAI(wml_credentials, space_id=space_id) forecast_window = 7 pipeline_optimizer = experiment.optimizer( name="COVID19 PL timeseries", prediction_type=AutoAI.PredictionType.FORECASTING, prediction_columns=['daily_cases'], timestamp_column_name=0, scoring=AutoAI.Metrics.R2_SCORE, max_number_of_estimators=1, backtest_num=4, lookback_window=5, forecast_window=forecast_window, holdout_size=5 )

Configuration parameters can be retrieved via pipeline_optimizer.get_params().

4. Experiment run

Call the fit() method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying background_model=True.

fit_details = pipeline_optimizer.fit(training_data_reference=training_data_reference, background_mode=False)
Training job f3dfd111-89bd-499d-83b5-07f9ced3ba86 completed: 100%|████████| [01:11<00:00, 1.40it/s]

You can use the get_run_status() method to monitor AutoAI jobs in background mode.

pipeline_optimizer.get_run_status()
'completed'

5. Pipelines comparison

You can list trained pipelines and evaluation metrics information in the form of a Pandas DataFrame by calling the summary() method. You can use the DataFrame to compare all discovered pipelines and select the one you like for further deployment.

summary = pipeline_optimizer.summary() summary

Check pipeline details by calling get_pipeline_details(pipeline_name='Pipeline_8'). By default details of best pipeline are returned.

best_pipeline_name = summary[summary.Winner==True].index.values[0] print('Best pipeline is:', best_pipeline_name) pipeline_details = pipeline_optimizer.get_pipeline_details()
Best pipeline is: Pipeline_6

Holdout data visualization

from datetime import datetime, timedelta import numpy as np visualization = pipeline_details['visualization']['backtest']['iterations'][-1] holdout_dates = visualization['time'] holdout_predictions = visualization['predicted_values'][0] observed_values = visualization['observed_values'][0] holdout_df = pd.DataFrame({'time':holdout_dates, 'observed_values':observed_values, 'predicted_values': holdout_predictions}) fig = px.line(holdout_df, x="time", y=holdout_df.columns, hover_data={"time": "|%B %d, %Y"}, title='Holdout data') fig.update_xaxes(dtick="M1", tickformat="%b\n%Y") fig.show()

6. Deploy and Score

In this section you will learn how to deploy and score pipeline model as online deployment using WML instance.

Online deployment creation

from ibm_watson_machine_learning.deployment import WebService service = WebService(wml_credentials, source_space_id=space_id) service.create( experiment_run_id=pipeline_optimizer.get_run_details()['metadata']['id'], model=best_pipeline_name, deployment_name="COVID19 for Poland" )
Preparing an AutoAI Deployment... Published model uid: ed63d148-ff68-4342-a33c-b90a7d08a0cd Deploying model ed63d148-ff68-4342-a33c-b90a7d08a0cd using V4 client. ####################################################################################### Synchronous deployment creation for uid: 'ed63d148-ff68-4342-a33c-b90a7d08a0cd' started ####################################################################################### initializing Note: online_url is deprecated and will be removed in a future release. Use serving_urls instead. ... ready ------------------------------------------------------------------------------------------------ Successfully finished deployment creation, deployment_uid='0c7539f7-0175-4159-87fb-5a3771129d22' ------------------------------------------------------------------------------------------------

To show all available information about the deployment use the .get_params() method:

service.get_params()

Scoring

You can use the score method to get predictions for defined forecasting window. You can either send payload records or use empty list.

predictions = service.score(payload=pd.DataFrame({'daily_cases' : []})) print('predictions for next 7 days:\n') predictions
predictions for next 7 days:
{'predictions': [{'fields': ['prediction'], 'values': [[[29333.442804537604]], [[29957.455192354842]], [[31766.405211835838]], [[34318.30390937021]], [[35107.35033785305]], [[32564.841193702112]], [[29853.500820049652]]]}]}

Or you could send payload with new obeservations:

predictions = service.score(payload=pd.DataFrame({'daily_cases' : df.iloc[-10:, 1].values.tolist()}))

Visualization of predictions

last_date = datetime.strptime(holdout_df.tail(1).time.values.tolist()[0],'%Y-%m-%d') prediction_dates = [(last_date + timedelta(days=1 + i)).date() for i in range(forecast_window)] prediction_values = [pred[0][0] for pred in predictions['predictions'][0]['values']] pred_df = pd.DataFrame({'time' : holdout_dates + prediction_dates, 'observed_values' : observed_values + [np.NAN for i in range(forecast_window)], 'predicted_values' : holdout_predictions + prediction_values}) fig = px.line(pred_df, x="time", y=pred_df.columns, hover_data={"time": "|%B %d, %Y"}, title='Forecast data') fig.update_xaxes(dtick="M1", tickformat="%b\n%Y") fig.show()

7. Clean up

If you want to clean up all created assets:

  • experiments

  • trainings

  • pipelines

  • model definitions

  • models

  • functions

  • deployments

please follow up this sample notebook.

8. Summary and next steps

You successfully completed this notebook!.

You learned how to use ibm-watson-machine-learning to run AutoAI experiments.

Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.

Authors

Lukasz Cmielowski, PhD, is an Automation Architect and Data Scientist at IBM with a track record of developing enterprise-level applications that substantially increases clients' ability to turn data into actionable knowledge.

Copyright © 2020-2025 IBM. This notebook and its source code are released under the terms of the MIT License.