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

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 Pak for Data administrator and ask them for your account credentials

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 WML

Authenticate the Watson Machine Learning service on IBM Cloud Pak 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'
from ibm_watsonx_ai import Credentials credentials = Credentials( username=username, api_key=api_key, url=url, instance_id="openshift", version="5.1" )

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

credentials = Credentials( username=***, password=***, url=***, instance_id="openshift", version="5.1" )
from ibm_watsonx_ai import APIClient client = APIClient(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 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
Creating data asset... SUCCESS
{'metadata': {'space_id': 'cbd87244-b000-4279-b991-3cefbf8b1555', 'usage': {'last_updated_at': '2024-04-29T11:39:33Z', 'last_updater_id': '1000330999', 'last_update_time': 1714390773219, 'last_accessed_at': '2024-04-29T11:39:33Z', 'last_access_time': 1714390773219, 'last_accessor_id': '1000330999', 'access_count': 0}, 'rov': {'mode': 0, 'collaborator_ids': {}, 'member_roles': {'1000330999': {'user_iam_id': '1000330999', 'roles': ['OWNER']}}}, 'name': 'poland_daily_cases_03_28_2021.csv', 'description': '', 'asset_type': 'data_asset', 'origin_country': 'us', 'resource_key': 'poland_daily_cases_03_28_2021.csv', 'rating': 0.0, 'total_ratings': 0, 'catalog_id': '6dd61f7f-0608-4288-abe8-3881dce0c404', 'created': 1714390773219, 'created_at': '2024-04-29T11:39:33Z', 'owner_id': '1000330999', 'size': 0, 'version': 2.0, 'asset_state': 'available', 'asset_attributes': ['data_asset'], 'asset_id': '4d0143df-3e12-4422-8ab3-f02c45aae7cf', 'asset_category': 'USER', 'creator_id': '1000330999', 'guid': '4d0143df-3e12-4422-8ab3-f02c45aae7cf', 'href': '/v2/assets/4d0143df-3e12-4422-8ab3-f02c45aae7cf?space_id=cbd87244-b000-4279-b991-3cefbf8b1555', 'last_updated_at': '2024-04-29T11:39:33Z'}, 'entity': {'data_asset': {'mime_type': 'text/csv'}}}
client.data_assets.get_id(asset_details)
'4d0143df-3e12-4422-8ab3-f02c45aae7cf'
from ibm_watsonx_ai.helpers import DataConnection 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()
MIME type unknown not supported

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_watsonx_ai.experiment import AutoAI experiment = AutoAI(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 dacaa0a5-03b5-4f10-9403-5e8295b02aad completed: 100%|████████| [00:56<00:00, 1.77it/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()
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 WML 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: 6c7b68b2-87e9-48c8-a2fd-e564568f428d Deploying model 6c7b68b2-87e9-48c8-a2fd-e564568f428d using V4 client. ###################################################################################### Synchronous deployment creation for id: '6c7b68b2-87e9-48c8-a2fd-e564568f428d' 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_id='d0fbcd82-d125-4961-9cd9-33d9823423b0' -----------------------------------------------------------------------------------------------

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.44280453762]], [[29957.455192354864]], [[31766.405211835852]], [[34318.30390937023]], [[35107.35033785305]], [[32564.84119370212]], [[29853.500820049674]]]}]}

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()
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 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.

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