Variable selection#

Select the variables of a scorecard and fit its logistic regression on WOE-encoded columns. correlation_filter(), vif() and vif_filter() check the candidates for collinearity and drop the collinear ones, logistic_regression() and stepwise() fit and select the model, and selection_path() compares the models of a fixed order of variables.

See Variable selection for a selection on the bundled data.

correlation_filter(X, *[, method, ...])

Drop one variable of each strongly correlated pair.

vif(X)

Compute the variance inflation factor of each variable.

vif_filter(X, *[, threshold, priority])

Drop the variable with the largest VIF until no VIF exceeds a threshold.

logistic_regression(X, target, *[, weights])

Fit a logistic regression and test each coefficient.

stepwise(X, target, *[, p_enter, p_remove, ...])

Select variables for a logistic regression by their p-values.

selection_path(X, target, *[, order, ...])

Fit a logistic regression on each leading part of an order of variables.

SeparationError

The classes are separated, so the logistic regression has no estimates.

kivi.selection.correlation_filter(X, *, method='pearson', threshold=0.7, priority=None)#

Drop one variable of each strongly correlated pair.

Variables are visited from the highest priority to the lowest. A variable is kept unless its absolute correlation with a variable that is already kept exceeds threshold.

Parameters:
Xpandas.DataFrame or array_like

Two-dimensional numeric values with one column per variable, such as WOE values from kivi.woe.woe_transform.

method{“pearson”, “spearman”}, default “pearson”

The correlation: Pearson’s linear correlation, or Spearman’s rank correlation, the Pearson correlation of the ranks of the values with ties given their average rank, as pandas.DataFrame.corr computes it.

thresholdfloat, default 0.7

Largest absolute correlation allowed between two kept variables, between 0 and 1.

priorityarray_like, optional

One number per column, such as its information value; of two correlated variables, the one with the higher priority is kept. A pandas Series is matched to the columns by label, other inputs by position. Ties, and every column when priority is omitted, follow the column order, so earlier columns are kept.

Returns:
pandas.Index

Labels of the kept columns, in the order of X. Column positions when X is not a DataFrame.

Raises:
ValueError

If X is not two-dimensional, has fewer than 2 rows or no columns, repeats a column label, or has a column that is not numeric, contains missing or infinite values or is constant; if method is not "pearson" or "spearman"; if threshold is not between 0 and 1; or if priority does not give one number for every column.

See also

vif

Measure how well the other variables explain each variable.

stepwise

Select variables by their significance in a logistic regression.

Notes

A variable is dropped only because of a variable that is kept. When a is correlated with b and b with c, but a not with c, and the priorities decrease from a to c, then b is dropped and c is kept.

Pearson’s correlation measures how close two variables are to a straight line. It suits WOE values, which the logistic regression combines linearly. Spearman’s correlation measures how close they are to a monotone relation and is not moved by a few extreme values, which suits raw variables before binning, such as amounts with a long right tail.

Examples

>>> import pandas as pd
>>> from kivi.selection import correlation_filter
>>> X = pd.DataFrame({
...     "a": [1.0, 2.0, 3.0, 4.0, 5.0],
...     "b": [1.0, 2.0, 3.0, 5.0, 4.0],
...     "c": [2.0, 1.0, 4.0, 3.0, 1.0],
... })
>>> X.corr().round(2)
     a     b     c
a  1.0  0.90  0.00
b  0.9  1.00  0.24
c  0.0  0.24  1.00
>>> correlation_filter(X).tolist()
['a', 'c']
>>> iv = pd.Series({"a": 0.12, "b": 0.31, "c": 0.05})
>>> correlation_filter(X, priority=iv).tolist()
['b', 'c']

A relation that is strictly monotone but not linear is perfect by rank:

>>> growth = pd.DataFrame({
...     "x": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0],
...     "y": [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0],
... })
>>> growth.corr().round(2)
      x     y
x  1.00  0.85
y  0.85  1.00
>>> growth.corr(method="spearman").round(2)
     x    y
x  1.0  1.0
y  1.0  1.0
>>> correlation_filter(growth, threshold=0.9).tolist()
['x', 'y']
>>> correlation_filter(growth, method="spearman", threshold=0.9).tolist()
['x']
kivi.selection.vif(X)#

Compute the variance inflation factor of each variable.

The VIF of a variable measures how well the other variables explain it in a linear regression. It is 1 for a variable that is uncorrelated with the others and grows without bound as the variable approaches a linear combination of them.

Parameters:
Xpandas.DataFrame or array_like

Two-dimensional numeric values with one column per variable, such as WOE values from kivi.woe.woe_transform.

Returns:
pandas.Series

VIF of each column, indexed by the column labels of X (positions when X is not a DataFrame) in an index named variable, and named vif. It is infinite for a column that is a linear combination of the others.

Raises:
ValueError

If X is not two-dimensional, has fewer than 2 rows or no columns, repeats a column label, or has a column that is not numeric, contains missing or infinite values or is constant.

See also

vif_filter

Drop the variable with the largest VIF until no VIF exceeds a threshold.

correlation_filter

Drop one variable of each strongly correlated pair.

logistic_regression

Fit the scorecard model.

Notes

For column \(j\), let \(R_j^2\) be the coefficient of determination of the least-squares regression of column \(j\) on an intercept and the other columns. Then

\[\mathrm{VIF}_j = \frac{1}{1 - R_j^2}.\]

The square root of the VIF is the factor by which collinearity inflates the standard error of the variable’s coefficient. With two columns of correlation \(r\), both have a VIF of \(1 / (1 - r^2)\).

A column counts as a linear combination of the others, with an infinite VIF, when it is one up to rounding: when the singular value decomposition of the standardized columns gives it a component in their null space, or when its VIF reaches \(1 / \epsilon \approx 4.5 \cdot 10^{15}\), so that \(1 - R_j^2\) is at most the machine epsilon \(\epsilon\), the spacing of double-precision numbers at 1. Two rows, for example, make any two columns collinear.

Examples

Two columns with a correlation of 0.9 both have a VIF of \(1 / (1 - 0.9^2) = 5.263\):

>>> import pandas as pd
>>> from kivi.selection import vif
>>> X = pd.DataFrame({"a": [1.0, 2.0, 3.0, 4.0, 5.0], "b": [1.0, 2.0, 3.0, 5.0, 4.0]})
>>> print(f"{X['a'].corr(X['b']):.2f}")
0.90
>>> vif(X).round(3)
variable
a    5.263
b    5.263
Name: vif, dtype: float64

Adding their sum makes every column a linear combination of the others:

>>> vif(X.assign(total=X["a"] + X["b"]))
variable
a        inf
b        inf
total    inf
Name: vif, dtype: float64
kivi.selection.vif_filter(X, *, threshold=5.0, priority=None)#

Drop the variable with the largest VIF until no VIF exceeds a threshold.

Each round computes the vif of the variables that are still kept. If the largest is at most threshold, they are all kept and the elimination stops; otherwise the variable with the largest VIF is dropped and the next round starts. A single variable, whose VIF is 1, is always kept.

Parameters:
Xpandas.DataFrame or array_like

Two-dimensional numeric values with one column per variable, such as WOE values from kivi.woe.woe_transform.

thresholdfloat, default 5.0

Largest VIF allowed for a kept variable, a finite number greater than 1.

priorityarray_like, optional

One number per column, such as its information value, matched to the columns as in correlation_filter: a pandas Series by label, other inputs by position. Of several variables whose VIFs tie for the largest, such as variables with infinite VIFs, the one with the lowest priority is dropped. Ties of priority, and every tie when priority is omitted, drop the last of the tied variables in the column order, so that earlier columns are kept, as in correlation_filter.

Returns:
pandas.Index

Labels of the kept columns, in the order of X. Column positions when X is not a DataFrame.

Raises:
ValueError

If X is not two-dimensional, has fewer than 2 rows or no columns, repeats a column label, or has a column that is not numeric, contains missing or infinite values or is constant; if threshold is not a finite number greater than 1; or if priority does not give one number for every column.

See also

vif

Compute the VIFs of one set of variables.

correlation_filter

Drop one variable of each strongly correlated pair.

Notes

Dropping a variable lowers the VIFs of the variables that it helped to explain, so a variable whose VIF exceeds threshold in the first round may be kept in the end. Each round therefore drops a single variable.

A variable that is a linear combination of the others has an infinite VIF, and so does every other variable of that combination (see vif). Such variables tie, and dropping one of them, the one with the lowest priority or else the last in the column order, usually leaves the others with finite VIFs. VIFs within a relative \(10^{-10}\) of the largest count as tied, so that rounding does not decide between variables whose VIFs are equal, such as the two variables of a pair.

Examples

c is nearly the sum of a and b, so all three have large VIFs, and d is unrelated to them:

>>> import pandas as pd
>>> from kivi.selection import vif, vif_filter
>>> X = pd.DataFrame({
...     "a": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
...     "b": [2.0, 1.0, 4.0, 3.0, 6.0, 5.0],
...     "c": [3.2, 2.9, 7.1, 6.8, 11.1, 11.0],
...     "d": [1.0, -1.0, -1.0, 1.0, 1.0, -1.0],
... })
>>> vif(X).round(1)
variable
a     577.8
b     952.8
c    2747.5
d       1.3
Name: vif, dtype: float64
>>> kept = vif_filter(X)
>>> kept.tolist()
['a', 'b', 'd']
>>> vif(X[kept]).round(2)
variable
a    3.55
b    3.55
d    1.12
Name: vif, dtype: float64

Dropping c, the variable with the largest VIF, leaves a and b with VIFs below 5, although they were above 500 in the first round.

The three variables of an exact linear combination all have an infinite VIF. Without priority, the last of them in the column order is dropped; with the information values as priority, the least predictive one is:

>>> Z = pd.DataFrame({"a": X["a"], "d": X["d"], "e": X["a"] + X["d"]})
>>> vif(Z)
variable
a    inf
d    inf
e    inf
Name: vif, dtype: float64
>>> vif_filter(Z).tolist()
['a', 'd']
>>> vif_filter(Z, priority=pd.Series({"a": 0.3, "d": 0.1, "e": 0.2})).tolist()
['a', 'e']
kivi.selection.logistic_regression(X, target, *, weights=None)#

Fit a logistic regression and test each coefficient.

The model has an intercept and one coefficient per column of X. The coefficients are maximum likelihood estimates, and each is tested against zero with a Wald test.

Parameters:
Xpandas.DataFrame or array_like

Two-dimensional numeric values with one column per variable, such as WOE values from kivi.woe.woe_transform.

targetarray_like

Binary labels, with 1 indicating the event. If X is a DataFrame and target a Series, they must have identical indices; otherwise they are matched by position.

weightsarray_like, optional

Non-negative frequency weight of each row, matched like target: a row with weight 2 counts as two identical observations, so integer weights give the same estimates, standard errors and log-likelihood as repeating rows. Rows with zero weight are left out of the fit. See the Notes on weights that do not count observations.

Returns:
pandas.DataFrame

One row for the intercept, labelled intercept, and one for each column of X, with the coefficient, its standard error, the Wald z statistic and its two-sided p-value, in an index named variable. attrs["log_likelihood"] holds the maximized log-likelihood and attrs["converged"] whether the fit converged.

Raises:
SeparationError

If the columns separate the classes, so that the estimates do not exist.

ValueError

If X is not two-dimensional, has fewer than 2 rows or no columns, repeats a column label, has a column labelled intercept, or has a column that is not numeric, contains missing or infinite values, is constant or is a linear combination of the intercept and the columns before it, or so close to one that its coefficient cannot be estimated; if target is not one-dimensional, its index or length does not match X, or it does not contain both 0 and 1 or has missing or other labels; or if weights is not numeric, does not give each row one finite, non-negative weight, or leaves a class without weight. With weights, only the checks for constant columns and linear combinations are limited to the rows with positive weight.

Warns:
RuntimeWarning

If the fit does not converge for a reason other than separation.

See also

stepwise

Select the columns of the model by their p-values.

vif

Check the columns for collinearity.

kivi.woe.woe_transform

Encode groups with their WOE.

Notes

The model is

\[\ln \frac{P(y = 1)}{P(y = 0)} = \beta_0 + \sum_j \beta_j x_j.\]

The estimates are found by Newton-Raphson, also known as iteratively reweighted least squares, on centred and scaled columns, so that an offset or the unit of a column does not affect their accuracy. The standard errors are the square roots of the diagonal of the inverse Fisher information, \(z = \hat\beta / \mathrm{se}\), and the p-value is \(P(|Z| > |z|)\) for a standard normal \(Z\).

With WOE-encoded variables, the coefficients are expected to be positive: see stepwise.

With weights \(w_i\), the estimates maximize the weighted log-likelihood \(\sum_i w_i [y_i \ln p_i + (1 - y_i) \ln(1 - p_i)]\), and the standard errors come from the weighted Fisher information \(\sum_i w_i p_i (1 - p_i) x_i x_i^\top\). These are frequency weights, as in statsmodels’ GLM(freq_weights=...): the total weight counts as the number of independent observations, so multiplying every weight by \(c\) divides the variances by \(c\). Integer weights that count repeated rows therefore give the standard errors of the repeated rows. Weights that do not count observations do not: those of kivi.reject_inference.fuzzy_augmentation, which split each rejected applicant into a bad and a good row, and those of kivi.reject_inference.reweighting, which let each accepted applicant stand for several, make the standard errors too small and the p-values too low. The inferred rows and the extra weight count as observations, although they add no observed outcomes.

References

[1]

D. W. Hosmer, S. Lemeshow and R. X. Sturdivant, “Applied Logistic Regression”, 3rd ed., Wiley, 2013.

Examples

With a single binary variable, the coefficient is the log odds ratio: the odds of the event are 1:3 at x = 0 and 3:1 at x = 1, so the coefficient is \(\ln 9\) and the intercept \(\ln(1/3)\).

>>> import pandas as pd
>>> from kivi.selection import logistic_regression
>>> X = pd.DataFrame({"x": [0, 0, 0, 0, 1, 1, 1, 1]})
>>> target = pd.Series([0, 0, 0, 1, 0, 1, 1, 1])
>>> logistic_regression(X, target).round(4)
             coef      se       z  p_value
variable
intercept -1.0986  1.1547 -0.9514   0.3414
x          2.1972  1.6330  1.3455   0.1785

Integer weights count repeated rows, so the four distinct rows with their counts give the same fit:

>>> distinct = pd.DataFrame({"x": [0, 0, 1, 1]})
>>> logistic_regression(distinct, [0, 1, 0, 1], weights=[3, 1, 1, 3]).round(4)
             coef      se       z  p_value
variable
intercept -1.0986  1.1547 -0.9514   0.3414
x          2.1972  1.6330  1.3455   0.1785
kivi.selection.stepwise(X, target, *, p_enter=0.05, p_remove=0.1, direction='both', positive=True, weights=None)#

Select variables for a logistic regression by their p-values.

Forward selection starts from the intercept and adds, one at a time, the variable with the smallest p-value while that p-value is below p_enter. Backward elimination starts from all variables and removes, one at a time, the variable with the largest p-value while that p-value is above p_remove. Selection in both directions adds variables like forward selection, but after each addition removes the variables that no longer meet p_remove.

Parameters:
Xpandas.DataFrame or array_like

Two-dimensional numeric values with one column per candidate variable, such as WOE values from kivi.woe.woe_transform.

targetarray_like

Binary labels, with 1 indicating the event. If X is a DataFrame and target a Series, they must have identical indices; otherwise they are matched by position.

p_enterfloat, default 0.05

A variable enters only if its p-value in the extended model is below this level, which is greater than 0 and at most 1.

p_removefloat, default 0.10

A variable is removed if its p-value is above this level, which is greater than 0 and at most 1 and, in both directions, not below p_enter.

direction{“both”, “forward”, “backward”}, default “both”

Whether variables are added and removed, only added, or only removed.

positivebool, default True

Keep every coefficient of the selected model positive. A variable enters only if all coefficients of the extended model are positive, and a variable whose coefficient is not positive is removed before any other, starting with the smallest z statistic.

weightsarray_like, optional

Non-negative frequency weight of each row, as in logistic_regression. Integer weights select the same variables as repeating rows. The p-values depend on the scale of the weights as they do on the sample size. The weights of reject inference make them too low, so that more variables enter than the observed outcomes support; select the variables on the accepted applicants instead.

Returns:
pandas.Index

Labels of the selected columns, in the order of X. Column positions when X is not a DataFrame.

Raises:
SeparationError

If direction is "backward" and the model with every column separates the classes.

ValueError

If X, target or weights is invalid as described for logistic_regression, in every direction; if p_enter or p_remove is not greater than 0 and at most 1, or p_enter exceeds p_remove when direction is "both"; or if direction is not one of the three options or positive is not a boolean.

Warns:
RuntimeWarning

If the model of the selected variables does not converge for a reason other than separation.

See also

logistic_regression

Fit the selected model and read its coefficients.

selection_path

Fit the models of a fixed order of variables.

correlation_filter

Drop strongly correlated variables first.

Notes

The p-values are those of the Wald tests reported by logistic_regression. Each candidate is tested in the model made of the selected variables and the candidate, so every step refits one model per candidate. A candidate does not enter if that model would separate the classes, does not converge or is numerically singular. In both directions, a variable cannot enter if that would recreate a set of variables that was selected before, which guarantees that the selection stops.

kivi defines the WOE of a group as the log of its share of events over its share of non-events, so a higher WOE means a higher event rate. In a logistic regression of target on a single WOE-encoded variable, the coefficient is therefore positive; it is exactly 1 when no cell needed smoothing. A negative coefficient in a model with several variables means that the variable’s effect is reversed by the others, usually because of collinearity, and makes the scorecard points of its bins contradict their event rates. positive=True rules out such models.

References

[1]

D. W. Hosmer, S. Lemeshow and R. X. Sturdivant, “Applied Logistic Regression”, 3rd ed., Wiley, 2013.

[2]

N. Siddiqi, “Credit Risk Scorecards: Developing and Implementing Intelligent Credit Scoring”, Wiley, 2006.

Examples

>>> import pandas as pd
>>> from kivi.datasets import load_bank
>>> from kivi.selection import stepwise
>>> from kivi.woe import woe_table, woe_transform
>>> data = load_bank()
>>> columns = ["poutcome", "contact", "housing", "loan", "marital", "default"]
>>> X = pd.DataFrame({
...     column: woe_transform(data[column], woe_table(data[column], data["target"]))
...     for column in columns
... })
>>> stepwise(X, data["target"]).tolist()
['poutcome', 'contact', 'housing', 'loan', 'marital']
kivi.selection.selection_path(X, target, *, order=None, validation=None, weights=None)#

Fit a logistic regression on each leading part of an order of variables.

Step \(k\) is the logistic regression of target on the first \(k\) variables of order, fitted as logistic_regression fits it. Each step reports how well its model ranks the development sample and, optionally, a validation sample, and the largest p-value and the smallest coefficient of its variables, so that the table shows where adding variables stops paying.

Parameters:
Xpandas.DataFrame or array_like

Two-dimensional numeric values with one column per candidate variable, such as WOE values from kivi.woe.woe_transform.

targetarray_like

Binary labels, with 1 indicating the event. If X is a DataFrame and target a Series, they must have identical indices; otherwise they are matched by position.

ordersequence, optional

The variables in the order in which they enter, such as the columns sorted by information value: labels of the columns of X, or column positions when X is not a DataFrame. It may leave columns out and gives one step per entry. Default every column, in the order of X.

validationtuple, optional

A validation sample (X_valid, target_valid), scored with the models fitted on X. X_valid holds the variables of order: a DataFrame with their labels when X is a DataFrame, otherwise values with as many columns as X, matched by position. target_valid holds both classes and is matched to X_valid as target is to X.

weightsarray_like, optional

Non-negative frequency weight of each row of X, matched like target, as in logistic_regression. The fits and the metrics on X use them, so integer weights give the same table as repeating rows. Each row of the validation sample counts once.

Returns:
pandas.DataFrame

One row per step, in an index named step that counts the steps from 1, with the columns:

  • variable: the variable that the step adds;

  • auc, gini and ks: the area under the ROC curve, the Gini coefficient and the KS statistic of the fitted probability on X, as kivi.metrics.roc_auc, kivi.metrics.gini and kivi.metrics.ks compute them;

  • max_p_value: the largest Wald p-value of the step’s variables, without the intercept;

  • min_coefficient: the smallest coefficient of the step’s variables, without the intercept;

  • validation_auc, validation_gini and validation_ks, only with validation: the same metrics on the validation sample.

Raises:
SeparationError

If the model of a step separates the classes; the message names the step and the variable that it adds.

ValueError

If X, target or weights is invalid as described for logistic_regression, where the columns before a variable are those before it in order; if order is not a sequence of distinct columns of X; or if validation is not a pair whose values have the variables of order and are numeric and finite, and whose labels are 0 and 1 with both classes present.

Warns:
RuntimeWarning

If the model of a step does not converge for a reason other than separation.

See also

stepwise

Select the variables of the model by their p-values.

logistic_regression

Fit the model of one step and read its coefficients.

kivi.metrics.roc_auc

Compute the AUC of a score.

Notes

The steps add the variables in a fixed order; nothing is selected or removed on the way. The order comes from outside the model, usually from the univariate strength of each variable, as in the forward procedure of many scorecard tools. stepwise instead chooses each variable by its p-value in the model.

The AUC on the development sample almost always rises with every variable, because each model is fitted to that sample. On a validation sample it stops rising, or falls, once the variables add more noise than information, which is where the order is usually cut. A min_coefficient at or below 0 marks a model in which a WOE-encoded variable works against its own event rates, which stepwise with positive=True rules out.

The metrics are computed from the linear predictor \(\hat\beta_0 + \sum_j \hat\beta_j x_j\). It ranks the rows as the fitted probability does, without the ties that would appear where probabilities close to 0 or 1 round to the same number.

Examples

>>> import pandas as pd
>>> from kivi.datasets import load_bank
>>> from kivi.selection import selection_path
>>> from kivi.woe import woe_table, woe_transform
>>> data = load_bank()
>>> development, validation = data.iloc[:3000], data.iloc[3000:]
>>> columns = ["poutcome", "contact", "housing", "loan", "marital", "default"]
>>> tables = {
...     column: woe_table(development[column], development["target"]) for column in columns
... }
>>> def encode(sample):
...     return pd.DataFrame(
...         {column: woe_transform(sample[column], tables[column]) for column in columns}
...     )
>>> path = selection_path(
...     encode(development),
...     development["target"],
...     validation=(encode(validation), validation["target"]),
... )
>>> path[["variable", "auc", "validation_auc", "max_p_value", "min_coefficient"]].round(4)
      variable     auc  validation_auc  max_p_value  min_coefficient
step
1     poutcome  0.6065          0.6162       0.0000           1.0000
2      contact  0.6548          0.6758       0.0000           0.7697
3      housing  0.6781          0.6956       0.0000           0.6702
4         loan  0.6918          0.7083       0.0017           0.6783
5      marital  0.7070          0.7070       0.0021           0.6602
6      default  0.7078          0.7076       0.7327          -1.3508

The AUC on the development sample rises with every step, while on the validation sample it peaks at step 4. default adds nothing: its p-value is 0.73 and its coefficient negative.

exception kivi.selection.SeparationError#

The classes are separated, so the logistic regression has no estimates.

A combination of the variables predicts the target without error, for every observation (complete separation) or for every observation off a boundary (quasi-complete separation). The likelihood then keeps growing as the coefficients grow, so the maximum likelihood estimates do not exist.

See also

logistic_regression

Raises this error.

stepwise

Leaves out candidates that separate the classes.

Examples

>>> import pandas as pd
>>> from kivi.selection import SeparationError, logistic_regression
>>> X = pd.DataFrame({"x": [1.0, 2.0, 3.0, 4.0]})
>>> try:
...     logistic_regression(X, [0, 0, 1, 1])
... except SeparationError:
...     print("x separates the classes")
x separates the classes