Model monitoring#
Track a score and its variables period by period. monitoring_table() gives the population, the events, the discrimination and the PSI of a score in every period, and stability_table() the PSI of every grouped variable.
See Model monitoring for examples on synthetic applications.
|
Monitor the population, event rate, discrimination and stability of a score. |
|
Monitor the population stability of grouped variables over time. |
- kivi.monitoring.monitoring_table(score, period, target=None, *, reference_period=None, reference_score=None, bins=10, smoothing=0.5, weights=None, reference_weights=None)#
Monitor the population, event rate, discrimination and stability of a score.
Each row summarizes one period, such as a month or a quarter: how many observations it has, how many events among those with a known outcome, how well the score separates the two classes and how far the distribution of the score has moved from a reference sample.
- Parameters:
- scorearray_like
Finite numeric scores that are higher for a higher event probability, such as a PD. Negate scorecard points, which are higher for a lower risk.
- periodarray_like
Period of each observation, such as the month of application, without missing values. Periods are sorted, and categorical periods follow the order of their categories. If score and period are both pandas Series, they must have identical indices; otherwise they are matched by position.
- targetarray_like, optional
Binary labels, with 1 indicating the event, and missing values for outcomes that are not known yet, such as those of loans that have not reached the end of the outcome window, matched like period. Without target, every outcome is unknown and the table only has the columns
totalandpsi.- reference_periodobject, optional
The label of the period that every period is compared with, such as the first month after the development sample. For datetime periods and pandas periods, a string that names exactly one period, such as
"2024-01"for months, selects it. Give either reference_period or reference_score.- reference_scorearray_like, optional
The scores of a reference sample that every period is compared with, such as the development sample, with any index. Pass the scores of the reference rows, such as
score[mask], rather than a boolean mask, which is rejected.- binsint or array_like, default 10
Number of quantile bands of the reference scores, or increasing band edges. An integer is the same as passing
kivi.binning.bin_edges(reference, bins=bins)for the reference scores, with their weights asweights, so tied scores can leave fewer bands than requested. Every period is compared on the same bands.- smoothingfloat, default 0.5
Positive replacement for a zero count when calculating the PSI, as in kivi.stability.psi_table, in units of weight with weights.
- weightsarray_like, optional
Non-negative weight of each observation, such as the inverse of its sampling rate, matched like period. Counts become sums of weights, and the discrimination and the PSI are weighted. On the same band edges, integer weights give the same table as repeating rows.
- reference_weightsarray_like, optional
Non-negative weight of each score of reference_score, matched like it. A reference period takes its weights from weights.
- Returns:
- pandas.DataFrame
One row per period, indexed by
period, with the columns described in the Notes.
- Raises:
- ValueError
If score or period is empty, an input is not one-dimensional, the inputs have different lengths or are Series with different indices, score is not real and numeric or has a missing or infinite value, target has a value other than 0, 1 and missing, or period has a missing value. Also if neither or both of reference_period and reference_score are given, reference_period is not one period with observations, reference_score is empty, boolean or not finite and numeric, reference_weights is given with reference_period, bins is neither a positive integer nor increasing edges, a score lies outside the edges, smoothing is not finite and positive, or a weight array is not numeric, does not give each observation one finite, non-negative weight with a positive total, or has an index other than that of its sample.
- Warns:
- UserWarning
If bins is an integer and tied reference scores leave fewer bands than requested, as in kivi.binning.bin_edges.
See also
stability_tableThe PSI of each variable of the score in each period.
kivi.metrics.roc_aucThe AUC of one sample.
kivi.stability.psi_tableThe PSI of one sample and its contributions.
Notes
The columns are:
total: observations in the period, or the sum of their weights, including those whose outcome is not known yet;known: observations with a known outcome;event: events among them;event_rate:eventdivided byknown, NaN without known outcomes;auc,giniandks: kivi.metrics.roc_auc, kivi.metrics.gini and kivi.metrics.ks of the known outcomes of the period, NaN unless both classes are present;psi: the population stability index of the period’s scores against the reference scores, on the bands described under bins.
Without a target the columns are
totalandpsi. Each row equals what the metric functions andpsi_table(pandas.cut(reference, edges), pandas.cut(period_score, edges))give for the period alone, with the weights of the two samples asreference_weightsandcurrent_weights. For a band \(i\) with shares \(q_i\) of the reference scores and \(p_i\) of the period’s scores, after smoothing,\[\mathrm{PSI} = \sum_i (p_i - q_i) \ln \frac{p_i}{q_i},\]where bands empty in both samples are left out. The reference period has a PSI of 0.
A category of a categorical period without observations, or whose weights sum to zero, keeps its row with zero counts and NaN in the other columns, so that monitoring tables of different samples line up. Here the rule differs from kivi.vintage.vintage_table and kivi.calibration.calibration_table, which leave such categories out. Other periods exist only through their observations, and those whose weights sum to zero are left out, as repeated rows would leave them out.
The discrimination of the most recent periods usually rests on few known outcomes, and the PSI of a small period mostly reflects sampling noise, so read both together with
knownandtotal.Examples
>>> import numpy as np >>> from kivi.monitoring import monitoring_table >>> score = [0.1, 0.2, 0.3, 0.4, 0.2, 0.3, 0.6, 0.7, 0.5, 0.6, 0.8, 0.9] >>> target = [0, 0, 1, 1, 0, 1, 0, 1, 0, np.nan, 1, np.nan] >>> period = ["2024-01"] * 4 + ["2024-02"] * 4 + ["2024-03"] * 4 >>> table = monitoring_table(score, period, target, reference_period="2024-01", bins=2) >>> table[["total", "known", "event", "event_rate"]] total known event event_rate period 2024-01 4 4 2 0.5 2024-02 4 4 2 0.5 2024-03 4 2 1 0.5 >>> table[["auc", "gini", "ks", "psi"]].round(4) auc gini ks psi period 2024-01 1.00 1.0 1.0 0.0000 2024-02 0.75 0.5 0.5 0.2747 2024-03 1.00 1.0 1.0 0.8087
The March outcomes of two observations are not known yet, so its discrimination rests on the other two.
- kivi.monitoring.stability_table(groups, period, *, reference_period=None, reference_groups=None, smoothing=0.5, weights=None, reference_weights=None)#
Monitor the population stability of grouped variables over time.
Each entry is the PSI of one variable in one period against a reference sample, as kivi.stability.psi_table computes it for the period alone. With the groups of a scorecard’s variables this is the variable part of a stability report, and the variables that move explain a shift of the score that monitoring_table shows.
- Parameters:
- groupspandas.DataFrame
One column per variable, holding labels or values binned using the same edges in every period, such as the result of
kivi.spec.BinningSpec.cut. Missing values form a group, and groups observed in only one sample are included.- periodarray_like
Period of each row of groups, without missing values. Periods are sorted, and categorical periods follow the order of their categories. A Series must have the index of groups.
- reference_periodobject, optional
The label of the period that every period is compared with, as in monitoring_table. Give either reference_period or reference_groups.
- reference_groupspandas.DataFrame, optional
The groups of a reference sample that every period is compared with, such as the development sample, with every column of groups and any index. Its other columns are ignored.
- smoothingfloat, default 0.5
Positive replacement for a zero count when calculating shares, in units of weight with weights.
- weightsarray_like, optional
Non-negative weight of each row of groups, matched like period. Counts become sums of weights, so integer weights give the same table as repeating rows.
- reference_weightsarray_like, optional
Non-negative weight of each row of reference_groups. A reference period takes its weights from weights.
- Returns:
- pandas.DataFrame
One row per period, indexed by
period, and one column per variable, with the columns of groups and the column index namedvariable. Each entry is the PSI of the variable in the period.
- Raises:
- ValueError
If groups is not a DataFrame, has no rows, no columns, repeated column names or more than one level of column names, period is not one-dimensional, does not have one value per row or has a missing value, or a Series argument has an index other than that of groups. Also if neither or both of reference_period and reference_groups are given, reference_period is not one period with observations, reference_groups is not a DataFrame with rows, unique column names and every column of groups, reference_weights is given with reference_period, smoothing is not finite and positive, or a weight array is not numeric, does not give each row one finite, non-negative weight with a positive total, or has an index other than that of its sample.
See also
monitoring_tableThe population, discrimination and PSI of the score.
kivi.stability.psi_tableThe PSI of one sample and its contributions.
kivi.stability.csi_tableThe change of a variable’s average points.
Notes
For a group \(i\) of a variable, with shares \(q_i\) of the reference sample and \(p_i\) of the period, after smoothing,
\[\mathrm{PSI} = \sum_i (p_i - q_i) \ln \frac{p_i}{q_i},\]over the groups observed in the reference sample or in the period. The reference period has a PSI of 0.
A category of a categorical period without observations, or whose weights sum to zero, keeps its row with NaN entries, as in monitoring_table. Other periods exist only through their rows, and those whose weights sum to zero are left out, as repeated rows would leave them out.
Examples
>>> import pandas as pd >>> from kivi.monitoring import stability_table >>> groups = pd.DataFrame({ ... "housing": ["own", "own", "rent", "rent", "own", "rent", "rent", "rent"], ... "region": ["north", "south", "north", "south", "north", "north", "south", None], ... }) >>> period = ["2024-01"] * 4 + ["2024-02"] * 4 >>> stability_table(groups, period, reference_period="2024-01").round(4) variable housing region period 2024-01 0.0000 0.000 2024-02 0.2747 0.231
One value of the February region is missing, a group that January does not have.