Binning specifications#
Bin and encode every column of a data frame in one step. fit_spec() fits the binning and the WOE of each column, and the resulting BinningSpec groups and encodes any other sample in the same way and saves itself as versioned JSON.
See Binning specifications for examples and the file format.
|
Fit the binning and WOE of every column of a development sample. |
|
Binning and WOE encoding of every column, fitted on a development sample. |
- kivi.spec.fit_spec(frame, target, *, columns=None, method='quantile', bins=5, special=None, options=None, unseen='raise', smoothing=0.5, weights=None)#
Fit the binning and WOE of every column of a development sample.
Numeric columns are binned with the method chosen for them and grouped with kivi.binning.cut. Categorical columns that method names are grouped with kivi.binning.category_groups or kivi.binning.chimerge_groups and kivi.binning.group_categories; the other categorical columns keep their labels as groups. The WOE of each group is then measured with kivi.woe.woe_table. Nothing is re-binned automatically: the method, the number of bins and the options of each column decide how coarse its bins are.
- Parameters:
- framepandas.DataFrame
Development sample with one column per variable. Columns with a numeric dtype other than bool and complex are binned, and complex columns are rejected. Columns of any other dtype, such as object, string, category or bool, are categorical: each label is a group unless method groups the column. Convert integer codes to the category dtype to keep them as labels.
- targetarray_like
Binary labels, with 1 indicating the event, one per row of frame. A Series must have the same index as frame; other inputs are matched by position.
- columnssequence of str, optional
Columns to fit, in the order of the specification. By default every column of frame.
- methodstr or dict, default “quantile”
Binning method of the numeric columns:
"quantile"or"uniform"for kivi.binning.bin_edges, or"chimerge","tree","ks"or"monotonic"for kivi.binning.chimerge_edges, kivi.binning.tree_edges, kivi.binning.ks_edges or kivi.binning.monotonic_edges. A dict maps columns to methods, and the numeric columns it leaves out use"quantile". A method applies only to the columns without edges in bins, so a dict must not name a column whose edges bins gives. A dict can also group categorical columns, with"rare"for kivi.binning.category_groups or"chimerge"for kivi.binning.chimerge_groups; the categorical columns it leaves out keep their labels.- binsint or dict, default 5
Number of bins, passed as
binsto kivi.binning.bin_edges, asmax_binsto the supervised methods and asmax_groupsto kivi.binning.chimerge_groups. A dict maps columns to a number of bins or to edges, which must increase from-inftoinfand are used as given. With"monotonic", None merges bins only until the WOE is monotonic. The numeric and"chimerge"columns that a dict leaves out get 5 bins. Columns grouped with"rare"take no number of bins.- specialdict, optional
Special codes of numeric and grouped categorical columns, such as
{"pdays": [-1], "job": ["unknown"]}. The codes of a numeric column must be numbers, possibly infinite; those of a categorical column are labels. They are left out of the fit, and each code forms its own group.- optionsdict, optional
Further keyword arguments for the binning or grouping function of each column, such as
{"balance": {"alpha": None}}with"chimerge"or{"job": {"min_share": 0.02}}with"rare". The special codes, the weights, the number of bins and, for"monotonic"and the grouping with"chimerge", the smoothing are passed by fit_spec and cannot be given here.- unseenfloat, “raise” or dict, default “raise”
WOE for values whose group is not in a column’s table when a sample is encoded: a new category, a special code or an interval without development observations, or missing values when development had none. By default such values raise an error. A dict maps columns to a WOE or
"raise", and the columns it leaves out raise. For a grouped column,{"group": label}gives such values the WOE of that group instead, and BinningSpec.cut assigns new categories to it; the group must be in the fitted table. A dict is always read by column, so give{"group": label}for each grouped column, as in{"job": {"group": "other"}}.- smoothingfloat, default 0.5
Positive replacement for a zero count when calculating the WOE, as in kivi.woe.woe_table.
"monotonic"binning uses the same value, so its trend holds in the tables.- weightsarray_like, optional
Non-negative weight of each row, matched like target, for the binning functions and kivi.woe.woe_table. Counts are then sums of weights, and smoothing is in units of weight.
- Returns:
- BinningSpec
The kind, edges, special codes, grouping, WOE table and unseen policy of every column.
- Raises:
- ValueError
If frame is not a DataFrame or has no columns to fit, columns repeats a column or names one that frame lacks, a column name is not a string, a column has a complex dtype, the columns include the target, or target does not give each row a label 0 or 1 or lacks one of the two classes. If a dict names a column that is not fitted, method gives a categorical column a method other than
"chimerge"or"rare", bins, special or options names a categorical column that method does not group, or a value is invalid, such as a special code of a numeric column that is not a number. Also if smoothing or weights are invalid, a numeric column has infinite values that are not special codes, or the binning or grouping of a column fails; the message then names the column.
- Warns:
- UserWarning
If tied quantiles leave a column with fewer bins than requested, as in kivi.binning.bin_edges, if a numeric column has no values to fit apart from missing, special and zero-weight values, so that its edges are
[-inf, inf], if a grouped column has no such values, so that its groups are its special codes, or if a column of dtype object holds only numbers, which makes each distinct number a group. The message names the column.
See also
BinningSpecGroup, encode and save the fitted columns.
kivi.binning.bin_edgesFit the edges of one column.
kivi.binning.chimerge_groupsGroup the categories of one column.
kivi.woe.woe_tableThe WOE table of one column.
Notes
Each column is fitted on its own with the public functions, so a column of the specification has the same edges and table as the steps of Binning and Weight of evidence and information value applied to it alone.
Examples
>>> import pandas as pd >>> from kivi.spec import fit_spec >>> frame = pd.DataFrame({ ... "age": [23, 31, 45, 52, 38, 27, 61, 49], ... "housing": ["yes", "no", "yes", "no", "no", "yes", "no", "yes"], ... }) >>> target = pd.Series([1, 0, 0, 0, 1, 1, 0, 0]) >>> spec = fit_spec(frame, target, bins=2) >>> spec.tables["age"][["non_event", "event", "woe"]].round(4) non_event event woe bin (-inf, 41.5] 1 3 1.4553 (41.5, inf] 4 0 -1.7228 >>> spec.woe_transform(frame).head(3).round(4) age housing 0 1.4553 0.5108 1 1.4553 -0.5878 2 -1.7228 0.5108
- class kivi.spec.BinningSpec(kinds, edges, special, tables, unseen, smoothing=0.5, kivi_version=None, groups=None)#
Binning and WOE encoding of every column, fitted on a development sample.
For each column, a specification records whether it is numeric or categorical, the edges and special codes of a numeric column, the grouping of a grouped categorical column, the WOE table of its groups and the policy for groups that are not in the table. cut groups any sample with the same edges and groupings, woe_transform encodes it with the same WOE, and to_json and from_json save and load the specification without changing its groups or its encoding. Fit a specification with fit_spec rather than calling the constructor.
A specification is immutable. Its mappings are read-only, and
edges,groupsandtablesreturn a new copy of an array, a dict or a table on each access, so changing the copy leaves the specification as it was. To change a field, such as the unseen policy, use dataclasses.replace, which validates the result again.- Parameters:
- kindsmapping
"numeric"or"categorical"for each column, in the order of the specification.- edgesmapping
Edges of each numeric column, increasing from
-inftoinf.- specialmapping
Special codes of each numeric column, possibly none. The codes are numbers, and each forms its own group, as in kivi.binning.cut.
- tablesmapping
The kivi.woe.woe_table result of each column. The groups of a numeric column are its special codes and the intervals of its edges, labelled as kivi.binning.cut labels them or by the exact edges, and those of a grouped column the groups of its grouping. Missing values form a group labelled NaN. The tables keep the labels of kivi.binning.cut.
- unseenmapping
"raise"or a finite WOE for each column, used for values whose group is not in the column’s table. A grouped column can instead name one of its groups as{"group": label}: such values then get that group’s WOE, and cut assigns the categories that its grouping does not map to that group.- smoothingfloat, default 0.5
Smoothing with which the tables were computed.
- kivi_versionstr, optional
Version of kivi that fitted the specification. By default, or if None, the installed version.
- groupsmapping, optional
Grouping of each grouped categorical column: a dict from category to group, as returned by kivi.binning.category_groups or kivi.binning.chimerge_groups. Categorical columns without an entry keep their labels as groups. By default no column is grouped.
- Attributes:
- FORMAT_VERSIONint
Newest version of the JSON format, which from_json reads and to_json writes for a specification with grouped columns.
- Raises:
- ValueError
If kinds is empty or has a name that is not a string or a kind other than the two above, if edges and special do not have one entry per numeric column, groups has an entry for a column that is not categorical, or tables and unseen do not have one entry per column, or if an entry is invalid: edges that do not increase from
-inftoinf, a missing or unsupported special code, a grouping with a missing or unsupported category or group, a table without a finitewoecolumn or with a repeated group, a group of a numeric column that is neither one of its special codes nor an interval of its edges, a group of a grouped column that its grouping lacks, or an unseen policy that is neither"raise"nor a finite number nor, for a grouped column, a group of its table. Also if smoothing is not finite and positive or kivi_version is not a string.
See also
fit_specFit a specification on a development sample.
kivi.binning.cutGroup one numeric column.
kivi.woe.woe_transformEncode one column with its WOE table.
Notes
Labels of categorical columns must be strings, integers, floats, booleans or intervals, which the JSON format keeps apart. Within a column, labels that compare equal, such as
Trueand1, form one group, because kivi.woe.woe_table and kivi.woe.woe_transform match labels by equality. The same holds for the categories and groups of a grouping, which keeps the categories of each group together, in the order in which the groups first appear.Two specifications are equal when to_json gives the same text for both, which includes kivi_version. The text is computed once and kept, so comparing and hashing a specification again is cheap.
Examples
>>> import pandas as pd >>> from kivi.spec import fit_spec >>> frame = pd.DataFrame({ ... "age": [23, 31, 45, 52, 38, 27, 61, 49], ... "housing": ["yes", "no", "yes", "no", "no", "yes", "no", "yes"], ... }) >>> target = pd.Series([1, 0, 0, 0, 1, 1, 0, 0]) >>> spec = fit_spec(frame, target, bins=2) >>> spec BinningSpec(columns=['age', 'housing']) >>> dict(spec.kinds) {'age': 'numeric', 'housing': 'categorical'} >>> spec.edges["age"] array([-inf, 41.5, inf])
- property format_version#
Version of the JSON format that to_json writes.
Version 2 adds the groupings of categorical columns to version 1. A specification without grouped columns is written as version 1, which earlier versions of kivi read as well. FORMAT_VERSION is the newest version.
See also
to_jsonWrite the specification.
Examples
>>> import pandas as pd >>> from kivi.spec import fit_spec >>> frame = pd.DataFrame({"housing": ["yes", "no", "yes", "no"]}) >>> fit_spec(frame, [1, 0, 0, 1]).format_version 1 >>> fit_spec(frame, [1, 0, 0, 1], method={"housing": "rare"}).format_version 2
- property columns#
Names of the columns in the specification.
The columns are in the order in which they were fitted, which is the order of the columns of cut and woe_transform.
See also
selectA specification of some of the columns.
Examples
>>> import pandas as pd >>> from kivi.spec import fit_spec >>> frame = pd.DataFrame({"age": [23, 31, 45, 52], "housing": ["yes", "no", "yes", "no"]}) >>> fit_spec(frame, [1, 0, 0, 1], bins=2).columns Index(['age', 'housing'], dtype='object')
- cut(frame)#
Group every column of a sample as in development.
Numeric columns are assigned to their bins with kivi.binning.cut, using the fitted edges and special codes; an infinite value that is not a special code is in no bin and stays missing. Grouped categorical columns are assigned to their groups as by kivi.binning.group_categories. A category that the grouping does not map joins the group that the column’s unseen policy names, if any, and otherwise keeps its own label, so that kivi.stability.psi_table shows it as a new group. Other categorical columns are returned unchanged, because their labels are their groups.
- Parameters:
- framepandas.DataFrame
Sample that has every column of the specification. Other columns are ignored.
- Returns:
- pandas.DataFrame
The groups of each column of the specification, in its order, with the index of frame. Numeric columns are categorical, with the special codes followed by every interval of the edges. Grouped columns are categorical, with the groups in the order of the grouping followed by the categories that it does not map and that no unseen group receives.
- Raises:
- ValueError
If frame is not a DataFrame, lacks a column of the specification or has it twice, a column fitted as numeric has values but not a real numeric dtype, such as a string or complex dtype, which could hide its special codes; convert such a column with
pandas.to_numeric. Also if a grouped column without an unseen group has a category that its grouping does not map but that is the label of one of its groups, so that its group would be ambiguous. The message names the column.
See also
woe_transformEncode the groups with the fitted WOE.
kivi.binning.cutGroup one numeric column.
kivi.binning.group_categoriesGroup one categorical column.
Examples
>>> import pandas as pd >>> from kivi.spec import fit_spec >>> frame = pd.DataFrame({"age": [23, 31, 45, 52], "housing": ["yes", "no", "yes", "no"]}) >>> spec = fit_spec(frame, [1, 0, 0, 1], bins=2) >>> spec.cut(pd.DataFrame({"age": [30, 70], "housing": ["no", "yes"]})) age housing 0 (-inf, 38.0] no 1 (38.0, inf] yes
- woe_transform(frame)#
Encode every column of a sample with the WOE fitted in development.
The columns are grouped as by cut, and each group is replaced with its WOE by kivi.woe.woe_transform. A group that is not in a column’s table, such as a new category, gets the column’s unseen policy, which by default raises an error. So does a category that the grouping of a grouped column does not map, even when it equals the label of a group, for which cut raises an error. An unseen group gives such values the WOE of that group.
- Parameters:
- framepandas.DataFrame
Sample that has every column of the specification. Other columns are ignored.
- Returns:
- pandas.DataFrame
Float WOE values of each column of the specification, in its order, with the index of frame.
- Raises:
- ValueError
If frame is not a DataFrame, lacks a column of the specification or has it twice, a column fitted as numeric has values but not a real numeric dtype, or a column with the unseen policy
"raise"has values whose group is not in its table, infinite values that are not special codes or, for a grouped column, categories that its grouping does not map. The message names the column.
See also
cutGroup the columns without encoding them.
kivi.woe.woe_transformEncode one column.
kivi.scorecard.woe_to_pointsTurn the WOE values into points.
Notes
An infinite value that is not a special code of its column, such as the result of a division by zero, is in no group: cut leaves it missing, and woe_transform treats it as unseen rather than giving it the WOE of missing values or of the last interval.
Examples
>>> import pandas as pd >>> from kivi.spec import fit_spec >>> frame = pd.DataFrame({ ... "age": [23, 31, 45, 52, 38, 27, 61, 49], ... "housing": ["yes", "no", "yes", "no", "no", "yes", "no", "yes"], ... }) >>> target = pd.Series([1, 0, 0, 0, 1, 1, 0, 0]) >>> new = pd.DataFrame({"age": [30, 70], "housing": ["no", "rent"]}) >>> fit_spec(frame, target, bins=2).woe_transform(new) Traceback (most recent call last): ... ValueError: column 'housing': 1 group(s) are not in table, such as 'rent'; ...
With an unseen WOE for
housing, the new label gets 0:>>> spec = fit_spec(frame, target, bins=2, unseen={"housing": 0.0}) >>> spec.woe_transform(new).round(4) age housing 0 1.4553 -0.5878 1 -1.7228 0.0000
- select(columns)#
Return the specification of some of the columns.
Use it to keep only the variables of the final model before saving the specification for production. The selected columns keep their edges, special codes, groupings, tables and unseen policies.
- Parameters:
- columnssequence of str
Columns to keep, in the order of the new specification.
- Returns:
- BinningSpec
A specification of columns only.
- Raises:
- ValueError
If columns is a string, is empty, repeats a column or names a column that is not in the specification.
Examples
>>> import pandas as pd >>> from kivi.spec import fit_spec >>> frame = pd.DataFrame({"age": [23, 31, 45, 52], "housing": ["yes", "no", "yes", "no"]}) >>> fit_spec(frame, [1, 0, 0, 1], bins=2).select(["housing"]) BinningSpec(columns=['housing'])
- to_dict()#
Return the specification as a dict of JSON types.
The result holds only dicts, lists, strings, numbers, booleans and None, so
json.dumpscan write it without further conversion. Its keys are always in the same order. to_json writes this dict.- Returns:
- dict
The keys
format,format_version,kivi_version,smoothingandvariables, a list with one dict per column. See the user guide for the format.
Examples
>>> import pandas as pd >>> from kivi.spec import fit_spec >>> frame = pd.DataFrame({"age": [23, 31, 45, 52]}) >>> data = fit_spec(frame, [1, 0, 0, 1], bins=2).to_dict() >>> list(data) ['format', 'format_version', 'kivi_version', 'smoothing', 'variables'] >>> data["variables"][0]["edges"] [{'float': '-inf'}, 38.0, {'float': 'inf'}]
- classmethod from_dict(data)#
Rebuild a specification from the result of to_dict.
The dict is checked before the specification is built, so that a damaged or hand-edited file fails with a message that names the problem instead of encoding wrong values.
- Parameters:
- datamapping
A dict in the format of to_dict, for example from
json.load.
- Returns:
- BinningSpec
The specification, equal to the one that wrote data.
- Raises:
- ValueError
If data is not a kivi binning specification, has a
format_versionnewer than this version of kivi reads, lacks a key or has an unknown one, or holds an invalid value. The message names the column.
Examples
>>> import pandas as pd >>> from kivi.spec import BinningSpec, fit_spec >>> frame = pd.DataFrame({"age": [23, 31, 45, 52]}) >>> spec = fit_spec(frame, [1, 0, 0, 1], bins=2) >>> BinningSpec.from_dict(spec.to_dict()) == spec True
- to_json(*, indent=None)#
Return the specification as JSON text.
The text is the dict of to_dict written by
json.dumps. The same specification always gives the same text, so saved specifications can be compared and kept under version control. Non-ASCII labels are written as they are, so save the text as UTF-8.- Parameters:
- indentint, optional
Indentation of nested values, as in
json.dumps. By default the text is a single line.
- Returns:
- str
JSON text that from_json reads back into an equal specification.
Examples
>>> import pandas as pd >>> from kivi.spec import fit_spec >>> frame = pd.DataFrame({"age": [23, 31, 45, 52]}) >>> spec = fit_spec(frame, [1, 0, 0, 1], bins=2) >>> print(spec.to_json(indent=2)) { "format": "kivi.BinningSpec", "format_version": 1, "kivi_version": "...", "smoothing": 0.5, "variables": [ { "name": "age", "kind": "numeric", "edges": [ { "float": "-inf" }, 38.0, ...
Write the text to a file with
Path("spec.json").write_text(text, encoding="utf-8").
- classmethod from_json(text)#
Read a specification from the JSON text of to_json.
The loaded specification groups and encodes every sample exactly as the one that was saved. A file written by a newer version of the format is rejected rather than read in part.
- Parameters:
- textstr or bytes
JSON text, for example from
Path(...).read_text(encoding="utf-8").
- Returns:
- BinningSpec
The specification, equal to the one that wrote text.
- Raises:
- ValueError
If text is neither a str nor bytes, is not valid JSON, contains
NaNorInfinity, or does not describe a valid specification; see from_dict.
Examples
>>> import pandas as pd >>> from kivi.spec import BinningSpec, fit_spec >>> frame = pd.DataFrame({"age": [23, 31, 45, 52]}) >>> spec = fit_spec(frame, [1, 0, 0, 1], bins=2) >>> loaded = BinningSpec.from_json(spec.to_json()) >>> loaded == spec True >>> loaded.woe_transform(frame).equals(spec.woe_transform(frame)) True