Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cloud/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-watsonx-ai

This notebook contains the steps and code to demonstrate support of AutoAI experiments for timeseries data sets in watsonx.ai Runtime 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.11.

Learning goals

The learning goals of this notebook are:

  • Define watsonx.ai Runtime 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:

  • Create a watsonx.ai Runtime Service instance (a free plan is offered and information about how to create the instance can be found here).

  • Create a Cloud Object Storage (COS) instance (a lite plan is offered and information about how to order storage can be found here).
    Note: When using Watson Studio, you already have a COS instance associated with the project you are running the notebook in.

Install and import the ibm-watsonx-ai and dependecies

Note: ibm-watsonx-ai documentation can be found here.

!pip install wget | tail -n 1 !pip install plotly | tail -n 1 !pip install -U ibm-watsonx-ai | tail -n 1

Connection to watsonx.ai Runtime

Authenticate the watsonx.ai Runtime service on IBM Cloud. You need to provide Cloud API key and location.

Tip: Your Cloud API key can be generated by going to the Users section of the Cloud console. From that page, click your name, scroll down to the API Keys section, and click Create an IBM Cloud API key. Give your key a name and click Create, then copy the created key and paste it below. You can also get a service specific url by going to the Endpoint URLs section of the watsonx.ai Runtime docs. You can check your instance location in your watsonx.ai Runtime Service instance details.

You can use IBM Cloud CLI to retrieve the instance location.

ibmcloud login --apikey API_KEY -a https://cloud.ibm.com ibmcloud resource service-instance INSTANCE_NAME

NOTE: You can also get a service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, and then copy the created key and paste it in the following cell.

Action: Enter your api_key and location in the following cell.

api_key = 'PUT_YOUR_KEY_HERE' location = 'PASTE YOUR INSTANCE LOCATION HERE'
from ibm_watsonx_ai import Credentials credentials = Credentials( api_key=api_key, url='https://' + location + '.ml.cloud.ibm.com' )
from ibm_watsonx_ai import APIClient client = APIClient(credentials)

Working with spaces

You need to create a space that will be used for your work. If you do not have a space, you can use Deployment Spaces Dashboard to create one.

  • Click New Deployment Space

  • Create an empty space

  • Select Cloud Object Storage

  • Select watsonx.ai Runtime instance and press Create

  • 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 watsonx.ai Runtime, you need to set the space which you will be using.

client.set.default_space(space_id)
'SUCCESS'

2. Timeseries data set

Connections to COS

In next cell we read the COS credentials from the space.

cos_credentials = client.spaces.get_details(space_id=space_id)['entity']['storage']['properties']

Training data sets

Download training data from git repository and upload it to a COS. This example uses the Poland COVID19 daily confirmed cases.

datasource_name = 'bluemixcloudobjectstorage' bucketname = cos_credentials['bucket_name']
import os, wget 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)

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()
MIME type unknown not supported

Create connection

conn_meta_props= { client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {datasource_name} ", client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_id_by_name(datasource_name), client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database", client.connections.ConfigurationMetaNames.PROPERTIES: { 'bucket': bucketname, 'access_key': cos_credentials['credentials']['editor']['access_key_id'], 'secret_key': cos_credentials['credentials']['editor']['secret_access_key'], 'iam_url': 'https://iam.cloud.ibm.com/identity/token', 'url': cos_credentials['endpoint_url'] } } conn_details = client.connections.create(meta_props=conn_meta_props)
Creating connections... SUCCESS

Note: The above connection can be initialized alternatively with api_key and resource_instance_id. The above cell can be replaced with:

conn_meta_props= { client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {db_name} ", client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_id_by_name(db_name), client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database", client.connections.ConfigurationMetaNames.PROPERTIES: { 'bucket': bucket_name, 'api_key': cos_credentials['apikey'], 'resource_instance_id': cos_credentials['resource_instance_id'], 'iam_url': 'https://iam.cloud.ibm.com/identity/token', 'url': 'https://s3.us.cloud-object-storage.appdomain.cloud' } } conn_details = client.connections.create(meta_props=conn_meta_props)
connection_id = client.connections.get_id(conn_details)

Training data connection

The code in next cell defines connections to created assets.

from ibm_watsonx_ai.helpers import DataConnection, S3Location data_connections = [] data_connection = DataConnection( connection_asset_id=connection_id, location=S3Location(bucket=cos_credentials['bucket_name'], path=filename) ) data_connection.set_client(client) data_connection.write(data=filename, remote_name=filename) data_connections.append(data_connection)

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

  • backtest_num – number of backtests

from ibm_watsonx_ai.experiment import AutoAI experiment = AutoAI(credentials, space_id=space_id) forecast_window = 7 backtest_num = 4 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=backtest_num, 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=data_connections, background_mode=False)
Training job 1d345490-624b-4809-ba30-c41a6df8de35 completed: 100%|████████| [01:50<00:00, 1.10s/it]

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

visualization = pipeline_details['visualization']['holdout'] holdout_dates = visualization['time'] holdout_predictions = visualization['predicted_values'][0] holdout_observed_values = visualization['observed_values'][0] holdout_df = pd.DataFrame({'time':holdout_dates, 'observed_values':holdout_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()
MIME type unknown not supported

Backtest data visualization

from datetime import datetime, timedelta import numpy as np backtest_dfs = [] for i in range(backtest_num): visualization = pipeline_details['visualization']['backtest']['iterations'][i] backtest_dates = visualization['time'] backtest_predictions = visualization['predicted_values'][0] observed_values = visualization['observed_values'][0] backtest_dfs.append(pd.DataFrame({'time':backtest_dates, 'observed_values':observed_values, 'predicted_values': backtest_predictions})) backtest_df = pd.concat(backtest_dfs) fig = px.line(backtest_df, x="time", y=backtest_df.columns, hover_data={"time": "|%B %d, %Y"}, title='Backtest data') fig.update_xaxes(dtick="M1", tickformat="%b\n%Y") fig.show()
MIME type unknown not supported

6. Deploy and Score

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

Online deployment creation

from ibm_watsonx_ai.deployment import WebService service = WebService(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: 4cf66a0c-067b-4869-96da-698b3bd51b43 Deploying model 4cf66a0c-067b-4869-96da-698b3bd51b43 using V4 client. ####################################################################################### Synchronous deployment creation for uid: '4cf66a0c-067b-4869-96da-698b3bd51b43' started ####################################################################################### initializing Note: online_url and serving_urls are deprecated and will be removed in a future release. Use inference instead. .. ready ------------------------------------------------------------------------------------------------ Successfully finished deployment creation, deployment_uid='7b65f65a-5535-440c-b170-433663547d57' ------------------------------------------------------------------------------------------------

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.350337853044]], [[32564.841193702112]], [[29853.50082004966]]]}]}

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' : holdout_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()
MIME type unknown not supported

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-watsonx-ai 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.

Mateusz Szewczyk, Software Engineer at watsonx.ai.

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