Migration guide#
From 0.9 to 1.0#
kivi 1.0 removes what 0.9 deprecated. Code that runs on 0.9 without a FutureWarning runs on 1.0 unchanged, except where it imports Dataset or uses the result of woe() for Series counts. To find the calls to change, run the code or its tests on 0.9 with FutureWarning turned into an error, as python -W error::FutureWarning or pytest -W error::FutureWarning do.
0.9 |
1.0 |
|---|---|
|
Raises a |
|
Raise a |
|
Returns a Series named |
|
Removed, together with the class |
|
Removed. Pass |
kivi 1.0 still supports Python 3.10, NumPy 1.24 and pandas 2.0. From 1.0 on, kivi follows semantic versioning: a deprecation keeps working with a FutureWarning until the next major release. Compatibility describes what a release may change.
From 0.2.x#
The functions below replace the 0.2.x classes. The example data of Dataset.bank_data(), which 1.0 removed, come from kivi.datasets.load_bank(). The target describes deposit subscription.
0.2.x |
Replacement |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
Explicit edges, such as |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Binning and WOE#
DistanceBins and FrequencyBins previously calculated group assignments and statistics together. Use bin_edges with uniform or quantile, call pandas.cut, then pass the groups to woe_table. Codes listed in abnormal_vals become the special argument: pass them to bin_edges, and use kivi.binning.cut with the same codes in place of pandas.cut. CategoryBins users can pass the label series directly.
Version 0.5.0 adds woe_transform in place of WOEScore. WOEScore matched raw values against the min_bin and max_bin columns of a WOE table. Form the groups with the development edges instead, then pass them to woe_transform with the woe_table result. A value that matches no group raises an error, as WOEScore did with error=”error”; pass unseen to choose its WOE instead.
Version 0.4.0 adds chimerge_edges and tree_edges in place of Chi2Bins and TreeBins. They are new implementations rather than ports, so the edges can differ. Chi2Bins started from 10 quantile bins, tested at a 0.9 confidence level, added 0.5 to every expected count and kept at least three bins; chimerge_edges(values, target, alpha=0.1, initial_bins=10) comes closest. TreeBins reported the midpoints that scikit-learn chooses as thresholds, while tree_edges reports the largest observed value below each cut. Compare the edges on a fixed reference sample before switching.
Codes listed in abnormal_vals of Chi2Bins and TreeBins become the special argument of chimerge_edges and tree_edges. As before, the codes and their labels are left out of the fit; pass the same codes to kivi.binning.cut to give each one its own group.
Population stability#
For PSI.fit(), form both sets of groups using the same reference edges, then call psi_table. It returns raw counts and a contribution per bin. Previously the psi column repeated the overall total. The new smoothing rule preserves counts and normalizes each distribution after replacing zeros. Recheck thresholds when migrating saved analyses.
Models, scorecards and calibration#
These modules are new implementations, so compare their output with the legacy code on a fixed reference sample before switching.
The legacy
liftcolumn was cumulative. Ingains_table,liftis the lift of each band andcum_liftthe cumulative lift. The metrics take a score that rises with risk, such as a PD; pass-scorefor scorecard points.ModelEvaluaterescaled each sample by its own minimum and maximum, so its scores were not comparable across samples; the new functions use the scores as given.VIFcalled statsmodels without a constant, which measures uncentred R²;vifincludes an intercept in every auxiliary regression, as in the textbook definition, so the values differ.stepwiseselects variables by their p-values and by default keeps every coefficient positive, as WOE inputs require. It is new:StepWisecompared the models of a fixed order of the variables instead, asselection_pathdoes from 1.4.0.logistic_regressionfits the model in NumPy, so statsmodels is no longer needed.BaseScoreAndPDOtook bad:good odds, for exampleodds=1/50.base_oddsis good:bad, so passbase_odds=50; passing1/50silently gives an offset of 712.9. The legacyPDToScoredivided by ln 2 only in one of its branches;pd_to_scoreandscore_to_pdare exact inverses.get_omegabecomesprior_correctionfor probabilities andcorrected_interceptfor the model intercept.
Portfolio analysis and production binning#
Version 0.6.0 replaces three more legacy classes. They are new implementations as well, so compare their output with the legacy code on a fixed reference sample before switching.
WOEBatchfitted the WOE of many columns at once, andManualBinsToolmerged bins by hand afterwards.fit_specfits every column with the binning function chosen for it, and itsBinningSpecsaves the edges and WOE tables as versioned JSON. Nothing is re-binned automatically: to merge bins by hand, pass the merged edges for that column inbins.CSImatched the points to the bins by position and lost the missing group.csi_tablematches the points to the groups by label, keeps the missing group, and raises for an observed group without points unlessunseen_pointsgives them. Its contributions sum to the change of the variable’s average points.VintagePdbuilt the vintage table from repayment schedules and observation dates.vintage_tabletakes a long panel with one row per loan and month on book and a bad flag that you define, for examplestatus == "90+", and from 1.2.0delinquency_panelbuilds that panel from the schedules and the payments. Passweights=amountfor the amount-weighted rates ofVintagePd. Months that a cohort has not reached are NaN rather than 0.
Master scales, variable profiles and strategy#
Version 0.7.0 replaces the legacy master scale and variable profile. Compare their output with the legacy code on a fixed reference sample before switching.
MasterScale.fit_grade_dfandconfirm_master_scalebecomefit_grade_pdandmaster_scale.fit_grade_pdfits the logarithm of the default rate by least squares weighted with the number of observations of each grade, where the legacy fit gave every grade the same weight; the two agree when the grades are equally large. A grade without defaults enters the fit with half a default instead of a logarithm of zero. The bounds between grades are the geometric means of adjacent PDs; passboundary="arithmetic"for the midpoints of the legacy scale.PDToRant(pd, ranking)becomesassign_grades(probability, scale). The legacy function put a PD that lies exactly on a bound in the grade above it;assign_gradesputs it in the grade below, as the intervals ofpandas.cutare closed on the right. It returns an ordered categorical of the grade labels instead of grade numbers.FeatureEvaluate(df, target_name).stats()becomesprofile_table(frame.drop(columns=target_name), frame[target_name]). The columns follow kivi’s names, such asmissing_share,missing_event_rateandnon_missing_lift, and a target without events raises an error, where the legacy lifts were -9999. The signed Gini coefficient of the values replaces the AUC and KS of a univariate logistic fit. The table adds the IV of a quick binning, special codes, sample weights and thetied_binscolumn.Strategy analysis, reject inference and weighted model fits have no 0.2.x counterpart.
kivi.strategyreplaces approval and bad-rate tables built by hand from score bands,kivi.reject_inferenceinfers the outcomes of declined applicants, andlogistic_regressionandstepwisetakeweightsto refit on them.
Category grouping, validation and monitoring#
Version 0.8.0 groups categorical variables, adds the ROC table and the uncertainty of an AUC, and monitors a model period by period. These are new implementations as well.
CategoryBinskept the labels of a categorical variable as they were.category_groupspools the rare categories andchimerge_groupsmerges the categories with similar event rates; both return a dictionary from category to group that is fitted on the reference sample, andgroup_categoriesapplies it to every sample. A category that the grouping does not know raises an error unlessunseennames its group.fit_specgroups a column with the methods"rare"and"chimerge", and a specification that groups a column is saved as format version 2, which 0.7.0 and earlier refuse to read.BinaryMetrics.roc_curvereturned the points of scikit-learn’sroc_curvewith its defaultdrop_intermediate=True.roc_tablehas one row for every distinct score, asroc_curvewithdrop_intermediate=False, with the cumulative counts, the two rates and the precision. Itsprecisionandtrue_positive_ratecolumns are the precision and the recall at each threshold, so it also gives the precision-recall curve, whichprecision_recall_chartdraws from 1.4.0.roc_auc_intervaladds the DeLong standard error and interval of the AUC and the Gini, anddelong_testcompares the AUCs of two scores on the same sample; the legacy code had neither.ScoreEvaluate.score_psiandadd_psicompared the band totals of two lift tables.monitoring_tablecompares every period with one reference sample on score bands fitted once, adds the known outcomes, the AUC, the Gini and the KS of each period, and counts an observation without a known outcome in the population only.stability_tablegives the PSI of every variable in every period.Lifetime PD term structures, the IFRS 9 expected credit loss and the allocation to stages have no 0.2.x counterpart; see
kivi.lifetime.
Charts, classification measures and variable statistics#
Version 1.1.0 draws charts and adds the measures of a classifier and more statistics to the variable profile.
plot_binandDefaultAnalysisdrew the bins of a variable from raw data,Calibration.CalibrationCurvethe predicted against the observed rate,BinaryMetrics.plot_rocandplot_ksthe ROC and KS curves, anddiagonal_corrandstructure_corrcorrelation heatmaps. The functions ofkivi.plottingdraw the tables that kivi returns instead:woe_chartawoe_table,calibration_chartacalibration_table,roc_chartandgains_chartaroc_tableand agains_tablewith the KS, soplot_ksbecomesgains_chartwith its defaultks=True, andcorrelation_charta correlation matrix such asX.corr(). They return the matplotlib Axes rather than saving image files, and they need matplotlib, whichpip install "kivi[plot]"installs.The F1 score and the confusion matrix of
BinaryMetricsjudged labels that the caller had predicted.confusion_table(score, target, cutoffs=...)takes a score and the cut-offs ofcutoff_tableinstead: a score above the cut-off is declined, and a declined event is a true positive. Pass labels already predicted as the score withcutoffs=[0]to get the legacy counts. Where nothing is declined, the precision is NaN, where the legacy code gave 0 with a warning, and the table has noliftcolumn; divideprecisionby the event rate for it.The skewness, kurtosis and coefficient of variation of
FeatureEvaluateare theskewness,kurtosisandcvcolumns ofprofile_table.cvis NaN when the mean is 0, where the legacy code gave -9999.ksis the KS statistic of the values themselves, which the legacyks_testcomputed with SciPy, without its p-value.chi2_p_valuetests the groups of the quick binning against the target, while the legacy chi-squared test was scikit-learn’schi2on the raw values, so the two p-values differ.Corr.spearmanrgave the Spearman correlation of each pair of columns.correlation_filter(X, method="spearman")drops one variable of each pair whose Spearman correlation is too high;X.corr(method="spearman")gives the matrix itself.
Delinquency panels, KS binning and expert weights#
Version 1.2.0 builds delinquency panels from repayment schedules, adds Best-KS binning and weighs the factors of expert scorecards. These are new implementations as well, so compare their output with the legacy code on a fixed reference sample before switching.
PortfolioAnalysis.VintageandVintagePdderived the delinquency of each loan from its repayment schedule at month-end observation dates.delinquency_panel(loan, due_date, amount_due, payment_loan, payment_date, payment_amount, end=...)builds that panel from the schedule and the payments as they were made, andvintage_tableturns it into vintage curves. The rules differ from the legacy code in the following ways:The legacy schedule had one row per instalment with its own payment date and remaining amounts, so the source system had already allocated the payments.
delinquency_panelapplies the payments to the oldest unpaid instalment first.The legacy code counted an instalment as unpaid only while its interest was unpaid, so unpaid principal alone did not make a loan delinquent.
delinquency_panelcounts the whole amount due, up totolerance.For a loan with nothing unpaid, the legacy code took the days from the due date to the payment date of its latest instalment, so a loan that paid its latest instalment late kept those days after catching up.
delinquency_panelgives such a loan 0 days.VintagePdleft out of an observation a loan whose first instalment was paid but a later one was not, while the SparkVintagekept its earliest unpaid instalment.delinquency_panelkeeps every loan from its first due month until it is repaid.The legacy buckets were M0 = 0, M1 = 1–30, M2 = 31–60, M3 = 61–90 and M4+ over 90 days.
statushascurrent,1-29,30-59,60-89and90+(90 days or more), so a loan exactly 30, 60 or 90 days past due falls one bucket later. Usedays_past_due > 90for the legacy M4+.The legacy cohort was the month of the origination date
loan_date. Pass the origination dates asoriginationfor the same cohorts.month_on_bookthen counts the months from the origination month, 0 at its end, so it is one less than the legacybook_month, which rounded the months from the first day of the origination month to the observation date; add 1 for the legacy numbering. Withoutorigination,cohortis the month before the first due date andmonth_on_bookis 1 in the first due month, which counts from the origination month only when the first instalment falls due a month after origination.The legacy remaining principal subtracted only the principal paid on instalments due by the observation date.
balancecounts every payment made by the month end, including payments made ahead.The legacy code observed every loan at
observe_periodmonth ends fromobserve_date.delinquency_panelobserves each loan from the month of its first due date toend, and drops it after the month end at which it is repaid.VintagePdreported, at each observation date, the remaining principal of the M4+ loans as a share of the cohort’s amount lent. That is a point-in-time rate, which falls when loans cure or are repaid.vintage_tablecounts the loans that were ever bad, by number or by a weight such as the amount lent. For the legacy rate, sumbalancewheredays_past_due > 90by cohort and month on book, and divide by the amount lent.
ks_edgesreplacesKSBins. It is a new implementation, so the edges can differ.KSBinsalways split the largest bin, whileks_edgessplits the bin whose cut ranks the most pairs of an event and a non-event apart, and stops when no bin has an allowed cut that separates the classes.KSBinsraised an error instead when the largest bin had no allowed cut, for example when a special code such aspdays == -1filled it, or when it held one class only.min_sample_ratecounted every row, missing values andabnormal_valsincluded, whilemin_bin_sharecounts only the fitted values, in weight;weightdid not affect the cuts ofKSBins, while the cuts ofks_edgesuse sums of weights. Both put each edge at the largest value of the bin to its left and break ties towards the smallest value. Codes listed inabnormal_valsbecome thespecialargument, as fortree_edges, andfit_specfits a column withks_edgeswhen itsmethodis"ks".The
AHPclass took a long frame with the columnsgroup,experimental,controlandvalue, weighed each group by the geometric means of the rows of its comparison matrix and estimated the principal eigenvalue as the mean of \((A w)_i / w_i\) for those weights.ahp_weights(matrix, method="geometric")gives the same weights for one comparison matrix, andahp_consistencythe CI and CR. kivi’s default is the exact principal eigenvector. For up to three factors it gives the same weights, eigenvalue and CR as the legacy estimate; from four factors on they differ slightly when the judgments are inconsistent.weight()returned one frame with the columnsdst, the factor,geo_mean, the geometric mean of its row, andgroup_weight, its weight within the group, with the groups one after the other in sorted order and no group column.group_ciandgroup_crheld the CI and CR of each group. Weigh each group on its own and join the results, as the example below shows;np.exp(np.log(matrix).mean(axis=1))givesgeo_meanif it is needed, andcombine_weightsmultiplies the weights of groups and of their factors into global weights.The legacy random indices are the same for 3 to 11, 13 and 15 factors, but 1.54 for 12 and 1.58 for 14 factors, where
ahp_consistencyuses the 1.53 and 1.57 of Tone’s table, and the legacy table went on to 1.60 for 16 factors, for whichahp_consistencyraises an error. For one factor the legacy CI was NaN with aRuntimeWarning; for one or two factorsahp_consistencyreturns 0 forci,riandcr. A CR above 0.1 is no error in either: the legacy class logged it in red, andahp_consistencyreturns it for the reader to judge.
A long frame of the legacy layout, with one group of three factors and one of two, becomes one matrix per group:
>>> import numpy as np
>>> import pandas as pd
>>> from kivi.expert import ahp_consistency, ahp_weights
>>> long = pd.DataFrame(
... {
... "group": ["finance"] * 9 + ["market"] * 4,
... "experimental": np.repeat(["coverage", "leverage", "margin", "position", "share"], [3, 3, 3, 2, 2]),
... "control": ["coverage", "leverage", "margin"] * 3 + ["position", "share"] * 2,
... "value": [1, 1 / 2, 3, 2, 1, 4, 1 / 3, 1 / 4, 1, 1, 3, 1 / 3, 1],
... }
... )
>>> weights, statistics = {}, {}
>>> for name, group in long.groupby("group"):
... matrix = group.pivot(index="experimental", columns="control", values="value")
... weights[name] = ahp_weights(matrix, method="geometric")
... statistics[name] = ahp_consistency(matrix)
>>> pd.concat(weights, names=["group"]).round(4)
group factor
finance coverage 0.3196
leverage 0.5584
margin 0.1220
market position 0.7500
share 0.2500
Name: weight, dtype: float64
>>> pd.DataFrame(statistics).T[["ci", "cr"]].round(4)
statistic ci cr
finance 0.0091 0.0158
market 0.0000 0.0000
Time-window and repayment features#
Version 1.3.0 computes features of event data and of monthly repayment statuses, the work of FeatureTools, FeatureToolsV2 and index/collect.py. These are new implementations as well, so compare their output with the legacy features on a fixed sample before switching.
The legacy tools ran on Spark DataFrames and wrote long tables of
uuid,index_name,index_valandload_dateinto Hive partitions.window_features()andpanel_features()take pandas DataFrames and return a wide DataFrame with one column per feature, on the index of the observations;DataFrame.meltgives a long table where one is needed. A backfill, whichbatch_derivative_indexran date by date, is one call with a row for every entity and snapshot date in the observations.The legacy windows included the snapshot date.
one_batch_datakept the rows whosemonths_between(now_date, load_date), a fractional number of months, lay between 0 andmonth - 1, andFeatureToolsandCollectIndextook the month of the snapshot date as the last month of every window. kivi’s windows are point in time:window_featurestakes \([t - k, t)\) by default, without the events at the observation time, andclosed="right"gives \((t - k, t]\), the closest equivalent to the legacy windows for records that are complete at the end of their day. Months are calendar months, counted aspandas.DateOffsetcounts them.panel_featuresuses only the months before the month of the observation time, because the status at the end of that month is not known yet.FeatureToolsaggregated the amounts and counts of each month first, with itsagg_type, and then took the sum, mean, extremes and standard deviation of these monthly totals over each window, so itsamt_maxwas the largest monthly total.window_featuresaggregates the events themselves; to aggregate monthly totals, pass them as events dated at the start of the next month, when they are complete. Itsfilter_rulesbecome filtered event tables with their ownprefix, one group each in aFeatureSpec. Its ratios to the window twice as long, to the window of twelve months and to the window before (div2tr,div1yandchain_rate) areratios, such as("amount_sum_3m", "amount_sum_6m"),("amount_sum_3m", "amount_sum_12m")and("amount_sum_3m", "amount_sum_6m_3m")with the window pair("6M", "3M"). A ratio is NaN where its denominator is 0 or missing, whereFeatureToolssubtracted 1e-6 from the denominator and the Spark ratio operators returned codes such as -9999.FeatureToolsalso counted the months of a window without a payment and the longest runs of consecutive months with and without one.panel_featurescounts the same on a monthly panel with an ordered status:bad_months_{window},longest_bad_run_{window}andlongest_good_run_{window}. Give the panel a row for every month of every entity, with a bad status for a month without a payment, and pass that status asbad; on a delinquency panel,bad="1-29"makes any arrears bad. A month without a row counts in no window and ends a run, where the legacy code counted it as a month without a payment.features_aggtakes the aggregations that its docstring lists under their kivi names:cntiscount, or theeventscolumn, which also counts the rows without a value,avgandmeanaremean,cnt_distisnunique,stddevandstddev_samparestd, whose square givesvarianceandvar_samp, andsum,min,max,firstandlastkeep their names.sum_dist,skewness,kurtosis,collect_set,collect_list,approx_count_distinctand the population statisticsstddev_popandvar_popare not ported. The features are named{prefix}{column}_{aggregation}_{window}, such asamount_sum_3m, rather thanent_{column}_last_{month}_{operator}.An
IndexFieldconfigured the columns, operators and months of an indicator, andCollectIndexcomputed it. AFeatureSpecholds the same as groups ofaggregationsandwindows, saved as versioned JSON, without the database, table and partition settings, because the caller reads and writes the tables. Itsid_levelsbecome one specification per level, each with its ownidcolumn.CollectIndexdeclared steps for the change from the previous period and from the same period a year earlier but left them empty; they are ratios to window pairs, such as("amount_sum_3m", "amount_sum_6m_3m")and("amount_sum_3m", "amount_sum_15m_12m").
Variable selection, charts and WOE trends#
Version 1.4.0 ports the last tools of the 0.2.x selection, chart and WOE utilities that had no replacement, and adds the validation tests of the European Central Bank, which have no 0.2.x counterpart. These are new implementations as well, so compare their output with the legacy code on a fixed reference sample before switching.
VIF.LowVIFFeatures(df, thresh=5)tried dropping each column in turn and dropped the one that left the smallest sum of VIFs, while the largest VIF was at leastthreshand more than two columns were left. It computed the VIFs without an intercept, which inflates the VIF of a variable whose mean is far from 0, dropped the columns from the frame it was given and returned the VIFs of every step.vif_filter(X, threshold=5)drops the variable with the largest VIF, with an intercept, until no VIF exceedsthresholdor one variable is left, andpriority, such as the IVs, decides between tied VIFs. It leavesXunchanged and returns the kept columns, likecorrelation_filter;vif(X[kept])gives their VIFs. On WOE values, whose means are close to 0, the VIFs differ little, but the two rules can drop different variables.StepWise(df, dependent=..., indicator="auc").forward()did not select variables by their p-values. It ranked the variables by a univariate measure of thedependenttable, such as their AUC or KS, fitted the logistic regressions on the first 1, 2, 3 and more of them and reported the AUC, the KS, the lift and the signs of the coefficients of each model, stopping once the relative gain ofindicatorfell belowearly_stop.selection_path(X, target, order=...)fits the same nested models, with the order asorder, such asprofile.sort_values("iv", ascending=False).index, and reports each step’sauc,gini,ks,max_p_valueandmin_coefficient, also on avalidationsample. It has no early stop:path["auc"].pct_change()gives the relative gain thatearly_stopcompared.backward()fitted the same models from the longest down, so read the path from its last row up. A model that could not be fitted was logged and reported without measures, whileselection_pathraisesSeparationErrorand names the step. The lift of a model is in thegains_tableof its fitted probabilities.woe/utils.monotonylabelled the trend of the values it was given.woe_trend(table)takes awoe_tableresult or a table of aBinningSpecand reads the WOE of its interval rows in the order of the table, leaving out the rows of special codes and missing values, and it raises for a categorical variable. Its labels correspond one to one:monotonywoe_trend单调上升"increasing"单调下降"decreasing"下降上升"u_shaped"上升下降"inverted_u"未知"irregular"数据不足, a single value"flat"monotonycounted equal neighbours as rising, so[0.3, 0.3, 0.1]was上升下降and equal values were单调上升. Inwoe_trend, neighbours whose WOE differ by at most a relative \(10^{-10}\) neither rise nor fall, so the same values are"decreasing", and equal values are"flat".BinaryMetrics.plot_scoredrew histograms and kernel densities of the scores of the goods and the bads.distribution_chartdraws, for each band of agains_tableor each bin of awoe_table, its share of all non-events and of all events as bars side by side;plot_kscut the scores into 40 bands of equal width, whilegains_table(score, target, bins=40)makes 40 bands of equal counts; equal-width edges such asnp.linspace(score.min(), score.max(), 41), with the outer two replaced by-np.infandnp.inf, give the bands ofplot_ks.plot_prjoined the points ofpr_curvewith straight lines, labelled the curve with the AUC of the ROC curve and drew the diagonal from (0, 1) to (1, 0).precision_recall_chartdraws theprecisionandtrue_positive_rateof aroc_tableas steps, whose area is the average precision, with a line at the event rate, the precision of a score that ranks at random.
Not ported#
Spark, SQL, model wrappers and application code are out of scope and remain in the historical revisions: the Spark sessions, partitions and Hive writers of spark, index and FeatureToolsV2, whose features kivi.features computes with pandas instead, the wrappers of Model, and the Excel, Markdown, logging and date helpers of utils. These 0.2.x tools have no replacement either:
The binning classes
KmeansBins, which cut at the boundaries of k-means clusters, andPearsonBins, which lowered the number of quantile bins until their rank correlation with the bad rate reached a threshold.monotonic_edgesreaches the monotonic WOE thatPearsonBinsaimed at, and the supervised methods of Binning replace the clustering ofKmeansBins.The sampling helpers
samplingandupsampling, the median and missing-value cross features ofjoint_featureinFeatureTools, its trend flags and its counts of months above and below the average, itsratioof two columns of a frame, and the min-max and z-score scaling ofScale. Use pandas. The ratios of window features are theratiosofwindow_featuresfrom 1.3.0.The industry percentile ranks of
index_indu_pctinFeatureToolsV2andpct_rank. Rank features within groups with pandas, as infeatures.groupby(industry).rank(pct=True).The grading by the Beta distribution in
BetaCalibration,BetaDistributionandMasterScale.cal_quantile, the chart of its grade shares inMasterScale.plot_grade_rate, andmodel_score_by_weight.master_scaleandwoe_to_pointscover the same steps without them, andcalibration_chartcompares the predicted and the observed rate of each grade.The univariate logistic fit of
FeatureEvaluateand the p-value of its KS test. Theginiandksofprofile_tablemeasure how well the values rank the target directly.ODDS, which computed a stability index of score bands, andStatsLogit, a wrapper of statsmodels’ logistic regression. Usepsi_tableandlogistic_regression.int_scoreinwoe/utils, which rounded a score to the nearest multiple of 5 from 0 to 100. Use(score / 5).round().clip(0, 20) * 5, which rounds ties to even whereint_scorerounded them down. Rounded points no longer add up to the rounded score, so round only the total.StepWise.top_n_features, which kept the variables with the highest KS of each dimension. Withdimensiona Series that maps each variable to its dimension,profile.assign(dimension=dimension).sort_values("iv").groupby("dimension").tail(n)keeps thenvariables with the highest IV of each dimension of aprofile_table, andsort_values("ks")those with the highest KS.BinaryMetrics.plot_confusion_matrix, a heatmap of the four counts of a confusion matrix.confusion_tablereturns them for every cut-off.Dataset.crime_data(), a table of crime rates of US states that has nothing to do with credit risk, and the synthetic data ofMakeData, a scikit-learn classification sample split for training, and offake_data, which drew each column from one range for the bad and another for the good customers.make_applicationsandmake_loan_panelsimulate loan applications and a loan portfolio instead, and from 1.3.0make_transactionsthe account transactions before each application, which neither legacy generator produced.