Calculating Confusion Matrix Elements for Binary Classification

This tutorial explains how to use NannyML to calculate the confusion matrix for binary classification models.

Note

The following example uses timestamps. These are optional but have an impact on the way data is chunked and results are plotted. You can read more about them in the data requirements.

Just The Code

```>>> import nannyml as nml
>>> from IPython.display import display

>>> reference_df, analysis_df, analysis_targets_df = nml.load_synthetic_car_loan_dataset()

>>> analysis_df = analysis_df.merge(analysis_targets_df, left_index=True, right_index=True)

>>> calc = nml.PerformanceCalculator(
...     y_pred_proba='y_pred_proba',
...     y_pred='y_pred',
...     y_true='repaid',
...     timestamp_column_name='timestamp',
...     problem_type='classification_binary',
...     metrics=['confusion_matrix'],
...     normalize_confusion_matrix='all',
...     chunk_size=5000)

>>> calc.fit(reference_df)

>>> results = calc.calculate(analysis_df)
>>> display(results.filter(period='analysis').to_df())

>>> display(results.filter(period='reference').to_df())

>>> figure = results.plot()
>>> figure.show()
```

Walkthrough

For simplicity this guide is based on a synthetic dataset included in the library, where the monitored model predicts whether a customer will repay a loan to buy a car. Check out Car Loan Dataset to learn more about this dataset.

In order to monitor a model, NannyML needs to learn about it from a reference dataset. Then it can monitor the data that is subject to actual analysis, provided as the analysis dataset. You can read more about this in our section on data periods.

The `analysis_targets` dataframe contains the target results of the analysis period. This is kept separate in the synthetic data because it is not used during performance estimation. But it is required to calculate performance, so the first thing we need to in this case is set up the right data in the right dataframes.

The analysis target values are joined on the analysis frame by their index. Your dataset may already contain the target column, so you may skip this join.

```>>> import nannyml as nml
>>> from IPython.display import display

>>> reference_df, analysis_df, analysis_targets_df = nml.load_synthetic_car_loan_dataset()

>>> analysis_df = analysis_df.merge(analysis_targets_df, left_index=True, right_index=True)

```

id

car_value

salary_range

debt_to_income_ratio

loan_length

repaid_loan_on_prev_car

size_of_downpayment

driver_tenure

repaid

timestamp

y_pred_proba

y_pred

0

0

39811

40K - 60K €

0.63295

19

False

40%

0.212653

1

2018-01-01 00:00:00.000

0.99

1

1

1

12679

40K - 60K €

0.718627

7

True

10%

4.92755

0

2018-01-01 00:08:43.152

0.07

0

2

2

19847

40K - 60K €

0.721724

17

False

0%

0.520817

1

2018-01-01 00:17:26.304

1

1

Next a `PerformanceCalculator` is created using the following:

• y_pred_proba: the name of the column in the reference data that contains the predicted probabilities.

• y_pred: the name of the column in the reference data that contains the predicted classes.

• y_true: the name of the column in the reference data that contains the true classes.

• timestamp_column_name (Optional): the name of the column in the reference data that contains timestamps.

• problem_type: the type of problem being monitored. In this example we will monitor a binary classification problem.

• metrics: a list of metrics to calculate. In this example we will calculate the `confusion_matrix` metric.

• normalize_confusion_matrix (Optional): how to normalize the confusion matrix. The normalization options are:

• None : returns counts for each cell

• “true” : normalize over the true class of observations.

• “pred” : normalize over the predicted class of observations

• “all” : normalize over all observations

• chunk_size (Optional): the number of observations in each chunk of data used to calculate performance. For more information about chunking other chunking options check out the chunking tutorial.

```>>> calc = nml.PerformanceCalculator(
...     y_pred_proba='y_pred_proba',
...     y_pred='y_pred',
...     y_true='repaid',
...     timestamp_column_name='timestamp',
...     problem_type='classification_binary',
...     metrics=['confusion_matrix'],
...     normalize_confusion_matrix='all',
...     chunk_size=5000)
```

The new `PerformanceCalculator` is fitted using the `fit()` method on the `reference` data.

```>>> calc.fit(reference_df)
```

The fitted `PerformanceCalculator` can then be used to calculate realized performance metrics on all data which has target values available with the `calculate()` method. NannyML can output a dataframe that contains all the results of the analysis data.

```>>> results = calc.calculate(analysis_df)
>>> display(results.filter(period='analysis').to_df())
```

chunk
key
chunk_index
start_index
end_index
start_date
end_date
period
targets_missing_rate
true_positive
sampling_error
value
upper_threshold
lower_threshold
true_negative
sampling_error
value
upper_threshold
lower_threshold
false_positive
sampling_error
value
upper_threshold
lower_threshold
false_negative
sampling_error
value
upper_threshold
lower_threshold

0

[0:4999]

0

0

4999

2018-10-30 18:00:00

2018-11-30 00:27:16.848000

analysis

0

0.00705286

0.4812

0.478879

0.449401

True

0.00706512

0.461

0.494119

0.464881

True

0.00202397

0.0218

0.025818

0.016022

False

0.00261473

0.036

0.0416915

0.0291885

False

1

[5000:9999]

1

5000

9999

2018-11-30 00:36:00

2018-12-30 07:03:16.848000

analysis

0

0.00705286

0.4542

0.478879

0.449401

False

0.00706512

0.488

0.494119

0.464881

False

0.00202397

0.0204

0.025818

0.016022

False

0.00261473

0.0374

0.0416915

0.0291885

False

2

[10000:14999]

2

10000

14999

2018-12-30 07:12:00

2019-01-29 13:39:16.848000

analysis

0

0.00705286

0.4558

0.478879

0.449401

False

0.00706512

0.4944

0.494119

0.464881

True

0.00202397

0.0198

0.025818

0.016022

False

0.00261473

0.03

0.0416915

0.0291885

False

3

[15000:19999]

3

15000

19999

2019-01-29 13:48:00

2019-02-28 20:15:16.848000

analysis

0

0.00705286

0.4592

0.478879

0.449401

False

0.00706512

0.4844

0.494119

0.464881

False

0.00202397

0.0192

0.025818

0.016022

False

0.00261473

0.0372

0.0416915

0.0291885

False

4

[20000:24999]

4

20000

24999

2019-02-28 20:24:00

2019-03-31 02:51:16.848000

analysis

0

0.00705286

0.4662

0.478879

0.449401

False

0.00706512

0.4748

0.494119

0.464881

False

0.00202397

0.0226

0.025818

0.016022

False

0.00261473

0.0364

0.0416915

0.0291885

False

5

[25000:29999]

5

25000

29999

2019-03-31 03:00:00

2019-04-30 09:27:16.848000

analysis

0

0.00705286

0.452

0.478879

0.449401

False

0.00706512

0.4626

0.494119

0.464881

True

0.00202397

0.038

0.025818

0.016022

True

0.00261473

0.0474

0.0416915

0.0291885

True

6

[30000:34999]

6

30000

34999

2019-04-30 09:36:00

2019-05-30 16:03:16.848000

analysis

0

0.00705286

0.454

0.478879

0.449401

False

0.00706512

0.4616

0.494119

0.464881

True

0.00202397

0.0334

0.025818

0.016022

True

0.00261473

0.051

0.0416915

0.0291885

True

7

[35000:39999]

7

35000

39999

2019-05-30 16:12:00

2019-06-29 22:39:16.848000

analysis

0

0.00705286

0.4514

0.478879

0.449401

False

0.00706512

0.463

0.494119

0.464881

True

0.00202397

0.0364

0.025818

0.016022

True

0.00261473

0.0492

0.0416915

0.0291885

True

8

[40000:44999]

8

40000

44999

2019-06-29 22:48:00

2019-07-30 05:15:16.848000

analysis

0

0.00705286

0.4498

0.478879

0.449401

False

0.00706512

0.4726

0.494119

0.464881

False

0.00202397

0.031

0.025818

0.016022

True

0.00261473

0.0466

0.0416915

0.0291885

True

9

[45000:49999]

9

45000

49999

2019-07-30 05:24:00

2019-08-29 11:51:16.848000

analysis

0

0.00705286

0.4636

0.478879

0.449401

False

0.00706512

0.4486

0.494119

0.464881

True

0.00202397

0.0396

0.025818

0.016022

True

0.00261473

0.0482

0.0416915

0.0291885

True

The results from the reference data are also available.

```>>> display(results.filter(period='reference').to_df())
```

chunk
key
chunk_index
start_index
end_index
start_date
end_date
period
targets_missing_rate
true_positive
sampling_error
value
upper_threshold
lower_threshold
true_negative
sampling_error
value
upper_threshold
lower_threshold
false_positive
sampling_error
value
upper_threshold
lower_threshold
false_negative
sampling_error
value
upper_threshold
lower_threshold

0

[0:4999]

0

0

4999

2018-01-01 00:00:00

2018-01-31 06:27:16.848000

reference

0

0.00705286

0.4596

0.478879

0.449401

False

0.00706512

0.4866

0.494119

0.464881

False

0.00202397

0.019

0.025818

0.016022

False

0.00261473

0.0348

0.0416915

0.0291885

False

1

[5000:9999]

1

5000

9999

2018-01-31 06:36:00

2018-03-02 13:03:16.848000

reference

0

0.00705286

0.455

0.478879

0.449401

False

0.00706512

0.4844

0.494119

0.464881

False

0.00202397

0.0226

0.025818

0.016022

False

0.00261473

0.038

0.0416915

0.0291885

False

2

[10000:14999]

2

10000

14999

2018-03-02 13:12:00

2018-04-01 19:39:16.848000

reference

0

0.00705286

0.471

0.478879

0.449401

False

0.00706512

0.4752

0.494119

0.464881

False

0.00202397

0.0198

0.025818

0.016022

False

0.00261473

0.034

0.0416915

0.0291885

False

3

[15000:19999]

3

15000

19999

2018-04-01 19:48:00

2018-05-02 02:15:16.848000

reference

0

0.00705286

0.4634

0.478879

0.449401

False

0.00706512

0.4808

0.494119

0.464881

False

0.00202397

0.0196

0.025818

0.016022

False

0.00261473

0.0362

0.0416915

0.0291885

False

4

[20000:24999]

4

20000

24999

2018-05-02 02:24:00

2018-06-01 08:51:16.848000

reference

0

0.00705286

0.4674

0.478879

0.449401

False

0.00706512

0.4708

0.494119

0.464881

False

0.00202397

0.022

0.025818

0.016022

False

0.00261473

0.0398

0.0416915

0.0291885

False

5

[25000:29999]

5

25000

29999

2018-06-01 09:00:00

2018-07-01 15:27:16.848000

reference

0

0.00705286

0.458

0.478879

0.449401

False

0.00706512

0.4862

0.494119

0.464881

False

0.00202397

0.0226

0.025818

0.016022

False

0.00261473

0.0332

0.0416915

0.0291885

False

6

[30000:34999]

6

30000

34999

2018-07-01 15:36:00

2018-07-31 22:03:16.848000

reference

0

0.00705286

0.4648

0.478879

0.449401

False

0.00706512

0.4802

0.494119

0.464881

False

0.00202397

0.0206

0.025818

0.016022

False

0.00261473

0.0344

0.0416915

0.0291885

False

7

[35000:39999]

7

35000

39999

2018-07-31 22:12:00

2018-08-31 04:39:16.848000

reference

0

0.00705286

0.469

0.478879

0.449401

False

0.00706512

0.476

0.494119

0.464881

False

0.00202397

0.0216

0.025818

0.016022

False

0.00261473

0.0334

0.0416915

0.0291885

False

8

[40000:44999]

8

40000

44999

2018-08-31 04:48:00

2018-09-30 11:15:16.848000

reference

0

0.00705286

0.4682

0.478879

0.449401

False

0.00706512

0.4768

0.494119

0.464881

False

0.00202397

0.0182

0.025818

0.016022

False

0.00261473

0.0368

0.0416915

0.0291885

False

9

[45000:49999]

9

45000

49999

2018-09-30 11:24:00

2018-10-30 17:51:16.848000

reference

0

0.00705286

0.465

0.478879

0.449401

False

0.00706512

0.478

0.494119

0.464881

False

0.00202397

0.0232

0.025818

0.016022

False

0.00261473

0.0338

0.0416915

0.0291885

False

Apart from chunk and period-related columns, the results data have a set of columns for each calculated metric.

• targets_missing_rate - The fraction of missing target data.

• value - the realized metric value for a specific chunk.

• sampling_error - the estimate of the Sampling Error.

• upper_threshold and lower_threshold - crossing these thresholds will raise an alert on significant performance change. The thresholds are calculated based on the actual performance of the monitored model on chunks in the reference partition. The thresholds are 3 standard deviations away from the mean performance calculated on chunks. They are calculated during fit phase.

• alert - flag indicating potentially significant performance change. `True` if estimated performance crosses upper or lower threshold.

The results can be plotted for visual inspection. Our plot contains several key elements.

• The purple step plot shows the performance in each chunk of the analysis period. Thick squared point markers indicate the middle of these chunks.

• The blue step plot shows the performance in each chunk of the reference period. Thick squared point markers indicate the middle of these chunks.

• The gray vertical line splits the reference and analysis periods.

• The red horizontal dashed lines show upper and lower thresholds for alerting purposes.

• The red diamond-shaped point markers in the middle of a chunk indicate that an alert has been raised. Alerts are caused by the performance crossing the upper or lower threshold.

```>>> figure = results.plot()
>>> figure.show()
```

Additional information such as the chunk index range and chunk date range (if timestamps were provided) is shown in the hover for each chunk (these are interactive plots, though only static views are included here).

Insights

After reviewing the performance calculation results, we should be able to clearly see how the model is performing against the targets, according to whatever metrics we wish to track.

What’s Next

If we decide further investigation is needed, the Data Drift functionality can help us to see what feature changes may be contributing to any performance changes.

It is also wise to check whether the model’s performance is satisfactory according to business requirements. This is an ad-hoc investigation that is not covered by NannyML.