Baseline Models
- class neer_match_utilities.baseline_models.GradientBoostingModel(model=<factory>)[source]
Gradient boosting baseline on similarity features using scikit-learn.
Designed as an alternative to the DL/NS models in neer_match, using scikit-learn’s HistGradientBoostingClassifier on top of similarity features produced by SimilarityFeatures.
It supports: - evaluation with TP, FP, TN, FN, Accuracy, Recall, Precision, F1, MCC, - a simple summary() reporting feature importances, where the classifier
has them.
Notes
Unlike Logit/Probit, this model has no statistical inference (SE/p-values).
Works well with nonlinearities and interactions in similarity features.
Up to version 1.2.5 the default was GradientBoostingClassifier, with the same 300 rounds, learning rate and depth. Its Newton step for a leaf divides by the sum of p(1 - p) over the pairs in it. With matches as rare as among all record pairs, the probabilities soon come close to 0 or 1, and where matches and non-matches with the same similarities share a leaf, that sum is close to zero: the leaf values, and the training loss, grow without bound (to 1e+79 in tests on real data), and the predictions collapse to 0 and 1. HistGradientBoostingClassifier does not split where a leaf’s hessian sum would fall below
min_hessian_to_split, and is tens of times faster. Passmodel=GradientBoostingClassifier(...)for the earlier classifier; models saved with it still load.Its
l2_regularizationof 1 (version 1.2.7; 0 in 1.2.6) adds 1 to the hessian sum each leaf value is divided by, as XGBoost’s defaultlambdadoes. Without it, leaves just abovemin_hessian_to_splitstill took huge steps on some splits, so that the training loss rose again after a hundred rounds and the fit ended worse than it had been (training F1 0.21 where 0.99 with it).
- __init__(model=<factory>)
- best_threshold(df_val, match_col='match', feature_prefix='col_', metric='mcc', thresholds=None, store_threshold=True, *, store_treshold=None)[source]
Find the classification threshold that maximizes a metric on validation data.
- Parameters:
df_val (
DataFrame) – Validation DataFrame produced by SimilarityFeatures.pairwise_similarity_dataframe().match_col (
str) – Target column.feature_prefix (
str) – Feature column prefix.metric (
str) – Metric to maximize.thresholds (
ndarray|None) – Threshold grid. If None, uses np.linspace(0.01, 0.99, 99).store_threshold (
bool) – If True, also store the chosen threshold on the model asbest_threshold_, whichModelBaseline.savesaves with it.store_treshold (
bool|None) – Deprecated misspelling ofstore_threshold, still accepted with a FutureWarning.
- Return type:
tuple[float,dict]- Returns:
best_t (float) – Threshold achieving the best metric on df_val.
best_stats (dict) – Evaluation dict (TP/FP/TN/FN/Accuracy/Recall/Precision/F1/MCC) at best_t.
- evaluate(df, match_col='match', feature_prefix='col_', threshold=None)[source]
Evaluate the model on a pairwise similarity DataFrame.
A pair counts as a match from
thresholdon; without one, from the threshold tuned and saved with the model (best_threshold_), and from 0.5 if there is none.Returns a dict:
TP, FP, TN, FN (integers)
Accuracy, Recall, Precision, F1, MCC (floats)
- Return type:
dict
- fit(df, match_col='match', feature_prefix='col_', use_class_weight=False)[source]
Fit gradient boosting on a pairwise similarity DataFrame.
- Parameters:
df (
DataFrame) – (Possibly subsampled) DataFrame produced by SimilarityFeatures.pairwise_similarity_dataframe().match_col (
str) – Name of the binary target column.feature_prefix (
str) – Prefix of feature columns (similarity features).use_class_weight (
bool) – If True, uses inverse-frequency sample weights to upweight matches. Useful if you fit on a very imbalanced dataset.
- Return type:
- class neer_match_utilities.baseline_models.LogitMatchingModel[source]
Logistic regression baseline on similarity features using statsmodels.
This class is designed as an alternative to the DL/NS models in neer_match, using statsmodels’ Logit on top of the similarity features produced by SimilarityFeatures.
It supports: - evaluation with TP, FP, TN, FN, Accuracy, Recall, Precision, F1, MCC, - full inference via summary().
- __init__()
- fit(df, match_col='match', feature_prefix='col_')[source]
Fit logistic regression on a pairwise similarity DataFrame.
Constant features, and features that are linear combinations of others, are left out of the fit (the latter with a printed note). Neither adds information, and both would make the matrix statsmodels inverts singular.
feature_colslists the features the model uses. If no feature varies, it is empty and the model has only its intercept: it gives every pair the same probability, about the share of matches indf.- Parameters:
df (
DataFrame) – (Possibly subsampled) DataFrame produced by SimilarityFeatures.pairwise_similarity_dataframe().match_col (
str) – Name of the binary target column.feature_prefix (
str) – Prefix of feature columns (similarity features).
- Return type:
- class neer_match_utilities.baseline_models.ProbitMatchingModel[source]
Probit regression baseline on similarity features using statsmodels.
Same interface as LogitMatchingModel, but using a normal CDF link.
- __init__()
- fit(df, match_col='match', feature_prefix='col_')[source]
Fit probit regression on a pairwise similarity DataFrame.
Constant features, and features that are linear combinations of others, are left out of the fit (the latter with a printed note). Neither adds information, and both would make the matrix statsmodels inverts singular.
feature_colslists the features the model uses. If no feature varies, it is empty and the model has only its intercept: it gives every pair the same probability, about the share of matches indf.- Parameters:
df (
DataFrame) – (Possibly subsampled) DataFrame produced by SimilarityFeatures.pairwise_similarity_dataframe().match_col (
str) – Name of the binary target column.feature_prefix (
str) – Prefix of feature columns (similarity features).
- Return type:
- class neer_match_utilities.baseline_models.StatsmodelsInferenceMixin[source]
Keeps a fitted model usable without its statsmodels
Resultsobject.Two problems motivate this. First, a
Resultsobject holds a reference to itsModel, and thereby toendog/exog– the full training data. Pickling it stores the entire design matrix, which in entity matching is the complete left x right cross join. Second, a pickledResultscontains pandas objects (paramsis a Series,normalized_cov_paramsa DataFrame), and pandas pickles are not portable across pandas versions – an archive written under one version can be unreadable under another.capture_inference()therefore extracts everything needed for later use – the coefficient vector, the parameter names and the regression table – into plain Python and numpy types.neer_match_utilities.baseline_io.ModelBaseline()stores those inmeta.pkl, and a model reconstructed from them alone can still predict, score and report its summary. The statsmodels pickle is then an optional extra rather than a dependency.predict_probastill delegates to theResultsobject whenever one is present, so behavior is unchanged for freshly fitted models and for archives that load cleanly. The pandas-free path engages only when the result is unavailable.- capture_inference()[source]
Extract the fitted model into plain types, while the training data is still attached.
Stores the coefficient vector, the parameter names and the regression table. These are what
ModelBaselinewrites tometa.pkl, and what a reloaded model falls back on when the statsmodels pickle is unavailable.- Return type:
None
- coefficients()[source]
Coefficients, standard errors, z-statistics, p-values and confidence intervals.
- Return type:
DataFrame
- predict_proba(df, feature_prefix='col_')[source]
Predict match probabilities.
Delegates to the statsmodels result when one is present. Otherwise applies the model’s link function to the linear predictor built from the stored coefficients, which gives the same answer without requiring the pickled result.
- Return type:
ndarray
- class neer_match_utilities.baseline_models.SuggestMixin[source]
Adds a NeerMatch-like .suggest(left, right, count, verbose) API to baseline models.
Requires:
self.predict_proba(df_pairs) implemented
self.similarity_map set to a SimilarityMap (or dict) describing features to compute
- suggest(left, right, *, count=10, verbose=0, left_id_col=None, right_id_col=None, pairs_per_chunk=250000, blocking=None)[source]
Return top-k candidate matches per left record (like neer_match DL models).
- Output columns:
left: integer row index into left (0..len(left)-1)
right: integer row index into right (0..len(right)-1)
prediction: match probability
Pairs are scored in blocks of whole left rows, at most
pairs_per_chunkpairs (but at least one left row) at a time, so memory does not grow withlen(left) * len(right). The result does not depend on the block size, up to floating-point rounding of the probabilities.With
blocking(seeneer_match_utilities.blocking), only the candidate pairs are scored, and the top-k come from them; a left record without candidates gets no suggestion.- Return type:
DataFrame
- neer_match_utilities.baseline_models.classification_metrics(y_true, y_hat)[source]
Confusion counts and scores of binary predictions.
Shared by the baseline models’
evaluateand byBaselineTrainingPipe, which collects the predictions block by block rather than from one frame.Returns a dict:
TP, FP, TN, FN (integers)
Accuracy, Recall, Precision, F1, MCC (floats)
- Return type:
dict