The analysis notebook
The exploration, modelling and evaluation behind Credit Risk Predictor, as it runs. Code cells, printed results and charts are shown as saved in the notebook on GitHub.
In [30]
import pandas as pd
import numpy as np
df = pd.read_csv("../data/application_train.csv")
df.head()| SK_ID_CURR | TARGET | NAME_CONTRACT_TYPE | CODE_GENDER | FLAG_OWN_CAR | FLAG_OWN_REALTY | CNT_CHILDREN | AMT_INCOME_TOTAL | AMT_CREDIT | AMT_ANNUITY | ... | FLAG_DOCUMENT_18 | FLAG_DOCUMENT_19 | FLAG_DOCUMENT_20 | FLAG_DOCUMENT_21 | AMT_REQ_CREDIT_BUREAU_HOUR | AMT_REQ_CREDIT_BUREAU_DAY | AMT_REQ_CREDIT_BUREAU_WEEK | AMT_REQ_CREDIT_BUREAU_MON | AMT_REQ_CREDIT_BUREAU_QRT | AMT_REQ_CREDIT_BUREAU_YEAR | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 100002 | 1 | Cash loans | M | N | Y | 0 | 202500.0 | 406597.5 | 24700.5 | ... | 0 | 0 | 0 | 0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 |
| 1 | 100003 | 0 | Cash loans | F | N | N | 0 | 270000.0 | 1293502.5 | 35698.5 | ... | 0 | 0 | 0 | 0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2 | 100004 | 0 | Revolving loans | M | Y | Y | 0 | 67500.0 | 135000.0 | 6750.0 | ... | 0 | 0 | 0 | 0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 3 | 100006 | 0 | Cash loans | F | N | Y | 0 | 135000.0 | 312682.5 | 29686.5 | ... | 0 | 0 | 0 | 0 | NaN | NaN | NaN | NaN | NaN | NaN |
| 4 | 100007 | 0 | Cash loans | M | N | Y | 0 | 121500.0 | 513000.0 | 21865.5 | ... | 0 | 0 | 0 | 0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
In [31]
df.shape(307511, 122)
In [32]
df.info()<class 'pandas.core.frame.DataFrame'> RangeIndex: 307511 entries, 0 to 307510 Columns: 122 entries, SK_ID_CURR to AMT_REQ_CREDIT_BUREAU_YEAR dtypes: float64(65), int64(41), object(16) memory usage: 286.2+ MB
In [33]
df["TARGET"].value_counts()TARGET 0 282686 1 24825 Name: count, dtype: int64
In [34]
df["TARGET"].value_counts(normalize=True) * 100TARGET 0 91.927118 1 8.072882 Name: proportion, dtype: float64
In [35]
df.isnull().sum().sort_values(ascending=False).head(20)COMMONAREA_AVG 214865 COMMONAREA_MODE 214865 COMMONAREA_MEDI 214865 NONLIVINGAPARTMENTS_MEDI 213514 NONLIVINGAPARTMENTS_MODE 213514 NONLIVINGAPARTMENTS_AVG 213514 FONDKAPREMONT_MODE 210295 LIVINGAPARTMENTS_AVG 210199 LIVINGAPARTMENTS_MEDI 210199 LIVINGAPARTMENTS_MODE 210199 FLOORSMIN_MODE 208642 FLOORSMIN_AVG 208642 FLOORSMIN_MEDI 208642 YEARS_BUILD_AVG 204488 YEARS_BUILD_MODE 204488 YEARS_BUILD_MEDI 204488 OWN_CAR_AGE 202929 LANDAREA_MEDI 182590 LANDAREA_AVG 182590 LANDAREA_MODE 182590 dtype: int64
In [36]
missing = df.isnull().sum()
missing_percentage = (missing / len(df)) * 100
missing_data = pd.DataFrame({
"Missing_Count": missing,
"Missing_Percentage": missing_percentage
})
missing_data.sort_values(
"Missing_Percentage",
ascending=False
).head(20)| Missing_Count | Missing_Percentage | |
|---|---|---|
| COMMONAREA_AVG | 214865 | 69.872297 |
| COMMONAREA_MODE | 214865 | 69.872297 |
| COMMONAREA_MEDI | 214865 | 69.872297 |
| NONLIVINGAPARTMENTS_MEDI | 213514 | 69.432963 |
| NONLIVINGAPARTMENTS_MODE | 213514 | 69.432963 |
| NONLIVINGAPARTMENTS_AVG | 213514 | 69.432963 |
| FONDKAPREMONT_MODE | 210295 | 68.386172 |
| LIVINGAPARTMENTS_AVG | 210199 | 68.354953 |
| LIVINGAPARTMENTS_MEDI | 210199 | 68.354953 |
| LIVINGAPARTMENTS_MODE | 210199 | 68.354953 |
| FLOORSMIN_MODE | 208642 | 67.848630 |
| FLOORSMIN_AVG | 208642 | 67.848630 |
| FLOORSMIN_MEDI | 208642 | 67.848630 |
| YEARS_BUILD_AVG | 204488 | 66.497784 |
| YEARS_BUILD_MODE | 204488 | 66.497784 |
| YEARS_BUILD_MEDI | 204488 | 66.497784 |
| OWN_CAR_AGE | 202929 | 65.990810 |
| LANDAREA_MEDI | 182590 | 59.376738 |
| LANDAREA_AVG | 182590 | 59.376738 |
| LANDAREA_MODE | 182590 | 59.376738 |
In [37]
missing_data["Missing_Percentage"].describe()count 122.000000 mean 24.395942 std 28.446507 min 0.000000 25% 0.000000 50% 0.332021 75% 50.818020 max 69.872297 Name: Missing_Percentage, dtype: float64
In [38]
print("Columns with > 50% missing:")
print(missing_data[missing_data["Missing_Percentage"] > 50])Columns with > 50% missing:
Missing_Count Missing_Percentage
OWN_CAR_AGE 202929 65.990810
EXT_SOURCE_1 173378 56.381073
APARTMENTS_AVG 156061 50.749729
BASEMENTAREA_AVG 179943 58.515956
YEARS_BUILD_AVG 204488 66.497784
COMMONAREA_AVG 214865 69.872297
ELEVATORS_AVG 163891 53.295980
ENTRANCES_AVG 154828 50.348768
FLOORSMIN_AVG 208642 67.848630
LANDAREA_AVG 182590 59.376738
LIVINGAPARTMENTS_AVG 210199 68.354953
LIVINGAREA_AVG 154350 50.193326
NONLIVINGAPARTMENTS_AVG 213514 69.432963
NONLIVINGAREA_AVG 169682 55.179164
APARTMENTS_MODE 156061 50.749729
BASEMENTAREA_MODE 179943 58.515956
YEARS_BUILD_MODE 204488 66.497784
COMMONAREA_MODE 214865 69.872297
ELEVATORS_MODE 163891 53.295980
ENTRANCES_MODE 154828 50.348768
FLOORSMIN_MODE 208642 67.848630
LANDAREA_MODE 182590 59.376738
LIVINGAPARTMENTS_MODE 210199 68.354953
LIVINGAREA_MODE 154350 50.193326
NONLIVINGAPARTMENTS_MODE 213514 69.432963
NONLIVINGAREA_MODE 169682 55.179164
APARTMENTS_MEDI 156061 50.749729
BASEMENTAREA_MEDI 179943 58.515956
… 13 more linesIn [39]
corr = df.corr(numeric_only=True)["TARGET"].sort_values(ascending=False)
print(corr.head(15))TARGET 1.000000 DAYS_BIRTH 0.078239 REGION_RATING_CLIENT_W_CITY 0.060893 REGION_RATING_CLIENT 0.058899 DAYS_LAST_PHONE_CHANGE 0.055218 DAYS_ID_PUBLISH 0.051457 REG_CITY_NOT_WORK_CITY 0.050994 FLAG_EMP_PHONE 0.045982 REG_CITY_NOT_LIVE_CITY 0.044395 FLAG_DOCUMENT_3 0.044346 DAYS_REGISTRATION 0.041975 OWN_CAR_AGE 0.037612 LIVE_CITY_NOT_WORK_CITY 0.032518 DEF_30_CNT_SOCIAL_CIRCLE 0.032248 DEF_60_CNT_SOCIAL_CIRCLE 0.031276 Name: TARGET, dtype: float64
In [40]
print(corr.tail(15))LIVINGAREA_MEDI -0.032739 LIVINGAREA_AVG -0.032997 FLOORSMIN_MEDI -0.033394 FLOORSMIN_AVG -0.033614 ELEVATORS_MEDI -0.033863 ELEVATORS_AVG -0.034199 REGION_POPULATION_RELATIVE -0.037227 AMT_GOODS_PRICE -0.039645 FLOORSMAX_MODE -0.043226 FLOORSMAX_MEDI -0.043768 FLOORSMAX_AVG -0.044003 DAYS_EMPLOYED -0.044932 EXT_SOURCE_1 -0.155317 EXT_SOURCE_2 -0.160472 EXT_SOURCE_3 -0.178919 Name: TARGET, dtype: float64
In [41]
df.info()<class 'pandas.core.frame.DataFrame'> RangeIndex: 307511 entries, 0 to 307510 Columns: 122 entries, SK_ID_CURR to AMT_REQ_CREDIT_BUREAU_YEAR dtypes: float64(65), int64(41), object(16) memory usage: 286.2+ MB
In [42]
#Yeh pata karne ke liye ki kaunse column categorical data wale hai
df.select_dtypes(include=["object", "string"]).columnsIndex(['NAME_CONTRACT_TYPE', 'CODE_GENDER', 'FLAG_OWN_CAR', 'FLAG_OWN_REALTY',
'NAME_TYPE_SUITE', 'NAME_INCOME_TYPE', 'NAME_EDUCATION_TYPE',
'NAME_FAMILY_STATUS', 'NAME_HOUSING_TYPE', 'OCCUPATION_TYPE',
'WEEKDAY_APPR_PROCESS_START', 'ORGANIZATION_TYPE', 'FONDKAPREMONT_MODE',
'HOUSETYPE_MODE', 'WALLSMATERIAL_MODE', 'EMERGENCYSTATE_MODE'],
dtype='object')In [43]
""""Isse humein pata chalega:
Column
↓
Kitni categories?
↓
Missing values?
↓
Kaunsi category kitni baar?"""
categorical_columns = df.select_dtypes(
include=["object", "string"]
).columns
for column in categorical_columns:
print(f"\n{column}")
print(df[column].value_counts(dropna=False).head(10))NAME_CONTRACT_TYPE NAME_CONTRACT_TYPE Cash loans 278232 Revolving loans 29279 Name: count, dtype: int64 CODE_GENDER CODE_GENDER F 202448 M 105059 XNA 4 Name: count, dtype: int64 FLAG_OWN_CAR FLAG_OWN_CAR N 202924 Y 104587 Name: count, dtype: int64 FLAG_OWN_REALTY FLAG_OWN_REALTY Y 213312 N 94199 Name: count, dtype: int64 NAME_TYPE_SUITE NAME_TYPE_SUITE Unaccompanied 248526 Family 40149 Spouse, partner 11370 … 122 more lines
DATA CLEANING
In [44]
#SK_ID_CURR sirf applicant ki ID hai. Iska credit-risk prediction mein meaningful feature nahi hai.
df = df.drop(columns=["SK_ID_CURR"])In [45]
#60% se zyada missing → column drop
missing_percentage = df.isnull().mean() * 100
columns_to_drop = missing_percentage[missing_percentage > 60].index
print("Columns to drop:", len(columns_to_drop))
print(columns_to_drop)Columns to drop: 17
Index(['OWN_CAR_AGE', 'YEARS_BUILD_AVG', 'COMMONAREA_AVG', 'FLOORSMIN_AVG',
'LIVINGAPARTMENTS_AVG', 'NONLIVINGAPARTMENTS_AVG', 'YEARS_BUILD_MODE',
'COMMONAREA_MODE', 'FLOORSMIN_MODE', 'LIVINGAPARTMENTS_MODE',
'NONLIVINGAPARTMENTS_MODE', 'YEARS_BUILD_MEDI', 'COMMONAREA_MEDI',
'FLOORSMIN_MEDI', 'LIVINGAPARTMENTS_MEDI', 'NONLIVINGAPARTMENTS_MEDI',
'FONDKAPREMONT_MODE'],
dtype='object')In [46]
df = df.drop(columns=columns_to_drop)In [47]
categorical_columns = df.select_dtypes(
include=["object", "string"]
).columns
numerical_columns = df.select_dtypes(
include=["int64", "float64"]
).columns
print("Categorical columns:", len(categorical_columns))
print("Numerical columns:", len(numerical_columns))Categorical columns: 15 Numerical columns: 89
In [48]
df[numerical_columns] = df[numerical_columns].fillna(
df[numerical_columns].median()
)In [49]
df[categorical_columns] = df[categorical_columns].fillna("Missing")In [50]
#Yeha pe humne target variable ko alag kar diya hai aur baaki features ko X mein store kar diya hai
#Step 5 — TARGET ko X aur y mein separate karo
X = df.drop(columns=["TARGET"])
y = df["TARGET"]In [51]
#Train test split karne ke liye sklearn ka train_test_split function use karenge
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)In [52]
#Step 6 — Categorical encoding
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(
handle_unknown="ignore",
sparse_output=True
)In [53]
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)
print("X_train:", X_train.shape)
print("X_test :", X_test.shape)
print("y_train:", y_train.shape)
print("y_test :", y_test.shape)X_train: (246008, 103) X_test : (61503, 103) y_train: (246008,) y_test : (61503,)
In [54]
""""Numerical columns = 89
Categorical columns = 15"""
#Model categorization ke liye, humne categorical columns ko one-hot encoding mein convert kar diya hai. Isse model ko categorical data samajhne mein madad milegi.'"Numerical columns = 89\nCategorical columns = 15'
In [55]
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
categorical_features = X_train.select_dtypes(
include=["object", "string"]
).columns
numerical_features = X_train.select_dtypes(
include=["int64", "float64"]
).columns
preprocessor = ColumnTransformer(
transformers=[
(
"num",
"passthrough",
numerical_features
),
(
"cat",
OneHotEncoder(
handle_unknown="ignore",
sparse_output=False
),
categorical_features
)
]
)In [56]
print("Numerical features:", len(numerical_features))
print("Categorical features:", len(categorical_features))Numerical features: 88 Categorical features: 15
In [57]
X_train_processed = preprocessor.fit_transform(X_train)
X_test_processed = preprocessor.transform(X_test)
print("X_train processed:", X_train_processed.shape)
print("X_test processed :", X_test_processed.shape)X_train processed: (246008, 229) X_test processed : (61503, 229)
In [58]
df[numerical_columns] = df[numerical_columns].fillna(
df[numerical_columns].median()
)
df[categorical_columns] = df[categorical_columns].fillna("Missing")Model Training
In [59]
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(
class_weight="balanced",
max_iter=1000,
random_state=42
)
model.fit(X_train_processed, y_train)LogisticRegression(class_weight='balanced', max_iter=1000, random_state=42)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
LogisticRegression
?Documentation for LogisticRegressioniFitted
Parameters
|
class_weight
class_weight: dict or 'balanced', default=None Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))``. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. .. versionadded:: 0.17 *class_weight='balanced'* |
'balanced' | |
|
random_state
random_state: int, RandomState instance, default=None Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the data. See :term:`Glossary <random_state>` for details. |
42 | |
|
max_iter
max_iter: int, default=100 Maximum number of iterations taken for the solvers to converge. |
1000 | |
|
penalty
penalty: {'l1', 'l2', 'elasticnet', None}, default='l2' Specify the norm of the penalty: - `None`: no penalty is added; - `'l2'`: add an L2 penalty term and it is the default choice; - `'l1'`: add an L1 penalty term; - `'elasticnet'`: both L1 and L2 penalty terms are added. .. warning:: Some penalties may not work with some solvers. See the parameter `solver` below, to know the compatibility between the penalty and solver. .. versionadded:: 0.19 l1 penalty with SAGA solver (allowing 'multinomial' + L1) .. deprecated:: 1.8 `penalty` was deprecated in version 1.8 and will be removed in 1.10. Use `l1_ratio` and `C` instead. `l1_ratio=0` for `penalty='l2'`, `l1_ratio=1` for `penalty='l1'`, `l1_ratio` set to any float between 0 and 1 for `penalty='elasticnet'`, and `C=np.inf` for `penalty=None`. |
'deprecated' | |
|
C
C: float, default=1.0 Inverse of regularization strength; must be a positive float. Like in support vector machines, smaller values specify stronger regularization. `C=np.inf` results in unpenalized logistic regression. For a visual example on the effect of tuning the `C` parameter with an L1 penalty, see: :ref:`sphx_glr_auto_examples_linear_model_plot_logistic_path.py`. |
1.0 | |
|
l1_ratio
l1_ratio: float, default=0.0 The Elastic-Net mixing parameter, with `0 <= l1_ratio <= 1`. Setting `l1_ratio=1` gives a pure L1-penalty, setting `l1_ratio=0` a pure L2-penalty. Any value between 0 and 1 gives an Elastic-Net penalty of the form `l1_ratio * L1 + (1 - l1_ratio) * L2`. .. warning:: Certain values of `l1_ratio`, i.e. some penalties, may not work with some solvers. See the parameter `solver` below, to know the compatibility between the penalty and solver. .. versionchanged:: 1.8 Default value changed from None to 0.0. .. deprecated:: 1.8 `None` is deprecated and will be removed in version 1.10. Always use `l1_ratio` to specify the penalty type. |
0.0 | |
|
dual
dual: bool, default=False Dual (constrained) or primal (regularized, see also :ref:`this equation <regularized-logistic-loss>`) formulation. Dual formulation is only implemented for l2 penalty with liblinear solver. Prefer `dual=False` when n_samples > n_features. |
False | |
|
tol
tol: float, default=1e-4 Tolerance for stopping criteria. |
0.0001 | |
|
fit_intercept
fit_intercept: bool, default=True Specifies if a constant (a.k.a. bias or intercept) should be added to the decision function. |
True | |
|
intercept_scaling
intercept_scaling: float, default=1 Useful only when the solver `liblinear` is used and `self.fit_intercept` is set to `True`. In this case, `x` becomes `[x, self.intercept_scaling]`, i.e. a "synthetic" feature with constant value equal to `intercept_scaling` is appended to the instance vector. The intercept becomes ``intercept_scaling * synthetic_feature_weight``. .. note:: The synthetic feature weight is subject to L1 or L2 regularization as all other features. To lessen the effect of regularization on synthetic feature weight (and therefore on the intercept) `intercept_scaling` has to be increased. |
1 | |
|
solver
solver: {'lbfgs', 'liblinear', 'newton-cg', 'newton-cholesky', 'sag', 'saga'}, default='lbfgs' Algorithm to use in the optimization problem. Default is 'lbfgs'. To choose a solver, you might want to consider the following aspects: - 'lbfgs' is a good default solver because it works reasonably well for a wide class of problems. - For :term:`multiclass` problems (`n_classes >= 3`), all solvers except 'liblinear' minimize the full multinomial loss, 'liblinear' will raise an error. - 'newton-cholesky' is a good choice for `n_samples` >> `n_features * n_classes`, especially with one-hot encoded categorical features with rare categories. Be aware that the memory usage of this solver has a quadratic dependency on `n_features * n_classes` because it explicitly computes the full Hessian matrix. - For small datasets, 'liblinear' is a good choice, whereas 'sag' and 'saga' are faster for large ones; - 'liblinear' can only handle binary classification by default. To apply a one-versus-rest scheme for the multiclass setting one can wrap it with the :class:`~sklearn.multiclass.OneVsRestClassifier`. .. warning:: The choice of the algorithm depends on the penalty chosen (`l1_ratio=0` for L2-penalty, `l1_ratio=1` for L1-penalty and `0 < l1_ratio < 1` for Elastic-Net) and on (multinomial) multiclass support: ================= ======================== ====================== solver l1_ratio multinomial multiclass ================= ======================== ====================== 'lbfgs' l1_ratio=0 yes 'liblinear' l1_ratio=1 or l1_ratio=0 no 'newton-cg' l1_ratio=0 yes 'newton-cholesky' l1_ratio=0 yes 'sag' l1_ratio=0 yes 'saga' 0<=l1_ratio<=1 yes ================= ======================== ====================== .. note:: 'sag' and 'saga' fast convergence is only guaranteed on features with approximately the same scale. You can preprocess the data with a scaler from :mod:`sklearn.preprocessing`. .. seealso:: Refer to the :ref:`User Guide <Logistic_regression>` for more information regarding :class:`LogisticRegression` and more specifically the :ref:`Table <logistic_regression_solvers>` summarizing solver/penalty supports. .. versionadded:: 0.17 Stochastic Average Gradient (SAG) descent solver. Multinomial support in version 0.18. .. versionadded:: 0.19 SAGA solver. .. versionchanged:: 0.22 The default solver changed from 'liblinear' to 'lbfgs' in 0.22. .. versionadded:: 1.2 newton-cholesky solver. Multinomial support in version 1.6. |
'lbfgs' | |
|
verbose
verbose: int, default=0 For the liblinear and lbfgs solvers set verbose to any positive number for verbosity. |
0 | |
|
warm_start
warm_start: bool, default=False When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. Useless for liblinear solver. See :term:`the Glossary <warm_start>`. .. versionadded:: 0.17 *warm_start* to support *lbfgs*, *newton-cg*, *sag*, *saga* solvers. |
False | |
|
n_jobs
n_jobs: int, default=None Does not have any effect. .. deprecated:: 1.8 `n_jobs` is deprecated in version 1.8 and will be removed in 1.10. |
None |
Fitted attributes
| Name | Type | Value |
|---|---|---|
|
classes_
classes_: ndarray of shape (n_classes, ) A list of class labels known to the classifier. |
ndarray[int64](2,) | [0,1] |
|
coef_
coef_: ndarray or CSR matrix of shape (1, n_features) or (n_classes, n_features) Coefficients of the features in the decision function. `coef_` is of shape (1, n_features) when the given problem is binary. By default, it will be created as a dense array, but can be turned to sparse (CSR format) through :meth:`sparsify` (which can be beneficial under L1 regularization when many coefficients are zero), and back to dense through :meth:`densify`. |
ndarray[float64](1, 229) | [[ 0.01, 0. , 0. ,..., 0.01,-0. , 0. ]] |
|
intercept_
intercept_: ndarray of shape (1,) or (n_classes,) Intercept (a.k.a. bias) added to the decision function. If `fit_intercept` is set to False, the intercept is set to zero. `intercept_` is of shape (1,) when the given problem is binary. |
ndarray[float64](1,) | [0.01] |
|
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 0.24 |
int | 229 |
|
n_iter_
n_iter_: ndarray of shape (1, ) Actual number of iterations for all classes. .. versionchanged:: 0.20 In SciPy <= 1.0.0 the number of lbfgs iterations may exceed ``max_iter``. ``n_iter_`` will now report at most ``max_iter``. |
ndarray[int32](1,) | [1000] |
In [60]
y_pred = model.predict(X_test_processed)
y_prob = model.predict_proba(X_test_processed)[:, 1]In [61]
from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
f1_score,
roc_auc_score
)
print("=== LOGISTIC REGRESSION ===")
print("Accuracy :", accuracy_score(y_test, y_pred))
print("Precision :", precision_score(y_test, y_pred))
print("Recall :", recall_score(y_test, y_pred))
print("F1 Score :", f1_score(y_test, y_pred))
print("ROC-AUC :", roc_auc_score(y_test, y_prob))=== LOGISTIC REGRESSION === Accuracy : 0.585337300619482 Precision : 0.11336596385542169 Recall : 0.6064451158106747 F1 Score : 0.19102299762093577 ROC-AUC : 0.6292258195496816
In [62]
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt
cm = confusion_matrix(y_test, y_pred)
print(cm)
disp = ConfusionMatrixDisplay(
confusion_matrix=cm,
display_labels=["No Default", "Default"]
)
disp.plot()
plt.title("Logistic Regression - Confusion Matrix")
plt.show()[[32989 23549] [ 1954 3011]]
In [63]
from sklearn.metrics import classification_report
print(classification_report(
y_test,
y_pred,
target_names=["No Default", "Default"]
))precision recall f1-score support
No Default 0.94 0.58 0.72 56538
Default 0.11 0.61 0.19 4965
accuracy 0.59 61503
macro avg 0.53 0.59 0.46 61503
weighted avg 0.88 0.59 0.68 61503In [64]
from sklearn.ensemble import RandomForestClassifier
rf_model = RandomForestClassifier(
n_estimators=200,
max_depth=12,
min_samples_leaf=10,
class_weight="balanced",
random_state=42,
n_jobs=-1
)
rf_model.fit(X_train_processed, y_train)RandomForestClassifier(class_weight='balanced', max_depth=12,
min_samples_leaf=10, n_estimators=200, n_jobs=-1,
random_state=42)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
RandomForestClassifier
?Documentation for RandomForestClassifieriFitted
Parameters
|
n_estimators
n_estimators: int, default=100 The number of trees in the forest. .. versionchanged:: 0.22 The default value of ``n_estimators`` changed from 10 to 100 in 0.22. |
200 | |
|
max_depth
max_depth: int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. |
12 | |
|
min_samples_leaf
min_samples_leaf: int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. |
10 | |
|
n_jobs
n_jobs: int, default=None The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`, :meth:`decision_path` and :meth:`apply` are all parallelized over the trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. |
-1 | |
|
random_state
random_state: int, RandomState instance or None, default=None Controls both the randomness of the bootstrapping of the samples used when building trees (if ``bootstrap=True``) and the sampling of the features to consider when looking for the best split at each node (if ``max_features < n_features``). See :term:`Glossary <random_state>` for details. |
42 | |
|
class_weight
class_weight: {"balanced", "balanced_subsample"}, dict or list of dicts, default=None Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` The "balanced_subsample" mode is the same as "balanced" except that weights are computed based on the bootstrap sample for every tree grown. For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. |
'balanced' | |
|
criterion
criterion: {"gini", "entropy", "log_loss"}, default="gini" The function to measure the quality of a split. Supported criteria are "gini" for the Gini impurity and "log_loss" and "entropy" both for the Shannon information gain, see :ref:`tree_mathematical_formulation`. Note: This parameter is tree-specific. |
'gini' | |
|
min_samples_split
min_samples_split: int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. |
2 | |
|
min_weight_fraction_leaf
min_weight_fraction_leaf: float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. |
0.0 | |
|
max_features
max_features: {"sqrt", "log2", None}, int or float, default="sqrt" The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `max(1, int(max_features * n_features_in_))` features are considered at each split. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. .. versionchanged:: 1.1 The default of `max_features` changed from `"auto"` to `"sqrt"`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. |
'sqrt' | |
|
max_leaf_nodes
max_leaf_nodes: int, default=None Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. |
None | |
|
min_impurity_decrease
min_impurity_decrease: float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 |
0.0 | |
|
bootstrap
bootstrap: bool, default=True Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. |
True | |
|
oob_score
oob_score: bool or callable, default=False Whether to use out-of-bag samples to estimate the generalization score. By default, :func:`~sklearn.metrics.accuracy_score` is used. Provide a callable with signature `metric(y_true, y_pred)` to use a custom metric. Only available if `bootstrap=True`. For an illustration of out-of-bag (OOB) error estimation, see the example :ref:`sphx_glr_auto_examples_ensemble_plot_ensemble_oob.py`. |
False | |
|
verbose
verbose: int, default=0 Controls the verbosity when fitting and predicting. |
0 | |
|
warm_start
warm_start: bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`Glossary <warm_start>` and :ref:`tree_ensemble_warm_start` for details. |
False | |
|
ccp_alpha
ccp_alpha: non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. See :ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py` for an example of such pruning. .. versionadded:: 0.22 |
0.0 | |
|
max_samples
max_samples: int or float, default=None If bootstrap is True, the number of samples to draw from X to train each base estimator. - If None (default), then draw `X.shape[0]` samples irrespective of `sample_weight`. - If int, then draw `max_samples` samples. - If float, then draw `max_samples * X.shape[0]` unweighted samples or `max_samples * sample_weight.sum()` weighted samples. .. versionadded:: 0.22 .. versionchanged:: 1.9 Float `max_samples` is relative to `sample_weight.sum()` instead of `X.shape[0]` for weighted samples. |
None | |
|
monotonic_cst
monotonic_cst: array-like of int of shape (n_features), default=None Indicates the monotonicity constraint to enforce on each feature. - 1: monotonic increase - 0: no constraint - -1: monotonic decrease If monotonic_cst is None, no constraints are applied. Monotonicity constraints are not supported for: - multiclass classifications (i.e. when `n_classes > 2`), - multioutput classifications (i.e. when `n_outputs_ > 1`). The constraints hold over the probability of the positive class. Read more in the :ref:`User Guide <monotonic_cst_gbdt>`. .. versionadded:: 1.4 |
None |
Fitted attributes
| Name | Type | Value |
|---|---|---|
|
classes_
classes_: ndarray of shape (n_classes,) or a list of such arrays The classes labels (single output problem), or a list of arrays of class labels (multi-output problem). |
ndarray[int64](2,) | [0,1] |
|
estimator_
estimator_: :class:`~sklearn.tree.DecisionTreeClassifier` The child estimator template used to create the collection of fitted sub-estimators. .. versionadded:: 1.2 `base_estimator_` was renamed to `estimator_`. |
DecisionTreeClassifier | DecisionTreeClassifier() |
|
estimators_
estimators_: list of DecisionTreeClassifier The collection of fitted sub-estimators. |
list | [DecisionTreeC...te=1608637542), DecisionTreeC...te=1273642419), DecisionTreeC...te=1935803228), DecisionTreeC...ate=787846414), ...] |
|
estimators_samples_
estimators_samples_: list of arrays The subset of drawn samples (i.e., the in-bag samples) for each base estimator. Each subset is defined by an array of the indices selected. .. versionadded:: 1.4 |
list | [array([111853..., dtype=int32), array([100790..., dtype=int32), array([206308..., dtype=int32), array([109373..., dtype=int32), ...] |
|
feature_importances_
feature_importances_: ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. |
ndarray[float64](229,) | [0. ,0.01,0.02,...,0. ,0. ,0. ] |
|
n_classes_
n_classes_: int or list The number of classes (single output problem), or a list containing the number of classes for each output (multi-output problem). |
int | 2 |
|
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 0.24 |
int | 229 |
|
n_outputs_
n_outputs_: int The number of outputs when ``fit`` is performed. |
int | 1 |
In [65]
rf_pred = rf_model.predict(X_test_processed)
rf_prob = rf_model.predict_proba(X_test_processed)[:, 1]In [66]
from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
f1_score,
roc_auc_score
)
print("=== RANDOM FOREST ===")
print("Accuracy :", accuracy_score(y_test, rf_pred))
print("Precision:", precision_score(y_test, rf_pred))
print("Recall :", recall_score(y_test, rf_pred))
print("F1 Score :", f1_score(y_test, rf_pred))
print("ROC-AUC :", roc_auc_score(y_test, rf_prob))=== RANDOM FOREST === Accuracy : 0.7227127132009821 Precision: 0.16772030124786982 Recall : 0.6145015105740181 F1 Score : 0.26351701502850233 ROC-AUC : 0.7394137789386863
In [67]
results = pd.DataFrame({
"Model": ["Logistic Regression","Random Forest"],
"Accuracy": [accuracy_score(y_test, y_pred), accuracy_score(y_test, rf_pred)],
"Precision": [precision_score(y_test, y_pred), precision_score(y_test, rf_pred)],
"Recall": [recall_score(y_test, y_pred), recall_score(y_test, rf_pred)],
"F1": [f1_score(y_test, y_pred), f1_score(y_test, rf_pred)],
"ROC-AUC": [roc_auc_score(y_test, y_prob), roc_auc_score(y_test, rf_prob)]
})
results| Model | Accuracy | Precision | Recall | F1 | ROC-AUC | |
|---|---|---|---|---|---|---|
| 0 | Logistic Regression | 0.585337 | 0.113366 | 0.606445 | 0.191023 | 0.629226 |
| 1 | Random Forest | 0.722713 | 0.167720 | 0.614502 | 0.263517 | 0.739414 |
In [68]
from sklearn.ensemble import HistGradientBoostingClassifier
gb_model = HistGradientBoostingClassifier(
max_iter=200,
learning_rate=0.05,
max_leaf_nodes=31,
l2_regularization=1.0,
random_state=42
)
gb_model.fit(X_train_processed, y_train)HistGradientBoostingClassifier(l2_regularization=1.0, learning_rate=0.05,
max_iter=200, random_state=42)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
HistGradientBoostingClassifier
?Documentation for HistGradientBoostingClassifieriFitted
Parameters
|
learning_rate
learning_rate: float, default=0.1 The learning rate, also known as *shrinkage*. This is used as a multiplicative factor for the leaves values. Use ``1`` for no shrinkage. |
0.05 | |
|
max_iter
max_iter: int, default=100 The maximum number of iterations of the boosting process, i.e. the maximum number of trees for binary classification. For multiclass classification, `n_classes` trees per iteration are built. |
200 | |
|
l2_regularization
l2_regularization: float, default=0 The L2 regularization parameter penalizing leaves with small hessians. Use ``0`` for no regularization (default). |
1.0 | |
|
random_state
random_state: int, RandomState instance or None, default=None Pseudo-random number generator to control the subsampling in the binning process, and the train/validation data split if early stopping is enabled. Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`. |
42 | |
|
loss
loss: {'log_loss'}, default='log_loss' The loss function to use in the boosting process. For binary classification problems, 'log_loss' is also known as logistic loss, binomial deviance or binary crossentropy. Internally, the model fits one tree per boosting iteration and uses the logistic sigmoid function (expit) as inverse link function to compute the predicted positive class probability. For multiclass classification problems, 'log_loss' is also known as multinomial deviance or categorical crossentropy. Internally, the model fits one tree per boosting iteration and per class and uses the softmax function as inverse link function to compute the predicted probabilities of the classes. |
'log_loss' | |
|
max_leaf_nodes
max_leaf_nodes: int or None, default=31 The maximum number of leaves for each tree. Must be strictly greater than 1. If None, there is no maximum limit. |
31 | |
|
max_depth
max_depth: int or None, default=None The maximum depth of each tree. The depth of a tree is the number of edges to go from the root to the deepest leaf. Depth isn't constrained by default. |
None | |
|
min_samples_leaf
min_samples_leaf: int, default=20 The minimum number of samples per leaf. For small datasets with less than a few hundred samples, it is recommended to lower this value since only very shallow trees would be built. |
20 | |
|
max_features
max_features: float, default=1.0 Proportion of randomly chosen features in each and every node split. This is a form of regularization, smaller values make the trees weaker learners and might prevent overfitting. If interaction constraints from `interaction_cst` are present, only allowed features are taken into account for the subsampling. .. versionadded:: 1.4 |
1.0 | |
|
max_bins
max_bins: int, default=255 The maximum number of bins to use for non-missing values. Before training, each feature of the input array `X` is binned into integer-valued bins, which allows for a much faster training stage. Features with a small number of unique values may use less than ``max_bins`` bins. In addition to the ``max_bins`` bins, one more bin is always reserved for missing values. Must be no larger than 255. |
255 | |
|
categorical_features
categorical_features: array-like of {bool, int, str} of shape (n_features) or shape (n_categorical_features,), default='from_dtype' Indicates the categorical features. - None : no feature will be considered categorical. - boolean array-like : boolean mask indicating categorical features. - integer array-like : integer indices indicating categorical features. - str array-like: names of categorical features (assuming the training data has feature names). - `"from_dtype"`: dataframe columns with dtype "Categorical" and "Enum" are considered to be categorical features. The input must be a dataframe that is supported by narwhals (or supports it): :func:`narwhals.from_native` must work. This is the case, for instance, for pandas and polars DataFrames. For each categorical feature, there must be at most `max_bins` unique categories. Negative values for categorical features encoded as numeric dtypes are treated as missing values. All categorical values are converted to floating point numbers. This means that categorical values of 1.0 and 1 are treated as the same category. Read more in the :ref:`User Guide <categorical_support_gbdt>`. .. versionadded:: 0.24 .. versionchanged:: 1.2 Added support for feature names. .. versionchanged:: 1.4 Added `"from_dtype"` option. .. versionchanged:: 1.6 The default value changed from `None` to `"from_dtype"`. |
'from_dtype' | |
|
monotonic_cst
monotonic_cst: array-like of int of shape (n_features) or dict, default=None Monotonic constraint to enforce on each feature are specified using the following integer values: - 1: monotonic increase - 0: no constraint - -1: monotonic decrease If a dict with str keys, map feature to monotonic constraints by name. If an array, the features are mapped to constraints by position. See :ref:`monotonic_cst_features_names` for a usage example. The constraints are only valid for binary classifications and hold over the probability of the positive class. Read more in the :ref:`User Guide <monotonic_cst_gbdt>`. .. versionadded:: 0.23 .. versionchanged:: 1.2 Accept dict of constraints with feature names as keys. |
None | |
|
interaction_cst
interaction_cst: {"pairwise", "no_interactions"} or sequence of lists/tuples/sets of int, default=None Specify interaction constraints, the sets of features which can interact with each other in child node splits. Each item specifies the set of feature indices that are allowed to interact with each other. If there are more features than specified in these constraints, they are treated as if they were specified as an additional set. The strings "pairwise" and "no_interactions" are shorthands for allowing only pairwise or no interactions, respectively. For instance, with 5 features in total, `interaction_cst=[{0, 1}]` is equivalent to `interaction_cst=[{0, 1}, {2, 3, 4}]`, and specifies that each branch of a tree will either only split on features 0 and 1 or only split on features 2, 3 and 4. See :ref:`this example<ice-vs-pdp>` on how to use `interaction_cst`. .. versionadded:: 1.2 |
None | |
|
warm_start
warm_start: bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble. For results to be valid, the estimator should be re-trained on the same data only. See :term:`the Glossary <warm_start>`. |
False | |
|
early_stopping
early_stopping: 'auto' or bool, default='auto' If 'auto', early stopping is enabled if the sample size is larger than 10000 or if `X_val` and `y_val` are passed to `fit`. If True, early stopping is enabled, otherwise early stopping is disabled. .. versionadded:: 0.23 |
'auto' | |
|
scoring
scoring: str or callable or None, default='loss' Scoring method to use for early stopping. Only used if `early_stopping` is enabled. Options: - str: see :ref:`scoring_string_names` for options. - callable: a scorer callable object (e.g., function) with signature ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. - `None`: :ref:`accuracy <accuracy_score>` is used. - 'loss': early stopping is checked w.r.t the loss value. |
'loss' | |
|
validation_fraction
validation_fraction: int or float or None, default=0.1 Proportion (or absolute size) of training data to set aside as validation data for early stopping. If None, early stopping is done on the training data. The value is ignored if either early stopping is not performed, e.g. `early_stopping=False`, or if `X_val` and `y_val` are passed to fit. |
0.1 | |
|
n_iter_no_change
n_iter_no_change: int, default=10 Used to determine when to "early stop". The fitting process is stopped when none of the last ``n_iter_no_change`` scores are better than the ``n_iter_no_change - 1`` -th-to-last one, up to some tolerance. Only used if early stopping is performed. |
10 | |
|
tol
tol: float, default=1e-7 The absolute tolerance to use when comparing scores. The higher the tolerance, the more likely we are to early stop: higher tolerance means that it will be harder for subsequent iterations to be considered an improvement upon the reference score. |
1e-07 | |
|
verbose
verbose: int, default=0 The verbosity level. If not zero, print some information about the fitting process. ``1`` prints only summary info, ``2`` prints info per iteration. |
0 | |
|
class_weight
class_weight: dict or 'balanced', default=None Weights associated with classes in the form `{class_label: weight}`. If not given, all classes are supposed to have weight one. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as `n_samples / (n_classes * np.bincount(y))`. Note that these weights will be multiplied with sample_weight (passed through the fit method) if `sample_weight` is specified. .. versionadded:: 1.2 |
None |
Fitted attributes
| Name | Type | Value |
|---|---|---|
|
classes_
classes_: array, shape = (n_classes,) Class labels. |
ndarray[int64](2,) | [0,1] |
|
do_early_stopping_
do_early_stopping_: bool Indicates whether early stopping is used during training. |
bool | True |
|
is_categorical_
is_categorical_: ndarray, shape (n_features, ) or None Boolean mask for the categorical features. ``None`` if there are no categorical features. |
NoneType | None |
|
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 0.24 |
int | 229 |
|
n_iter_
n_iter_: int The number of iterations as selected by early stopping, depending on the `early_stopping` parameter. Otherwise it corresponds to max_iter. |
int | 200 |
|
n_trees_per_iteration_
n_trees_per_iteration_: int The number of tree that are built at each iteration. This is equal to 1 for binary classification, and to ``n_classes`` for multiclass classification. |
int | 1 |
|
train_score_
train_score_: ndarray, shape (n_iter_+1,) The scores at each iteration on the training data. The first entry is the score of the ensemble before the first iteration. Scores are computed according to the ``scoring`` parameter. If ``scoring`` is not 'loss', scores are computed on a subset of at most 10 000 samples. Empty if no early stopping. |
ndarray[float64](201,) | [-0.28,-0.28,-0.28,...,-0.24,-0.24,-0.24] |
|
validation_score_
validation_score_: ndarray, shape (n_iter_+1,) The scores at each iteration on the held-out validation data. The first entry is the score of the ensemble before the first iteration. Scores are computed according to the ``scoring`` parameter. Empty if no early stopping or if ``validation_fraction`` is None. |
ndarray[float64](201,) | [-0.28,-0.28,-0.28,...,-0.25,-0.25,-0.25] |
In [69]
gb_pred = gb_model.predict(X_test_processed)
gb_prob = gb_model.predict_proba(X_test_processed)[:, 1]In [70]
print("=== HISTOGRAM GRADIENT BOOSTING ===")
print("Accuracy :", accuracy_score(y_test, gb_pred))
print("Precision:", precision_score(y_test, gb_pred))
print("Recall :", recall_score(y_test, gb_pred))
print("F1 Score :", f1_score(y_test, gb_pred))
print("ROC-AUC :", roc_auc_score(y_test, gb_prob))=== HISTOGRAM GRADIENT BOOSTING === Accuracy : 0.9198087898151309 Precision: 0.6037735849056604 Recall : 0.01933534743202417 F1 Score : 0.03747072599531616 ROC-AUC : 0.759978307952619
In [71]
results = pd.DataFrame({
"Model": [
"Logistic Regression",
"Random Forest",
"HistGradientBoosting"
],
"Accuracy": [
accuracy_score(y_test, y_pred),
accuracy_score(y_test, rf_pred),
accuracy_score(y_test, gb_pred)
],
"Precision": [
precision_score(y_test, y_pred),
precision_score(y_test, rf_pred),
precision_score(y_test, gb_pred)
],
"Recall": [
recall_score(y_test, y_pred),
recall_score(y_test, rf_pred),
recall_score(y_test, gb_pred)
],
"F1": [
f1_score(y_test, y_pred),
f1_score(y_test, rf_pred),
f1_score(y_test, gb_pred)
],
"ROC-AUC": [
roc_auc_score(y_test, y_prob),
roc_auc_score(y_test, rf_prob),
roc_auc_score(y_test, gb_prob)
]
})
results| Model | Accuracy | Precision | Recall | F1 | ROC-AUC | |
|---|---|---|---|---|---|---|
| 0 | Logistic Regression | 0.585337 | 0.113366 | 0.606445 | 0.191023 | 0.629226 |
| 1 | Random Forest | 0.722713 | 0.167720 | 0.614502 | 0.263517 | 0.739414 |
| 2 | HistGradientBoosting | 0.919809 | 0.603774 | 0.019335 | 0.037471 | 0.759978 |
In [72]
import numpy as np
from sklearn.metrics import precision_score, recall_score, f1_score
threshold_results = []
for threshold in np.arange(0.10, 0.51, 0.05):
pred = (gb_prob >= threshold).astype(int)
threshold_results.append({
"Threshold": threshold,
"Precision": precision_score(y_test, pred, zero_division=0),
"Recall": recall_score(y_test, pred),
"F1": f1_score(y_test, pred)
})
threshold_df = pd.DataFrame(threshold_results)
threshold_df| Threshold | Precision | Recall | F1 | |
|---|---|---|---|---|
| 0 | 0.10 | 0.190751 | 0.592346 | 0.288574 |
| 1 | 0.15 | 0.249789 | 0.417925 | 0.312688 |
| 2 | 0.20 | 0.298715 | 0.290232 | 0.294412 |
| 3 | 0.25 | 0.346531 | 0.199194 | 0.252974 |
| 4 | 0.30 | 0.381503 | 0.132931 | 0.197162 |
| 5 | 0.35 | 0.428991 | 0.088218 | 0.146341 |
| 6 | 0.40 | 0.492754 | 0.054783 | 0.098604 |
| 7 | 0.45 | 0.530822 | 0.031219 | 0.058969 |
| 8 | 0.50 | 0.603774 | 0.019335 | 0.037471 |
In [73]
threshold_df.loc[
threshold_df["F1"].idxmax()
]Threshold 0.150000 Precision 0.249789 Recall 0.417925 F1 0.312688 Name: 1, dtype: float64
In [74]
final_threshold = 0.15
final_pred = (gb_prob >= final_threshold).astype(int)
print("=== FINAL HISTGRADIENTBOOSTING ===")
print("Threshold :", final_threshold)
print("Precision :", precision_score(y_test, final_pred))
print("Recall :", recall_score(y_test, final_pred))
print("F1 Score :", f1_score(y_test, final_pred))
print("ROC-AUC :", roc_auc_score(y_test, gb_prob))=== FINAL HISTGRADIENTBOOSTING === Threshold : 0.15 Precision : 0.24978933429637654 Recall : 0.4179254783484391 F1 Score : 0.31268836648583487 ROC-AUC : 0.759978307952619
In [75]
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
cm = confusion_matrix(y_test, final_pred)
print(cm)
disp = ConfusionMatrixDisplay(
confusion_matrix=cm,
display_labels=["No Default", "Default"]
)
disp.plot()
plt.title("Final Model - Confusion Matrix (Threshold = 0.15)")
plt.show()[[50306 6232] [ 2890 2075]]
In [76]
print(
classification_report(
y_test,
final_pred,
target_names=["No Default", "Default"]
)
)precision recall f1-score support
No Default 0.95 0.89 0.92 56538
Default 0.25 0.42 0.31 4965
accuracy 0.85 61503
macro avg 0.60 0.65 0.61 61503
weighted avg 0.89 0.85 0.87 61503In [77]
from sklearn.metrics import roc_curve, roc_auc_score
import matplotlib.pyplot as plt
fpr, tpr, thresholds = roc_curve(y_test, gb_prob)
auc = roc_auc_score(y_test, gb_prob)
plt.figure(figsize=(8, 6))
plt.plot(fpr, tpr, label=f"HistGradientBoosting (AUC = {auc:.3f})")
plt.plot([0, 1], [0, 1], linestyle="--")
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("ROC Curve - HistGradientBoosting")
plt.legend()
plt.show()In [78]
from sklearn.metrics import precision_recall_curve
precision, recall, thresholds = precision_recall_curve(
y_test,
gb_prob
)
plt.figure(figsize=(8, 6))
plt.plot(recall, precision)
plt.xlabel("Recall")
plt.ylabel("Precision")
plt.title("Precision-Recall Curve - HistGradientBoosting")
plt.grid()
plt.show()In [79]
plt.figure(figsize=(8, 6))
plt.plot(
threshold_df["Threshold"],
threshold_df["Precision"],
marker="o",
label="Precision"
)
plt.plot(
threshold_df["Threshold"],
threshold_df["Recall"],
marker="o",
label="Recall"
)
plt.plot(
threshold_df["Threshold"],
threshold_df["F1"],
marker="o",
label="F1 Score"
)
plt.axvline(
x=0.15,
linestyle="--",
label="Best Threshold = 0.15"
)
plt.xlabel("Threshold")
plt.ylabel("Score")
plt.title("Threshold Analysis")
plt.legend()
plt.grid()
plt.show()In [80]
from sklearn.inspection import permutation_importance
perm_importance = permutation_importance(
gb_model,
X_test_processed,
y_test,
n_repeats=5,
random_state=42,
scoring="roc_auc",
n_jobs=-1
)
feature_names = preprocessor.get_feature_names_out()
importance_df = pd.DataFrame({
"Feature": feature_names,
"Importance": perm_importance.importances_mean
})
importance_df = importance_df.sort_values(
"Importance",
ascending=False
)
importance_df.head(20)| Feature | Importance | |
|---|---|---|
| 28 | num__EXT_SOURCE_3 | 0.062478 |
| 27 | num__EXT_SOURCE_2 | 0.048455 |
| 4 | num__AMT_GOODS_PRICE | 0.019804 |
| 26 | num__EXT_SOURCE_1 | 0.019637 |
| 2 | num__AMT_CREDIT | 0.012610 |
| 6 | num__DAYS_BIRTH | 0.006826 |
| 3 | num__AMT_ANNUITY | 0.004238 |
| 7 | num__DAYS_EMPLOYED | 0.003826 |
| 90 | cat__CODE_GENDER_F | 0.002707 |
| 114 | cat__NAME_EDUCATION_TYPE_Higher education | 0.002321 |
| 93 | cat__FLAG_OWN_CAR_N | 0.002181 |
| 9 | num__DAYS_ID_PUBLISH | 0.001773 |
| 119 | cat__NAME_FAMILY_STATUS_Married | 0.001443 |
| 88 | cat__NAME_CONTRACT_TYPE_Cash loans | 0.001372 |
| 61 | num__DAYS_LAST_PHONE_CHANGE | 0.001181 |
| 86 | num__AMT_REQ_CREDIT_BUREAU_QRT | 0.000878 |
| 91 | cat__CODE_GENDER_M | 0.000840 |
| 63 | num__FLAG_DOCUMENT_3 | 0.000743 |
| 112 | cat__NAME_INCOME_TYPE_Working | 0.000685 |
| 8 | num__DAYS_REGISTRATION | 0.000610 |
In [81]
top_features = importance_df.head(20).sort_values(
"Importance"
)
plt.figure(figsize=(10, 8))
plt.barh(
top_features["Feature"],
top_features["Importance"]
)
plt.xlabel("Permutation Importance")
plt.ylabel("Feature")
plt.title("Top 20 Feature Importance - HistGradientBoosting")
plt.tight_layout()
plt.show()In [82]
from sklearn.pipeline import Pipeline
final_pipeline = Pipeline([
("preprocessor", preprocessor),
("model", gb_model)
])
final_pipelinePipeline(steps=[('preprocessor',
ColumnTransformer(transformers=[('num', 'passthrough',
Index(['CNT_CHILDREN', 'AMT_INCOME_TOTAL', 'AMT_CREDIT', 'AMT_ANNUITY',
'AMT_GOODS_PRICE', 'REGION_POPULATION_RELATIVE', 'DAYS_BIRTH',
'DAYS_EMPLOYED', 'DAYS_REGISTRATION', 'DAYS_ID_PUBLISH', 'FLAG_MOBIL',
'FLAG_EMP_PHONE', 'FLAG_WORK_PHONE', 'FLAG_CONT_MOBILE', 'FLAG_PHONE',
'FL...
'NAME_TYPE_SUITE', 'NAME_INCOME_TYPE', 'NAME_EDUCATION_TYPE',
'NAME_FAMILY_STATUS', 'NAME_HOUSING_TYPE', 'OCCUPATION_TYPE',
'WEEKDAY_APPR_PROCESS_START', 'ORGANIZATION_TYPE', 'HOUSETYPE_MODE',
'WALLSMATERIAL_MODE', 'EMERGENCYSTATE_MODE'],
dtype='object'))])),
('model',
HistGradientBoostingClassifier(l2_regularization=1.0,
learning_rate=0.05,
max_iter=200,
random_state=42))])In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Pipeline
?Documentation for PipelineiFitted
Parameters
|
steps
steps: list of tuples List of (name of step, estimator) tuples that are to be chained in sequential order. To be compatible with the scikit-learn API, all steps must define `fit`. All non-last steps must also define `transform`. See :ref:`Combining Estimators <combining_estimators>` for more details. |
[('preprocessor', ...), ('model', ...)] | |
|
transform_input
transform_input: list of str, default=None The names of the :term:`metadata` parameters that should be transformed by the pipeline before passing it to the step consuming it. This enables transforming some input arguments to ``fit`` (other than ``X``) to be transformed by the steps of the pipeline up to the step which requires them. Requirement is defined via :ref:`metadata routing <metadata_routing>`. For instance, this can be used to pass a validation set through the pipeline. You can only set this if metadata routing is enabled, which you can enable using ``sklearn.set_config(enable_metadata_routing=True)``. .. versionadded:: 1.6 |
None | |
|
memory
memory: str or object with the joblib.Memory interface, default=None Used to cache the fitted transformers of the pipeline. The last step will never be cached, even if it is a transformer. By default, no caching is performed. If a string is given, it is the path to the caching directory. Enabling caching triggers a clone of the transformers before fitting. Therefore, the transformer instance given to the pipeline cannot be inspected directly. Use the attribute ``named_steps`` or ``steps`` to inspect estimators within the pipeline. Caching the transformers is advantageous when fitting is time consuming. See :ref:`sphx_glr_auto_examples_neighbors_plot_caching_nearest_neighbors.py` for an example on how to enable caching. |
None | |
|
verbose
verbose: bool, default=False If True, the time elapsed while fitting each step will be printed as it is completed. |
False |
Fitted attributes
| Name | Type | Value |
|---|---|---|
|
classes_
classes_: ndarray of shape (n_classes,) The classes labels. Only exist if the last step of the pipeline is a classifier. |
ndarray[int64](2,) | [0,1] |
|
feature_names_in_
feature_names_in_: ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Only defined if the underlying estimator exposes such an attribute when fit. .. versionadded:: 1.0 |
ndarray[object](103,) | ['NAME_CONTRACT_TYPE','CODE_GENDER','FLAG_OWN_CAR',..., 'AMT_REQ_CREDIT_BUREAU_MON','AMT_REQ_CREDIT_BUREAU_QRT', 'AMT_REQ_CREDIT_BUREAU_YEAR'] |
|
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. Only defined if the underlying first estimator in `steps` exposes such an attribute when fit. .. versionadded:: 0.24 |
int | 103 |
preprocessor: ColumnTransformer
?Documentation for preprocessor: ColumnTransformer
Parameters
|
transformers
transformers: list of tuples List of (name, transformer, columns) tuples specifying the transformer objects to be applied to subsets of the data. name : str Like in Pipeline and FeatureUnion, this allows the transformer and its parameters to be set using ``set_params`` and searched in grid search. transformer : {'drop', 'passthrough'} or estimator Estimator must support :term:`fit` and :term:`transform`. Special-cased strings 'drop' and 'passthrough' are accepted as well, to indicate to drop the columns or to pass them through untransformed, respectively. columns : str, array-like of str, int, array-like of int, array-like of bool, slice or callable Indexes the data on its second axis. Integers are interpreted as positional columns, while strings can reference DataFrame columns by name. A scalar string or int should be used where ``transformer`` expects X to be a 1d array-like (vector), otherwise a 2d array will be passed to the transformer. A callable is passed the input data `X` and can return any of the above. To select multiple columns by name or dtype, you can use :obj:`make_column_selector`. |
[('num', ...), ('cat', ...)] | |
|
remainder
remainder: {'drop', 'passthrough'} or estimator, default='drop' By default, only the specified columns in `transformers` are transformed and combined in the output, and the non-specified columns are dropped. (default of ``'drop'``). By specifying ``remainder='passthrough'``, all remaining columns that were not specified in `transformers`, but present in the data passed to `fit` will be automatically passed through. This subset of columns is concatenated with the output of the transformers. For dataframes, extra columns not seen during `fit` will be excluded from the output of `transform`. By setting ``remainder`` to be an estimator, the remaining non-specified columns will use the ``remainder`` estimator. The estimator must support :term:`fit` and :term:`transform`. Note that using this feature requires that the DataFrame columns input at :term:`fit` and :term:`transform` have identical order. |
'drop' | |
|
sparse_threshold
sparse_threshold: float, default=0.3 If the output of the different transformers contains sparse matrices, these will be stacked as a sparse matrix if the overall density is lower than this value. Use ``sparse_threshold=0`` to always return dense. When the transformed output consists of all dense data, the stacked result will be dense, and this keyword will be ignored. |
0.3 | |
|
n_jobs
n_jobs: int, default=None Number of jobs to run in parallel. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. |
None | |
|
transformer_weights
transformer_weights: dict, default=None Multiplicative weights for features per transformer. The output of the transformer is multiplied by these weights. Keys are transformer names, values the weights. |
None | |
|
verbose
verbose: bool, default=False If True, the time elapsed while fitting each transformer will be printed as it is completed. |
False | |
|
verbose_feature_names_out
verbose_feature_names_out: bool, str or Callable[[str, str], str], default=True - If True, :meth:`ColumnTransformer.get_feature_names_out` will prefix all feature names with the name of the transformer that generated that feature. It is equivalent to setting `verbose_feature_names_out="{transformer_name}__{feature_name}"`. - If False, :meth:`ColumnTransformer.get_feature_names_out` will not prefix any feature names and will error if feature names are not unique. - If ``Callable[[str, str], str]``, :meth:`ColumnTransformer.get_feature_names_out` will rename all the features using the name of the transformer. The first argument of the callable is the transformer name and the second argument is the feature name. The returned string will be the new feature name. - If ``str``, it must be a string ready for formatting. The given string will be formatted using two field names: ``transformer_name`` and ``feature_name``. e.g. ``"{feature_name}__{transformer_name}"``. See :meth:`str.format` method from the standard library for more info. .. versionadded:: 1.0 .. versionchanged:: 1.6 `verbose_feature_names_out` can be a callable or a string to be formatted. |
True |
Fitted attributes
| Name | Type | Value |
|---|---|---|
|
feature_names_in_
feature_names_in_: ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 |
ndarray[object](103,) | ['NAME_CONTRACT_TYPE','CODE_GENDER','FLAG_OWN_CAR',..., 'AMT_REQ_CREDIT_BUREAU_MON','AMT_REQ_CREDIT_BUREAU_QRT', 'AMT_REQ_CREDIT_BUREAU_YEAR'] |
|
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. Only defined if the underlying transformers expose such an attribute when fit. .. versionadded:: 0.24 |
int | 103 |
|
named_transformers_
named_transformers_: :class:`~sklearn.utils.Bunch` Read-only attribute to access any transformer by given name. Keys are transformer names and values are the fitted transformer objects. |
Bunch | {'num': Funct...output=False)} |
|
output_indices_
output_indices_: dict A dictionary from each transformer name to a slice, where the slice corresponds to indices in the transformed output. This is useful to inspect which transformer is responsible for which transformed feature(s). .. versionadded:: 1.0 |
dict | {'cat': slice(88, 229, None), 'num': slice(0, 88, None), 're...er': slice(0, 0, None)} |
|
sparse_output_
sparse_output_: bool Boolean flag indicating whether the output of ``transform`` is a sparse matrix or a dense numpy array, which depends on the output of the individual transformers and the `sparse_threshold` keyword. |
bool | False |
|
transformers_
transformers_: list The collection of fitted transformers as tuples of (name, fitted_transformer, column). `fitted_transformer` can be an estimator, or `'drop'`; `'passthrough'` is replaced with an equivalent :class:`~sklearn.preprocessing.FunctionTransformer`. In case there were no columns selected, this will be the unfitted transformer. If there are remaining columns, the final element is a tuple of the form: ('remainder', transformer, remaining_columns) corresponding to the ``remainder`` parameter. If there are remaining columns, then ``len(transformers_)==len(transformers)+1``, otherwise ``len(transformers_)==len(transformers)``. .. versionadded:: 1.7 The format of the remaining columns now attempts to match that of the other transformers: if all columns were provided as column names (`str`), the remaining columns are stored as column names; if all columns were provided as mask arrays (`bool`), so are the remaining columns; in all other cases the remaining columns are stored as indices (`int`). |
list | [('num', FunctionTrans...='one-to-one'), Index(['CNT_C...type='object')), ('cat', OneHotEncoder..._output=False), Index(['NAME_...type='object'))] |
num
Index(['CNT_CHILDREN', 'AMT_INCOME_TOTAL', 'AMT_CREDIT', 'AMT_ANNUITY',
'AMT_GOODS_PRICE', 'REGION_POPULATION_RELATIVE', 'DAYS_BIRTH',
'DAYS_EMPLOYED', 'DAYS_REGISTRATION', 'DAYS_ID_PUBLISH', 'FLAG_MOBIL',
'FLAG_EMP_PHONE', 'FLAG_WORK_PHONE', 'FLAG_CONT_MOBILE', 'FLAG_PHONE',
'FLAG_EMAIL', 'CNT_FAM_MEMBERS', 'REGION_RATING_CLIENT',
'REGION_RATING_CLIENT_W_CITY', 'HOUR_APPR_PROCESS_START',
'REG_REGION_NOT_LIVE_REGION', 'REG_REGION_NOT_WORK_REGION',
'LIVE_REGION_NOT_WORK_REGION', 'REG_CITY_NOT_LIVE_CITY',
'REG_CITY_NOT_WORK_CITY', 'LIVE_CITY_NOT_WORK_CITY', 'EXT_SOURCE_1',
'EXT_SOURCE_2', 'EXT_SOURCE_3', 'APARTMENTS_AVG', 'BASEMENTAREA_AVG',
'YEARS_BEGINEXPLUATATION_AVG', 'ELEVATORS_AVG', 'ENTRANCES_AVG',
'FLOORSMAX_AVG', 'LANDAREA_AVG', 'LIVINGAREA_AVG', 'NONLIVINGAREA_AVG',
'APARTMENTS_MODE', 'BASEMENTAREA_MODE', 'YEARS_BEGINEXPLUATATION_MODE',
'ELEVATORS_MODE', 'ENTRANCES_MODE', 'FLOORSMAX_MODE', 'LANDAREA_MODE',
'LIVINGAREA_MODE', 'NONLIVINGAREA_MODE', 'APARTMENTS_MEDI',
'BASEMENTAREA_MEDI', 'YEARS_BEGINEXPLUATATION_MEDI', 'ELEVATORS_MEDI',
'ENTRANCES_MEDI', 'FLOORSMAX_MEDI', 'LANDAREA_MEDI', 'LIVINGAREA_MEDI',
'NONLIVINGAREA_MEDI', 'TOTALAREA_MODE', 'OBS_30_CNT_SOCIAL_CIRCLE',
'DEF_30_CNT_SOCIAL_CIRCLE', 'OBS_60_CNT_SOCIAL_CIRCLE',
'DEF_60_CNT_SOCIAL_CIRCLE', 'DAYS_LAST_PHONE_CHANGE', 'FLAG_DOCUMENT_2',
'FLAG_DOCUMENT_3', 'FLAG_DOCUMENT_4', 'FLAG_DOCUMENT_5',
'FLAG_DOCUMENT_6', 'FLAG_DOCUMENT_7', 'FLAG_DOCUMENT_8',
'FLAG_DOCUMENT_9', 'FLAG_DOCUMENT_10', 'FLAG_DOCUMENT_11',
'FLAG_DOCUMENT_12', 'FLAG_DOCUMENT_13', 'FLAG_DOCUMENT_14',
'FLAG_DOCUMENT_15', 'FLAG_DOCUMENT_16', 'FLAG_DOCUMENT_17',
'FLAG_DOCUMENT_18', 'FLAG_DOCUMENT_19', 'FLAG_DOCUMENT_20',
'FLAG_DOCUMENT_21', 'AMT_REQ_CREDIT_BUREAU_HOUR',
'AMT_REQ_CREDIT_BUREAU_DAY', 'AMT_REQ_CREDIT_BUREAU_WEEK',
'AMT_REQ_CREDIT_BUREAU_MON', 'AMT_REQ_CREDIT_BUREAU_QRT',
'AMT_REQ_CREDIT_BUREAU_YEAR'],
dtype='object')
passthrough
?Documentation for FunctionTransformer
88 features
| CNT_CHILDREN |
| AMT_INCOME_TOTAL |
| AMT_CREDIT |
| AMT_ANNUITY |
| AMT_GOODS_PRICE |
| REGION_POPULATION_RELATIVE |
| DAYS_BIRTH |
| DAYS_EMPLOYED |
| DAYS_REGISTRATION |
| DAYS_ID_PUBLISH |
| FLAG_MOBIL |
| FLAG_EMP_PHONE |
| FLAG_WORK_PHONE |
| FLAG_CONT_MOBILE |
| FLAG_PHONE |
| FLAG_EMAIL |
| CNT_FAM_MEMBERS |
| REGION_RATING_CLIENT |
| REGION_RATING_CLIENT_W_CITY |
| HOUR_APPR_PROCESS_START |
| REG_REGION_NOT_LIVE_REGION |
| REG_REGION_NOT_WORK_REGION |
| LIVE_REGION_NOT_WORK_REGION |
| REG_CITY_NOT_LIVE_CITY |
| REG_CITY_NOT_WORK_CITY |
| LIVE_CITY_NOT_WORK_CITY |
| EXT_SOURCE_1 |
| EXT_SOURCE_2 |
| EXT_SOURCE_3 |
| APARTMENTS_AVG |
| BASEMENTAREA_AVG |
| YEARS_BEGINEXPLUATATION_AVG |
| ELEVATORS_AVG |
| ENTRANCES_AVG |
| FLOORSMAX_AVG |
| LANDAREA_AVG |
| LIVINGAREA_AVG |
| NONLIVINGAREA_AVG |
| APARTMENTS_MODE |
| BASEMENTAREA_MODE |
| YEARS_BEGINEXPLUATATION_MODE |
| ELEVATORS_MODE |
| ENTRANCES_MODE |
| FLOORSMAX_MODE |
| LANDAREA_MODE |
| LIVINGAREA_MODE |
| NONLIVINGAREA_MODE |
| APARTMENTS_MEDI |
| BASEMENTAREA_MEDI |
| YEARS_BEGINEXPLUATATION_MEDI |
| ELEVATORS_MEDI |
| ENTRANCES_MEDI |
| FLOORSMAX_MEDI |
| LANDAREA_MEDI |
| LIVINGAREA_MEDI |
| NONLIVINGAREA_MEDI |
| TOTALAREA_MODE |
| OBS_30_CNT_SOCIAL_CIRCLE |
| DEF_30_CNT_SOCIAL_CIRCLE |
| OBS_60_CNT_SOCIAL_CIRCLE |
| DEF_60_CNT_SOCIAL_CIRCLE |
| DAYS_LAST_PHONE_CHANGE |
| FLAG_DOCUMENT_2 |
| FLAG_DOCUMENT_3 |
| FLAG_DOCUMENT_4 |
| FLAG_DOCUMENT_5 |
| FLAG_DOCUMENT_6 |
| FLAG_DOCUMENT_7 |
| FLAG_DOCUMENT_8 |
| FLAG_DOCUMENT_9 |
| FLAG_DOCUMENT_10 |
| FLAG_DOCUMENT_11 |
| FLAG_DOCUMENT_12 |
| FLAG_DOCUMENT_13 |
| FLAG_DOCUMENT_14 |
| FLAG_DOCUMENT_15 |
| FLAG_DOCUMENT_16 |
| FLAG_DOCUMENT_17 |
| FLAG_DOCUMENT_18 |
| FLAG_DOCUMENT_19 |
| FLAG_DOCUMENT_20 |
| FLAG_DOCUMENT_21 |
| AMT_REQ_CREDIT_BUREAU_HOUR |
| AMT_REQ_CREDIT_BUREAU_DAY |
| AMT_REQ_CREDIT_BUREAU_WEEK |
| AMT_REQ_CREDIT_BUREAU_MON |
| AMT_REQ_CREDIT_BUREAU_QRT |
| AMT_REQ_CREDIT_BUREAU_YEAR |
cat
Index(['NAME_CONTRACT_TYPE', 'CODE_GENDER', 'FLAG_OWN_CAR', 'FLAG_OWN_REALTY',
'NAME_TYPE_SUITE', 'NAME_INCOME_TYPE', 'NAME_EDUCATION_TYPE',
'NAME_FAMILY_STATUS', 'NAME_HOUSING_TYPE', 'OCCUPATION_TYPE',
'WEEKDAY_APPR_PROCESS_START', 'ORGANIZATION_TYPE', 'HOUSETYPE_MODE',
'WALLSMATERIAL_MODE', 'EMERGENCYSTATE_MODE'],
dtype='object')
OneHotEncoder
?Documentation for OneHotEncoder
Parameters
|
sparse_output
sparse_output: bool, default=True When ``True``, it returns a SciPy sparse matrix/array in "Compressed Sparse Row" (CSR) format. .. versionadded:: 1.2 `sparse` was renamed to `sparse_output` |
False | |
|
handle_unknown
handle_unknown: {'error', 'ignore', 'infrequent_if_exist', 'warn'}, default='error' Specifies the way unknown categories are handled during :meth:`transform`. - 'error' : Raise an error if an unknown category is present during transform. - 'ignore' : When an unknown category is encountered during transform, the resulting one-hot encoded columns for this feature will be all zeros. In the inverse transform, an unknown category will be denoted as None. - 'infrequent_if_exist' : When an unknown category is encountered during transform, the resulting one-hot encoded columns for this feature will map to the infrequent category if it exists. The infrequent category will be mapped to the last position in the encoding. During inverse transform, an unknown category will be mapped to the category denoted `'infrequent'` if it exists. If the `'infrequent'` category does not exist, then :meth:`transform` and :meth:`inverse_transform` will handle an unknown category as with `handle_unknown='ignore'`. Infrequent categories exist based on `min_frequency` and `max_categories`. Read more in the :ref:`User Guide <encoder_infrequent_categories>`. - 'warn' : When an unknown category is encountered during transform a warning is issued, and the encoding then proceeds as described for `handle_unknown="infrequent_if_exist"`. .. versionchanged:: 1.1 `'infrequent_if_exist'` was added to automatically handle unknown categories and infrequent categories. .. versionadded:: 1.6 The option `"warn"` was added in 1.6. |
'ignore' | |
|
categories
categories: 'auto' or a list of array-like, default='auto' Categories (unique values) per feature: - 'auto' : Determine categories automatically from the training data. - list : ``categories[i]`` holds the categories expected in the ith column. The passed categories should not mix strings and numeric values within a single feature, and should be sorted in case of numeric values. The used categories can be found in the ``categories_`` attribute. .. versionadded:: 0.20 |
'auto' | |
|
drop
drop: {'first', 'if_binary'} or an array-like of shape (n_features,), default=None Specifies a methodology to use to drop one of the categories per feature. This is useful in situations where perfectly collinear features cause problems, such as when feeding the resulting data into an unregularized linear regression model. However, dropping one category breaks the symmetry of the original representation and can therefore induce a bias in downstream models, for instance for penalized linear classification or regression models. - None : retain all features (the default). - 'first' : drop the first category in each feature. If only one category is present, the feature will be dropped entirely. - 'if_binary' : drop the first category in each feature with two categories. Features with 1 or more than 2 categories are left intact. - array : ``drop[i]`` is the category in feature ``X[:, i]`` that should be dropped. When `max_categories` or `min_frequency` is configured to group infrequent categories, the dropping behavior is handled after the grouping. .. versionadded:: 0.21 The parameter `drop` was added in 0.21. .. versionchanged:: 0.23 The option `drop='if_binary'` was added in 0.23. .. versionchanged:: 1.1 Support for dropping infrequent categories. |
None | |
|
dtype
dtype: number type, default=np.float64 Desired dtype of output. |
<class 'numpy.float64'> | |
|
min_frequency
min_frequency: int or float, default=None Specifies the minimum frequency below which a category will be considered infrequent. - If `int`, categories with a smaller cardinality will be considered infrequent. - If `float`, categories with a smaller cardinality than `min_frequency * n_samples` will be considered infrequent. .. versionadded:: 1.1 Read more in the :ref:`User Guide <encoder_infrequent_categories>`. |
None | |
|
max_categories
max_categories: int, default=None Specifies an upper limit to the number of output features for each input feature when considering infrequent categories. If there are infrequent categories, `max_categories` includes the category representing the infrequent categories along with the frequent categories. If `None`, there is no limit to the number of output features. .. versionadded:: 1.1 Read more in the :ref:`User Guide <encoder_infrequent_categories>`. |
None | |
|
feature_name_combiner
feature_name_combiner: "concat" or callable, default="concat" Callable with signature `def callable(input_feature, category)` that returns a string. This is used to create feature names to be returned by :meth:`get_feature_names_out`. `"concat"` concatenates encoded feature name and category with `feature + "_" + str(category)`.E.g. feature X with values 1, 6, 7 create feature names `X_1, X_6, X_7`. .. versionadded:: 1.3 |
'concat' |
Fitted attributes
| Name | Type | Value |
|---|---|---|
|
categories_
categories_: list of arrays The categories of each feature determined during fitting (in order of the features in X and corresponding with the output of ``transform``). This includes the category specified in ``drop`` (if any). |
list | [array(['Cash ... dtype=object), array(['F', '... dtype=object), array(['N', '... dtype=object), array(['N', '... dtype=object), ...] |
|
drop_idx_
drop_idx_: array of shape (n_features,) - ``drop_idx_[i]`` is the index in ``categories_[i]`` of the category to be dropped for each feature. - ``drop_idx_[i] = None`` if no category is to be dropped from the feature with index ``i``, e.g. when `drop='if_binary'` and the feature isn't binary. - ``drop_idx_ = None`` if all the transformed features will be retained. If infrequent categories are enabled by setting `min_frequency` or `max_categories` to a non-default value and `drop_idx[i]` corresponds to an infrequent category, then the entire infrequent category is dropped. .. versionchanged:: 0.23 Added the possibility to contain `None` values. |
NoneType | None |
|
feature_names_in_
feature_names_in_: ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 |
ndarray[object](15,) | ['NAME_CONTRACT_TYPE','CODE_GENDER','FLAG_OWN_CAR',...,'HOUSETYPE_MODE', 'WALLSMATERIAL_MODE','EMERGENCYSTATE_MODE'] |
|
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 1.0 |
int | 15 |
141 features
| NAME_CONTRACT_TYPE_Cash loans |
| NAME_CONTRACT_TYPE_Revolving loans |
| CODE_GENDER_F |
| CODE_GENDER_M |
| CODE_GENDER_XNA |
| FLAG_OWN_CAR_N |
| FLAG_OWN_CAR_Y |
| FLAG_OWN_REALTY_N |
| FLAG_OWN_REALTY_Y |
| NAME_TYPE_SUITE_Children |
| NAME_TYPE_SUITE_Family |
| NAME_TYPE_SUITE_Group of people |
| NAME_TYPE_SUITE_Missing |
| NAME_TYPE_SUITE_Other_A |
| NAME_TYPE_SUITE_Other_B |
| NAME_TYPE_SUITE_Spouse, partner |
| NAME_TYPE_SUITE_Unaccompanied |
| NAME_INCOME_TYPE_Businessman |
| NAME_INCOME_TYPE_Commercial associate |
| NAME_INCOME_TYPE_Maternity leave |
| NAME_INCOME_TYPE_Pensioner |
| NAME_INCOME_TYPE_State servant |
| NAME_INCOME_TYPE_Student |
| NAME_INCOME_TYPE_Unemployed |
| NAME_INCOME_TYPE_Working |
| NAME_EDUCATION_TYPE_Academic degree |
| NAME_EDUCATION_TYPE_Higher education |
| NAME_EDUCATION_TYPE_Incomplete higher |
| NAME_EDUCATION_TYPE_Lower secondary |
| NAME_EDUCATION_TYPE_Secondary / secondary special |
| NAME_FAMILY_STATUS_Civil marriage |
| NAME_FAMILY_STATUS_Married |
| NAME_FAMILY_STATUS_Separated |
| NAME_FAMILY_STATUS_Single / not married |
| NAME_FAMILY_STATUS_Unknown |
| NAME_FAMILY_STATUS_Widow |
| NAME_HOUSING_TYPE_Co-op apartment |
| NAME_HOUSING_TYPE_House / apartment |
| NAME_HOUSING_TYPE_Municipal apartment |
| NAME_HOUSING_TYPE_Office apartment |
| NAME_HOUSING_TYPE_Rented apartment |
| NAME_HOUSING_TYPE_With parents |
| OCCUPATION_TYPE_Accountants |
| OCCUPATION_TYPE_Cleaning staff |
| OCCUPATION_TYPE_Cooking staff |
| OCCUPATION_TYPE_Core staff |
| OCCUPATION_TYPE_Drivers |
| OCCUPATION_TYPE_HR staff |
| OCCUPATION_TYPE_High skill tech staff |
| OCCUPATION_TYPE_IT staff |
| OCCUPATION_TYPE_Laborers |
| OCCUPATION_TYPE_Low-skill Laborers |
| OCCUPATION_TYPE_Managers |
| OCCUPATION_TYPE_Medicine staff |
| OCCUPATION_TYPE_Missing |
| OCCUPATION_TYPE_Private service staff |
| OCCUPATION_TYPE_Realty agents |
| OCCUPATION_TYPE_Sales staff |
| OCCUPATION_TYPE_Secretaries |
| OCCUPATION_TYPE_Security staff |
| OCCUPATION_TYPE_Waiters/barmen staff |
| WEEKDAY_APPR_PROCESS_START_FRIDAY |
| WEEKDAY_APPR_PROCESS_START_MONDAY |
| WEEKDAY_APPR_PROCESS_START_SATURDAY |
| WEEKDAY_APPR_PROCESS_START_SUNDAY |
| WEEKDAY_APPR_PROCESS_START_THURSDAY |
| WEEKDAY_APPR_PROCESS_START_TUESDAY |
| WEEKDAY_APPR_PROCESS_START_WEDNESDAY |
| ORGANIZATION_TYPE_Advertising |
| ORGANIZATION_TYPE_Agriculture |
| ORGANIZATION_TYPE_Bank |
| ORGANIZATION_TYPE_Business Entity Type 1 |
| ORGANIZATION_TYPE_Business Entity Type 2 |
| ORGANIZATION_TYPE_Business Entity Type 3 |
| ORGANIZATION_TYPE_Cleaning |
| ORGANIZATION_TYPE_Construction |
| ORGANIZATION_TYPE_Culture |
| ORGANIZATION_TYPE_Electricity |
| ORGANIZATION_TYPE_Emergency |
| ORGANIZATION_TYPE_Government |
| ORGANIZATION_TYPE_Hotel |
| ORGANIZATION_TYPE_Housing |
| ORGANIZATION_TYPE_Industry: type 1 |
| ORGANIZATION_TYPE_Industry: type 10 |
| ORGANIZATION_TYPE_Industry: type 11 |
| ORGANIZATION_TYPE_Industry: type 12 |
| ORGANIZATION_TYPE_Industry: type 13 |
| ORGANIZATION_TYPE_Industry: type 2 |
| ORGANIZATION_TYPE_Industry: type 3 |
| ORGANIZATION_TYPE_Industry: type 4 |
| ORGANIZATION_TYPE_Industry: type 5 |
| ORGANIZATION_TYPE_Industry: type 6 |
| ORGANIZATION_TYPE_Industry: type 7 |
| ORGANIZATION_TYPE_Industry: type 8 |
| ORGANIZATION_TYPE_Industry: type 9 |
| ORGANIZATION_TYPE_Insurance |
| ORGANIZATION_TYPE_Kindergarten |
| ORGANIZATION_TYPE_Legal Services |
| ORGANIZATION_TYPE_Medicine |
| ORGANIZATION_TYPE_Military |
| ORGANIZATION_TYPE_Mobile |
| ORGANIZATION_TYPE_Other |
| ORGANIZATION_TYPE_Police |
| ORGANIZATION_TYPE_Postal |
| ORGANIZATION_TYPE_Realtor |
| ORGANIZATION_TYPE_Religion |
| ORGANIZATION_TYPE_Restaurant |
| ORGANIZATION_TYPE_School |
| ORGANIZATION_TYPE_Security |
| ORGANIZATION_TYPE_Security Ministries |
| ORGANIZATION_TYPE_Self-employed |
| ORGANIZATION_TYPE_Services |
| ORGANIZATION_TYPE_Telecom |
| ORGANIZATION_TYPE_Trade: type 1 |
| ORGANIZATION_TYPE_Trade: type 2 |
| ORGANIZATION_TYPE_Trade: type 3 |
| ORGANIZATION_TYPE_Trade: type 4 |
| ORGANIZATION_TYPE_Trade: type 5 |
| ORGANIZATION_TYPE_Trade: type 6 |
| ORGANIZATION_TYPE_Trade: type 7 |
| ORGANIZATION_TYPE_Transport: type 1 |
| ORGANIZATION_TYPE_Transport: type 2 |
| ORGANIZATION_TYPE_Transport: type 3 |
| ORGANIZATION_TYPE_Transport: type 4 |
| ORGANIZATION_TYPE_University |
| ORGANIZATION_TYPE_XNA |
| HOUSETYPE_MODE_Missing |
| HOUSETYPE_MODE_block of flats |
| HOUSETYPE_MODE_specific housing |
| HOUSETYPE_MODE_terraced house |
| WALLSMATERIAL_MODE_Block |
| WALLSMATERIAL_MODE_Missing |
| WALLSMATERIAL_MODE_Mixed |
| WALLSMATERIAL_MODE_Monolithic |
| WALLSMATERIAL_MODE_Others |
| WALLSMATERIAL_MODE_Panel |
| WALLSMATERIAL_MODE_Stone, brick |
| WALLSMATERIAL_MODE_Wooden |
| EMERGENCYSTATE_MODE_Missing |
| EMERGENCYSTATE_MODE_No |
| EMERGENCYSTATE_MODE_Yes |
229 features
| num__CNT_CHILDREN |
| num__AMT_INCOME_TOTAL |
| num__AMT_CREDIT |
| num__AMT_ANNUITY |
| num__AMT_GOODS_PRICE |
| num__REGION_POPULATION_RELATIVE |
| num__DAYS_BIRTH |
| num__DAYS_EMPLOYED |
| num__DAYS_REGISTRATION |
| num__DAYS_ID_PUBLISH |
| num__FLAG_MOBIL |
| num__FLAG_EMP_PHONE |
| num__FLAG_WORK_PHONE |
| num__FLAG_CONT_MOBILE |
| num__FLAG_PHONE |
| num__FLAG_EMAIL |
| num__CNT_FAM_MEMBERS |
| num__REGION_RATING_CLIENT |
| num__REGION_RATING_CLIENT_W_CITY |
| num__HOUR_APPR_PROCESS_START |
| num__REG_REGION_NOT_LIVE_REGION |
| num__REG_REGION_NOT_WORK_REGION |
| num__LIVE_REGION_NOT_WORK_REGION |
| num__REG_CITY_NOT_LIVE_CITY |
| num__REG_CITY_NOT_WORK_CITY |
| num__LIVE_CITY_NOT_WORK_CITY |
| num__EXT_SOURCE_1 |
| num__EXT_SOURCE_2 |
| num__EXT_SOURCE_3 |
| num__APARTMENTS_AVG |
| num__BASEMENTAREA_AVG |
| num__YEARS_BEGINEXPLUATATION_AVG |
| num__ELEVATORS_AVG |
| num__ENTRANCES_AVG |
| num__FLOORSMAX_AVG |
| num__LANDAREA_AVG |
| num__LIVINGAREA_AVG |
| num__NONLIVINGAREA_AVG |
| num__APARTMENTS_MODE |
| num__BASEMENTAREA_MODE |
| num__YEARS_BEGINEXPLUATATION_MODE |
| num__ELEVATORS_MODE |
| num__ENTRANCES_MODE |
| num__FLOORSMAX_MODE |
| num__LANDAREA_MODE |
| num__LIVINGAREA_MODE |
| num__NONLIVINGAREA_MODE |
| num__APARTMENTS_MEDI |
| num__BASEMENTAREA_MEDI |
| num__YEARS_BEGINEXPLUATATION_MEDI |
| num__ELEVATORS_MEDI |
| num__ENTRANCES_MEDI |
| num__FLOORSMAX_MEDI |
| num__LANDAREA_MEDI |
| num__LIVINGAREA_MEDI |
| num__NONLIVINGAREA_MEDI |
| num__TOTALAREA_MODE |
| num__OBS_30_CNT_SOCIAL_CIRCLE |
| num__DEF_30_CNT_SOCIAL_CIRCLE |
| num__OBS_60_CNT_SOCIAL_CIRCLE |
| num__DEF_60_CNT_SOCIAL_CIRCLE |
| num__DAYS_LAST_PHONE_CHANGE |
| num__FLAG_DOCUMENT_2 |
| num__FLAG_DOCUMENT_3 |
| num__FLAG_DOCUMENT_4 |
| num__FLAG_DOCUMENT_5 |
| num__FLAG_DOCUMENT_6 |
| num__FLAG_DOCUMENT_7 |
| num__FLAG_DOCUMENT_8 |
| num__FLAG_DOCUMENT_9 |
| num__FLAG_DOCUMENT_10 |
| num__FLAG_DOCUMENT_11 |
| num__FLAG_DOCUMENT_12 |
| num__FLAG_DOCUMENT_13 |
| num__FLAG_DOCUMENT_14 |
| num__FLAG_DOCUMENT_15 |
| num__FLAG_DOCUMENT_16 |
| num__FLAG_DOCUMENT_17 |
| num__FLAG_DOCUMENT_18 |
| num__FLAG_DOCUMENT_19 |
| num__FLAG_DOCUMENT_20 |
| num__FLAG_DOCUMENT_21 |
| num__AMT_REQ_CREDIT_BUREAU_HOUR |
| num__AMT_REQ_CREDIT_BUREAU_DAY |
| num__AMT_REQ_CREDIT_BUREAU_WEEK |
| num__AMT_REQ_CREDIT_BUREAU_MON |
| num__AMT_REQ_CREDIT_BUREAU_QRT |
| num__AMT_REQ_CREDIT_BUREAU_YEAR |
| cat__NAME_CONTRACT_TYPE_Cash loans |
| cat__NAME_CONTRACT_TYPE_Revolving loans |
| cat__CODE_GENDER_F |
| cat__CODE_GENDER_M |
| cat__CODE_GENDER_XNA |
| cat__FLAG_OWN_CAR_N |
| cat__FLAG_OWN_CAR_Y |
| cat__FLAG_OWN_REALTY_N |
| cat__FLAG_OWN_REALTY_Y |
| cat__NAME_TYPE_SUITE_Children |
| cat__NAME_TYPE_SUITE_Family |
| cat__NAME_TYPE_SUITE_Group of people |
| cat__NAME_TYPE_SUITE_Missing |
| cat__NAME_TYPE_SUITE_Other_A |
| cat__NAME_TYPE_SUITE_Other_B |
| cat__NAME_TYPE_SUITE_Spouse, partner |
| cat__NAME_TYPE_SUITE_Unaccompanied |
| cat__NAME_INCOME_TYPE_Businessman |
| cat__NAME_INCOME_TYPE_Commercial associate |
| cat__NAME_INCOME_TYPE_Maternity leave |
| cat__NAME_INCOME_TYPE_Pensioner |
| cat__NAME_INCOME_TYPE_State servant |
| cat__NAME_INCOME_TYPE_Student |
| cat__NAME_INCOME_TYPE_Unemployed |
| cat__NAME_INCOME_TYPE_Working |
| cat__NAME_EDUCATION_TYPE_Academic degree |
| cat__NAME_EDUCATION_TYPE_Higher education |
| cat__NAME_EDUCATION_TYPE_Incomplete higher |
| cat__NAME_EDUCATION_TYPE_Lower secondary |
| cat__NAME_EDUCATION_TYPE_Secondary / secondary special |
| cat__NAME_FAMILY_STATUS_Civil marriage |
| cat__NAME_FAMILY_STATUS_Married |
| cat__NAME_FAMILY_STATUS_Separated |
| cat__NAME_FAMILY_STATUS_Single / not married |
| cat__NAME_FAMILY_STATUS_Unknown |
| cat__NAME_FAMILY_STATUS_Widow |
| cat__NAME_HOUSING_TYPE_Co-op apartment |
| cat__NAME_HOUSING_TYPE_House / apartment |
| cat__NAME_HOUSING_TYPE_Municipal apartment |
| cat__NAME_HOUSING_TYPE_Office apartment |
| cat__NAME_HOUSING_TYPE_Rented apartment |
| cat__NAME_HOUSING_TYPE_With parents |
| cat__OCCUPATION_TYPE_Accountants |
| cat__OCCUPATION_TYPE_Cleaning staff |
| cat__OCCUPATION_TYPE_Cooking staff |
| cat__OCCUPATION_TYPE_Core staff |
| cat__OCCUPATION_TYPE_Drivers |
| cat__OCCUPATION_TYPE_HR staff |
| cat__OCCUPATION_TYPE_High skill tech staff |
| cat__OCCUPATION_TYPE_IT staff |
| cat__OCCUPATION_TYPE_Laborers |
| cat__OCCUPATION_TYPE_Low-skill Laborers |
| cat__OCCUPATION_TYPE_Managers |
| cat__OCCUPATION_TYPE_Medicine staff |
| cat__OCCUPATION_TYPE_Missing |
| cat__OCCUPATION_TYPE_Private service staff |
| cat__OCCUPATION_TYPE_Realty agents |
| cat__OCCUPATION_TYPE_Sales staff |
| cat__OCCUPATION_TYPE_Secretaries |
| cat__OCCUPATION_TYPE_Security staff |
| cat__OCCUPATION_TYPE_Waiters/barmen staff |
| cat__WEEKDAY_APPR_PROCESS_START_FRIDAY |
| cat__WEEKDAY_APPR_PROCESS_START_MONDAY |
| cat__WEEKDAY_APPR_PROCESS_START_SATURDAY |
| cat__WEEKDAY_APPR_PROCESS_START_SUNDAY |
| cat__WEEKDAY_APPR_PROCESS_START_THURSDAY |
| cat__WEEKDAY_APPR_PROCESS_START_TUESDAY |
| cat__WEEKDAY_APPR_PROCESS_START_WEDNESDAY |
| cat__ORGANIZATION_TYPE_Advertising |
| cat__ORGANIZATION_TYPE_Agriculture |
| cat__ORGANIZATION_TYPE_Bank |
| cat__ORGANIZATION_TYPE_Business Entity Type 1 |
| cat__ORGANIZATION_TYPE_Business Entity Type 2 |
| cat__ORGANIZATION_TYPE_Business Entity Type 3 |
| cat__ORGANIZATION_TYPE_Cleaning |
| cat__ORGANIZATION_TYPE_Construction |
| cat__ORGANIZATION_TYPE_Culture |
| cat__ORGANIZATION_TYPE_Electricity |
| cat__ORGANIZATION_TYPE_Emergency |
| cat__ORGANIZATION_TYPE_Government |
| cat__ORGANIZATION_TYPE_Hotel |
| cat__ORGANIZATION_TYPE_Housing |
| cat__ORGANIZATION_TYPE_Industry: type 1 |
| cat__ORGANIZATION_TYPE_Industry: type 10 |
| cat__ORGANIZATION_TYPE_Industry: type 11 |
| cat__ORGANIZATION_TYPE_Industry: type 12 |
| cat__ORGANIZATION_TYPE_Industry: type 13 |
| cat__ORGANIZATION_TYPE_Industry: type 2 |
| cat__ORGANIZATION_TYPE_Industry: type 3 |
| cat__ORGANIZATION_TYPE_Industry: type 4 |
| cat__ORGANIZATION_TYPE_Industry: type 5 |
| cat__ORGANIZATION_TYPE_Industry: type 6 |
| cat__ORGANIZATION_TYPE_Industry: type 7 |
| cat__ORGANIZATION_TYPE_Industry: type 8 |
| cat__ORGANIZATION_TYPE_Industry: type 9 |
| cat__ORGANIZATION_TYPE_Insurance |
| cat__ORGANIZATION_TYPE_Kindergarten |
| cat__ORGANIZATION_TYPE_Legal Services |
| cat__ORGANIZATION_TYPE_Medicine |
| cat__ORGANIZATION_TYPE_Military |
| cat__ORGANIZATION_TYPE_Mobile |
| cat__ORGANIZATION_TYPE_Other |
| cat__ORGANIZATION_TYPE_Police |
| cat__ORGANIZATION_TYPE_Postal |
| cat__ORGANIZATION_TYPE_Realtor |
| cat__ORGANIZATION_TYPE_Religion |
| cat__ORGANIZATION_TYPE_Restaurant |
| cat__ORGANIZATION_TYPE_School |
| cat__ORGANIZATION_TYPE_Security |
| cat__ORGANIZATION_TYPE_Security Ministries |
| cat__ORGANIZATION_TYPE_Self-employed |
| cat__ORGANIZATION_TYPE_Services |
| cat__ORGANIZATION_TYPE_Telecom |
| cat__ORGANIZATION_TYPE_Trade: type 1 |
| cat__ORGANIZATION_TYPE_Trade: type 2 |
| cat__ORGANIZATION_TYPE_Trade: type 3 |
| cat__ORGANIZATION_TYPE_Trade: type 4 |
| cat__ORGANIZATION_TYPE_Trade: type 5 |
| cat__ORGANIZATION_TYPE_Trade: type 6 |
| cat__ORGANIZATION_TYPE_Trade: type 7 |
| cat__ORGANIZATION_TYPE_Transport: type 1 |
| cat__ORGANIZATION_TYPE_Transport: type 2 |
| cat__ORGANIZATION_TYPE_Transport: type 3 |
| cat__ORGANIZATION_TYPE_Transport: type 4 |
| cat__ORGANIZATION_TYPE_University |
| cat__ORGANIZATION_TYPE_XNA |
| cat__HOUSETYPE_MODE_Missing |
| cat__HOUSETYPE_MODE_block of flats |
| cat__HOUSETYPE_MODE_specific housing |
| cat__HOUSETYPE_MODE_terraced house |
| cat__WALLSMATERIAL_MODE_Block |
| cat__WALLSMATERIAL_MODE_Missing |
| cat__WALLSMATERIAL_MODE_Mixed |
| cat__WALLSMATERIAL_MODE_Monolithic |
| cat__WALLSMATERIAL_MODE_Others |
| cat__WALLSMATERIAL_MODE_Panel |
| cat__WALLSMATERIAL_MODE_Stone, brick |
| cat__WALLSMATERIAL_MODE_Wooden |
| cat__EMERGENCYSTATE_MODE_Missing |
| cat__EMERGENCYSTATE_MODE_No |
| cat__EMERGENCYSTATE_MODE_Yes |
HistGradientBoostingClassifier
?Documentation for HistGradientBoostingClassifier
Parameters
|
learning_rate
learning_rate: float, default=0.1 The learning rate, also known as *shrinkage*. This is used as a multiplicative factor for the leaves values. Use ``1`` for no shrinkage. |
0.05 | |
|
max_iter
max_iter: int, default=100 The maximum number of iterations of the boosting process, i.e. the maximum number of trees for binary classification. For multiclass classification, `n_classes` trees per iteration are built. |
200 | |
|
l2_regularization
l2_regularization: float, default=0 The L2 regularization parameter penalizing leaves with small hessians. Use ``0`` for no regularization (default). |
1.0 | |
|
random_state
random_state: int, RandomState instance or None, default=None Pseudo-random number generator to control the subsampling in the binning process, and the train/validation data split if early stopping is enabled. Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`. |
42 | |
|
loss
loss: {'log_loss'}, default='log_loss' The loss function to use in the boosting process. For binary classification problems, 'log_loss' is also known as logistic loss, binomial deviance or binary crossentropy. Internally, the model fits one tree per boosting iteration and uses the logistic sigmoid function (expit) as inverse link function to compute the predicted positive class probability. For multiclass classification problems, 'log_loss' is also known as multinomial deviance or categorical crossentropy. Internally, the model fits one tree per boosting iteration and per class and uses the softmax function as inverse link function to compute the predicted probabilities of the classes. |
'log_loss' | |
|
max_leaf_nodes
max_leaf_nodes: int or None, default=31 The maximum number of leaves for each tree. Must be strictly greater than 1. If None, there is no maximum limit. |
31 | |
|
max_depth
max_depth: int or None, default=None The maximum depth of each tree. The depth of a tree is the number of edges to go from the root to the deepest leaf. Depth isn't constrained by default. |
None | |
|
min_samples_leaf
min_samples_leaf: int, default=20 The minimum number of samples per leaf. For small datasets with less than a few hundred samples, it is recommended to lower this value since only very shallow trees would be built. |
20 | |
|
max_features
max_features: float, default=1.0 Proportion of randomly chosen features in each and every node split. This is a form of regularization, smaller values make the trees weaker learners and might prevent overfitting. If interaction constraints from `interaction_cst` are present, only allowed features are taken into account for the subsampling. .. versionadded:: 1.4 |
1.0 | |
|
max_bins
max_bins: int, default=255 The maximum number of bins to use for non-missing values. Before training, each feature of the input array `X` is binned into integer-valued bins, which allows for a much faster training stage. Features with a small number of unique values may use less than ``max_bins`` bins. In addition to the ``max_bins`` bins, one more bin is always reserved for missing values. Must be no larger than 255. |
255 | |
|
categorical_features
categorical_features: array-like of {bool, int, str} of shape (n_features) or shape (n_categorical_features,), default='from_dtype' Indicates the categorical features. - None : no feature will be considered categorical. - boolean array-like : boolean mask indicating categorical features. - integer array-like : integer indices indicating categorical features. - str array-like: names of categorical features (assuming the training data has feature names). - `"from_dtype"`: dataframe columns with dtype "Categorical" and "Enum" are considered to be categorical features. The input must be a dataframe that is supported by narwhals (or supports it): :func:`narwhals.from_native` must work. This is the case, for instance, for pandas and polars DataFrames. For each categorical feature, there must be at most `max_bins` unique categories. Negative values for categorical features encoded as numeric dtypes are treated as missing values. All categorical values are converted to floating point numbers. This means that categorical values of 1.0 and 1 are treated as the same category. Read more in the :ref:`User Guide <categorical_support_gbdt>`. .. versionadded:: 0.24 .. versionchanged:: 1.2 Added support for feature names. .. versionchanged:: 1.4 Added `"from_dtype"` option. .. versionchanged:: 1.6 The default value changed from `None` to `"from_dtype"`. |
'from_dtype' | |
|
monotonic_cst
monotonic_cst: array-like of int of shape (n_features) or dict, default=None Monotonic constraint to enforce on each feature are specified using the following integer values: - 1: monotonic increase - 0: no constraint - -1: monotonic decrease If a dict with str keys, map feature to monotonic constraints by name. If an array, the features are mapped to constraints by position. See :ref:`monotonic_cst_features_names` for a usage example. The constraints are only valid for binary classifications and hold over the probability of the positive class. Read more in the :ref:`User Guide <monotonic_cst_gbdt>`. .. versionadded:: 0.23 .. versionchanged:: 1.2 Accept dict of constraints with feature names as keys. |
None | |
|
interaction_cst
interaction_cst: {"pairwise", "no_interactions"} or sequence of lists/tuples/sets of int, default=None Specify interaction constraints, the sets of features which can interact with each other in child node splits. Each item specifies the set of feature indices that are allowed to interact with each other. If there are more features than specified in these constraints, they are treated as if they were specified as an additional set. The strings "pairwise" and "no_interactions" are shorthands for allowing only pairwise or no interactions, respectively. For instance, with 5 features in total, `interaction_cst=[{0, 1}]` is equivalent to `interaction_cst=[{0, 1}, {2, 3, 4}]`, and specifies that each branch of a tree will either only split on features 0 and 1 or only split on features 2, 3 and 4. See :ref:`this example<ice-vs-pdp>` on how to use `interaction_cst`. .. versionadded:: 1.2 |
None | |
|
warm_start
warm_start: bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble. For results to be valid, the estimator should be re-trained on the same data only. See :term:`the Glossary <warm_start>`. |
False | |
|
early_stopping
early_stopping: 'auto' or bool, default='auto' If 'auto', early stopping is enabled if the sample size is larger than 10000 or if `X_val` and `y_val` are passed to `fit`. If True, early stopping is enabled, otherwise early stopping is disabled. .. versionadded:: 0.23 |
'auto' | |
|
scoring
scoring: str or callable or None, default='loss' Scoring method to use for early stopping. Only used if `early_stopping` is enabled. Options: - str: see :ref:`scoring_string_names` for options. - callable: a scorer callable object (e.g., function) with signature ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. - `None`: :ref:`accuracy <accuracy_score>` is used. - 'loss': early stopping is checked w.r.t the loss value. |
'loss' | |
|
validation_fraction
validation_fraction: int or float or None, default=0.1 Proportion (or absolute size) of training data to set aside as validation data for early stopping. If None, early stopping is done on the training data. The value is ignored if either early stopping is not performed, e.g. `early_stopping=False`, or if `X_val` and `y_val` are passed to fit. |
0.1 | |
|
n_iter_no_change
n_iter_no_change: int, default=10 Used to determine when to "early stop". The fitting process is stopped when none of the last ``n_iter_no_change`` scores are better than the ``n_iter_no_change - 1`` -th-to-last one, up to some tolerance. Only used if early stopping is performed. |
10 | |
|
tol
tol: float, default=1e-7 The absolute tolerance to use when comparing scores. The higher the tolerance, the more likely we are to early stop: higher tolerance means that it will be harder for subsequent iterations to be considered an improvement upon the reference score. |
1e-07 | |
|
verbose
verbose: int, default=0 The verbosity level. If not zero, print some information about the fitting process. ``1`` prints only summary info, ``2`` prints info per iteration. |
0 | |
|
class_weight
class_weight: dict or 'balanced', default=None Weights associated with classes in the form `{class_label: weight}`. If not given, all classes are supposed to have weight one. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as `n_samples / (n_classes * np.bincount(y))`. Note that these weights will be multiplied with sample_weight (passed through the fit method) if `sample_weight` is specified. .. versionadded:: 1.2 |
None |
Fitted attributes
| Name | Type | Value |
|---|---|---|
|
classes_
classes_: array, shape = (n_classes,) Class labels. |
ndarray[int64](2,) | [0,1] |
|
do_early_stopping_
do_early_stopping_: bool Indicates whether early stopping is used during training. |
bool | True |
|
is_categorical_
is_categorical_: ndarray, shape (n_features, ) or None Boolean mask for the categorical features. ``None`` if there are no categorical features. |
NoneType | None |
|
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 0.24 |
int | 229 |
|
n_iter_
n_iter_: int The number of iterations as selected by early stopping, depending on the `early_stopping` parameter. Otherwise it corresponds to max_iter. |
int | 200 |
|
n_trees_per_iteration_
n_trees_per_iteration_: int The number of tree that are built at each iteration. This is equal to 1 for binary classification, and to ``n_classes`` for multiclass classification. |
int | 1 |
|
train_score_
train_score_: ndarray, shape (n_iter_+1,) The scores at each iteration on the training data. The first entry is the score of the ensemble before the first iteration. Scores are computed according to the ``scoring`` parameter. If ``scoring`` is not 'loss', scores are computed on a subset of at most 10 000 samples. Empty if no early stopping. |
ndarray[float64](201,) | [-0.28,-0.28,-0.28,...,-0.24,-0.24,-0.24] |
|
validation_score_
validation_score_: ndarray, shape (n_iter_+1,) The scores at each iteration on the held-out validation data. The first entry is the score of the ensemble before the first iteration. Scores are computed according to the ``scoring`` parameter. Empty if no early stopping or if ``validation_fraction`` is None. |
ndarray[float64](201,) | [-0.28,-0.28,-0.28,...,-0.25,-0.25,-0.25] |
In [83]
final_pipeline.fit(X_train, y_train)Pipeline(steps=[('preprocessor',
ColumnTransformer(transformers=[('num', 'passthrough',
Index(['CNT_CHILDREN', 'AMT_INCOME_TOTAL', 'AMT_CREDIT', 'AMT_ANNUITY',
'AMT_GOODS_PRICE', 'REGION_POPULATION_RELATIVE', 'DAYS_BIRTH',
'DAYS_EMPLOYED', 'DAYS_REGISTRATION', 'DAYS_ID_PUBLISH', 'FLAG_MOBIL',
'FLAG_EMP_PHONE', 'FLAG_WORK_PHONE', 'FLAG_CONT_MOBILE', 'FLAG_PHONE',
'FL...
'NAME_TYPE_SUITE', 'NAME_INCOME_TYPE', 'NAME_EDUCATION_TYPE',
'NAME_FAMILY_STATUS', 'NAME_HOUSING_TYPE', 'OCCUPATION_TYPE',
'WEEKDAY_APPR_PROCESS_START', 'ORGANIZATION_TYPE', 'HOUSETYPE_MODE',
'WALLSMATERIAL_MODE', 'EMERGENCYSTATE_MODE'],
dtype='object'))])),
('model',
HistGradientBoostingClassifier(l2_regularization=1.0,
learning_rate=0.05,
max_iter=200,
random_state=42))])In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Pipeline
?Documentation for PipelineiFitted
Parameters
|
steps
steps: list of tuples List of (name of step, estimator) tuples that are to be chained in sequential order. To be compatible with the scikit-learn API, all steps must define `fit`. All non-last steps must also define `transform`. See :ref:`Combining Estimators <combining_estimators>` for more details. |
[('preprocessor', ...), ('model', ...)] | |
|
transform_input
transform_input: list of str, default=None The names of the :term:`metadata` parameters that should be transformed by the pipeline before passing it to the step consuming it. This enables transforming some input arguments to ``fit`` (other than ``X``) to be transformed by the steps of the pipeline up to the step which requires them. Requirement is defined via :ref:`metadata routing <metadata_routing>`. For instance, this can be used to pass a validation set through the pipeline. You can only set this if metadata routing is enabled, which you can enable using ``sklearn.set_config(enable_metadata_routing=True)``. .. versionadded:: 1.6 |
None | |
|
memory
memory: str or object with the joblib.Memory interface, default=None Used to cache the fitted transformers of the pipeline. The last step will never be cached, even if it is a transformer. By default, no caching is performed. If a string is given, it is the path to the caching directory. Enabling caching triggers a clone of the transformers before fitting. Therefore, the transformer instance given to the pipeline cannot be inspected directly. Use the attribute ``named_steps`` or ``steps`` to inspect estimators within the pipeline. Caching the transformers is advantageous when fitting is time consuming. See :ref:`sphx_glr_auto_examples_neighbors_plot_caching_nearest_neighbors.py` for an example on how to enable caching. |
None | |
|
verbose
verbose: bool, default=False If True, the time elapsed while fitting each step will be printed as it is completed. |
False |
Fitted attributes
| Name | Type | Value |
|---|---|---|
|
classes_
classes_: ndarray of shape (n_classes,) The classes labels. Only exist if the last step of the pipeline is a classifier. |
ndarray[int64](2,) | [0,1] |
|
feature_names_in_
feature_names_in_: ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Only defined if the underlying estimator exposes such an attribute when fit. .. versionadded:: 1.0 |
ndarray[object](103,) | ['NAME_CONTRACT_TYPE','CODE_GENDER','FLAG_OWN_CAR',..., 'AMT_REQ_CREDIT_BUREAU_MON','AMT_REQ_CREDIT_BUREAU_QRT', 'AMT_REQ_CREDIT_BUREAU_YEAR'] |
|
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. Only defined if the underlying first estimator in `steps` exposes such an attribute when fit. .. versionadded:: 0.24 |
int | 103 |
preprocessor: ColumnTransformer
?Documentation for preprocessor: ColumnTransformer
Parameters
|
transformers
transformers: list of tuples List of (name, transformer, columns) tuples specifying the transformer objects to be applied to subsets of the data. name : str Like in Pipeline and FeatureUnion, this allows the transformer and its parameters to be set using ``set_params`` and searched in grid search. transformer : {'drop', 'passthrough'} or estimator Estimator must support :term:`fit` and :term:`transform`. Special-cased strings 'drop' and 'passthrough' are accepted as well, to indicate to drop the columns or to pass them through untransformed, respectively. columns : str, array-like of str, int, array-like of int, array-like of bool, slice or callable Indexes the data on its second axis. Integers are interpreted as positional columns, while strings can reference DataFrame columns by name. A scalar string or int should be used where ``transformer`` expects X to be a 1d array-like (vector), otherwise a 2d array will be passed to the transformer. A callable is passed the input data `X` and can return any of the above. To select multiple columns by name or dtype, you can use :obj:`make_column_selector`. |
[('num', ...), ('cat', ...)] | |
|
remainder
remainder: {'drop', 'passthrough'} or estimator, default='drop' By default, only the specified columns in `transformers` are transformed and combined in the output, and the non-specified columns are dropped. (default of ``'drop'``). By specifying ``remainder='passthrough'``, all remaining columns that were not specified in `transformers`, but present in the data passed to `fit` will be automatically passed through. This subset of columns is concatenated with the output of the transformers. For dataframes, extra columns not seen during `fit` will be excluded from the output of `transform`. By setting ``remainder`` to be an estimator, the remaining non-specified columns will use the ``remainder`` estimator. The estimator must support :term:`fit` and :term:`transform`. Note that using this feature requires that the DataFrame columns input at :term:`fit` and :term:`transform` have identical order. |
'drop' | |
|
sparse_threshold
sparse_threshold: float, default=0.3 If the output of the different transformers contains sparse matrices, these will be stacked as a sparse matrix if the overall density is lower than this value. Use ``sparse_threshold=0`` to always return dense. When the transformed output consists of all dense data, the stacked result will be dense, and this keyword will be ignored. |
0.3 | |
|
n_jobs
n_jobs: int, default=None Number of jobs to run in parallel. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. |
None | |
|
transformer_weights
transformer_weights: dict, default=None Multiplicative weights for features per transformer. The output of the transformer is multiplied by these weights. Keys are transformer names, values the weights. |
None | |
|
verbose
verbose: bool, default=False If True, the time elapsed while fitting each transformer will be printed as it is completed. |
False | |
|
verbose_feature_names_out
verbose_feature_names_out: bool, str or Callable[[str, str], str], default=True - If True, :meth:`ColumnTransformer.get_feature_names_out` will prefix all feature names with the name of the transformer that generated that feature. It is equivalent to setting `verbose_feature_names_out="{transformer_name}__{feature_name}"`. - If False, :meth:`ColumnTransformer.get_feature_names_out` will not prefix any feature names and will error if feature names are not unique. - If ``Callable[[str, str], str]``, :meth:`ColumnTransformer.get_feature_names_out` will rename all the features using the name of the transformer. The first argument of the callable is the transformer name and the second argument is the feature name. The returned string will be the new feature name. - If ``str``, it must be a string ready for formatting. The given string will be formatted using two field names: ``transformer_name`` and ``feature_name``. e.g. ``"{feature_name}__{transformer_name}"``. See :meth:`str.format` method from the standard library for more info. .. versionadded:: 1.0 .. versionchanged:: 1.6 `verbose_feature_names_out` can be a callable or a string to be formatted. |
True |
Fitted attributes
| Name | Type | Value |
|---|---|---|
|
feature_names_in_
feature_names_in_: ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 |
ndarray[object](103,) | ['NAME_CONTRACT_TYPE','CODE_GENDER','FLAG_OWN_CAR',..., 'AMT_REQ_CREDIT_BUREAU_MON','AMT_REQ_CREDIT_BUREAU_QRT', 'AMT_REQ_CREDIT_BUREAU_YEAR'] |
|
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. Only defined if the underlying transformers expose such an attribute when fit. .. versionadded:: 0.24 |
int | 103 |
|
named_transformers_
named_transformers_: :class:`~sklearn.utils.Bunch` Read-only attribute to access any transformer by given name. Keys are transformer names and values are the fitted transformer objects. |
Bunch | {'num': Funct...output=False)} |
|
output_indices_
output_indices_: dict A dictionary from each transformer name to a slice, where the slice corresponds to indices in the transformed output. This is useful to inspect which transformer is responsible for which transformed feature(s). .. versionadded:: 1.0 |
dict | {'cat': slice(88, 229, None), 'num': slice(0, 88, None), 're...er': slice(0, 0, None)} |
|
sparse_output_
sparse_output_: bool Boolean flag indicating whether the output of ``transform`` is a sparse matrix or a dense numpy array, which depends on the output of the individual transformers and the `sparse_threshold` keyword. |
bool | False |
|
transformers_
transformers_: list The collection of fitted transformers as tuples of (name, fitted_transformer, column). `fitted_transformer` can be an estimator, or `'drop'`; `'passthrough'` is replaced with an equivalent :class:`~sklearn.preprocessing.FunctionTransformer`. In case there were no columns selected, this will be the unfitted transformer. If there are remaining columns, the final element is a tuple of the form: ('remainder', transformer, remaining_columns) corresponding to the ``remainder`` parameter. If there are remaining columns, then ``len(transformers_)==len(transformers)+1``, otherwise ``len(transformers_)==len(transformers)``. .. versionadded:: 1.7 The format of the remaining columns now attempts to match that of the other transformers: if all columns were provided as column names (`str`), the remaining columns are stored as column names; if all columns were provided as mask arrays (`bool`), so are the remaining columns; in all other cases the remaining columns are stored as indices (`int`). |
list | [('num', FunctionTrans...='one-to-one'), Index(['CNT_C...type='object')), ('cat', OneHotEncoder..._output=False), Index(['NAME_...type='object'))] |
num
Index(['CNT_CHILDREN', 'AMT_INCOME_TOTAL', 'AMT_CREDIT', 'AMT_ANNUITY',
'AMT_GOODS_PRICE', 'REGION_POPULATION_RELATIVE', 'DAYS_BIRTH',
'DAYS_EMPLOYED', 'DAYS_REGISTRATION', 'DAYS_ID_PUBLISH', 'FLAG_MOBIL',
'FLAG_EMP_PHONE', 'FLAG_WORK_PHONE', 'FLAG_CONT_MOBILE', 'FLAG_PHONE',
'FLAG_EMAIL', 'CNT_FAM_MEMBERS', 'REGION_RATING_CLIENT',
'REGION_RATING_CLIENT_W_CITY', 'HOUR_APPR_PROCESS_START',
'REG_REGION_NOT_LIVE_REGION', 'REG_REGION_NOT_WORK_REGION',
'LIVE_REGION_NOT_WORK_REGION', 'REG_CITY_NOT_LIVE_CITY',
'REG_CITY_NOT_WORK_CITY', 'LIVE_CITY_NOT_WORK_CITY', 'EXT_SOURCE_1',
'EXT_SOURCE_2', 'EXT_SOURCE_3', 'APARTMENTS_AVG', 'BASEMENTAREA_AVG',
'YEARS_BEGINEXPLUATATION_AVG', 'ELEVATORS_AVG', 'ENTRANCES_AVG',
'FLOORSMAX_AVG', 'LANDAREA_AVG', 'LIVINGAREA_AVG', 'NONLIVINGAREA_AVG',
'APARTMENTS_MODE', 'BASEMENTAREA_MODE', 'YEARS_BEGINEXPLUATATION_MODE',
'ELEVATORS_MODE', 'ENTRANCES_MODE', 'FLOORSMAX_MODE', 'LANDAREA_MODE',
'LIVINGAREA_MODE', 'NONLIVINGAREA_MODE', 'APARTMENTS_MEDI',
'BASEMENTAREA_MEDI', 'YEARS_BEGINEXPLUATATION_MEDI', 'ELEVATORS_MEDI',
'ENTRANCES_MEDI', 'FLOORSMAX_MEDI', 'LANDAREA_MEDI', 'LIVINGAREA_MEDI',
'NONLIVINGAREA_MEDI', 'TOTALAREA_MODE', 'OBS_30_CNT_SOCIAL_CIRCLE',
'DEF_30_CNT_SOCIAL_CIRCLE', 'OBS_60_CNT_SOCIAL_CIRCLE',
'DEF_60_CNT_SOCIAL_CIRCLE', 'DAYS_LAST_PHONE_CHANGE', 'FLAG_DOCUMENT_2',
'FLAG_DOCUMENT_3', 'FLAG_DOCUMENT_4', 'FLAG_DOCUMENT_5',
'FLAG_DOCUMENT_6', 'FLAG_DOCUMENT_7', 'FLAG_DOCUMENT_8',
'FLAG_DOCUMENT_9', 'FLAG_DOCUMENT_10', 'FLAG_DOCUMENT_11',
'FLAG_DOCUMENT_12', 'FLAG_DOCUMENT_13', 'FLAG_DOCUMENT_14',
'FLAG_DOCUMENT_15', 'FLAG_DOCUMENT_16', 'FLAG_DOCUMENT_17',
'FLAG_DOCUMENT_18', 'FLAG_DOCUMENT_19', 'FLAG_DOCUMENT_20',
'FLAG_DOCUMENT_21', 'AMT_REQ_CREDIT_BUREAU_HOUR',
'AMT_REQ_CREDIT_BUREAU_DAY', 'AMT_REQ_CREDIT_BUREAU_WEEK',
'AMT_REQ_CREDIT_BUREAU_MON', 'AMT_REQ_CREDIT_BUREAU_QRT',
'AMT_REQ_CREDIT_BUREAU_YEAR'],
dtype='object')
passthrough
?Documentation for FunctionTransformer
88 features
| CNT_CHILDREN |
| AMT_INCOME_TOTAL |
| AMT_CREDIT |
| AMT_ANNUITY |
| AMT_GOODS_PRICE |
| REGION_POPULATION_RELATIVE |
| DAYS_BIRTH |
| DAYS_EMPLOYED |
| DAYS_REGISTRATION |
| DAYS_ID_PUBLISH |
| FLAG_MOBIL |
| FLAG_EMP_PHONE |
| FLAG_WORK_PHONE |
| FLAG_CONT_MOBILE |
| FLAG_PHONE |
| FLAG_EMAIL |
| CNT_FAM_MEMBERS |
| REGION_RATING_CLIENT |
| REGION_RATING_CLIENT_W_CITY |
| HOUR_APPR_PROCESS_START |
| REG_REGION_NOT_LIVE_REGION |
| REG_REGION_NOT_WORK_REGION |
| LIVE_REGION_NOT_WORK_REGION |
| REG_CITY_NOT_LIVE_CITY |
| REG_CITY_NOT_WORK_CITY |
| LIVE_CITY_NOT_WORK_CITY |
| EXT_SOURCE_1 |
| EXT_SOURCE_2 |
| EXT_SOURCE_3 |
| APARTMENTS_AVG |
| BASEMENTAREA_AVG |
| YEARS_BEGINEXPLUATATION_AVG |
| ELEVATORS_AVG |
| ENTRANCES_AVG |
| FLOORSMAX_AVG |
| LANDAREA_AVG |
| LIVINGAREA_AVG |
| NONLIVINGAREA_AVG |
| APARTMENTS_MODE |
| BASEMENTAREA_MODE |
| YEARS_BEGINEXPLUATATION_MODE |
| ELEVATORS_MODE |
| ENTRANCES_MODE |
| FLOORSMAX_MODE |
| LANDAREA_MODE |
| LIVINGAREA_MODE |
| NONLIVINGAREA_MODE |
| APARTMENTS_MEDI |
| BASEMENTAREA_MEDI |
| YEARS_BEGINEXPLUATATION_MEDI |
| ELEVATORS_MEDI |
| ENTRANCES_MEDI |
| FLOORSMAX_MEDI |
| LANDAREA_MEDI |
| LIVINGAREA_MEDI |
| NONLIVINGAREA_MEDI |
| TOTALAREA_MODE |
| OBS_30_CNT_SOCIAL_CIRCLE |
| DEF_30_CNT_SOCIAL_CIRCLE |
| OBS_60_CNT_SOCIAL_CIRCLE |
| DEF_60_CNT_SOCIAL_CIRCLE |
| DAYS_LAST_PHONE_CHANGE |
| FLAG_DOCUMENT_2 |
| FLAG_DOCUMENT_3 |
| FLAG_DOCUMENT_4 |
| FLAG_DOCUMENT_5 |
| FLAG_DOCUMENT_6 |
| FLAG_DOCUMENT_7 |
| FLAG_DOCUMENT_8 |
| FLAG_DOCUMENT_9 |
| FLAG_DOCUMENT_10 |
| FLAG_DOCUMENT_11 |
| FLAG_DOCUMENT_12 |
| FLAG_DOCUMENT_13 |
| FLAG_DOCUMENT_14 |
| FLAG_DOCUMENT_15 |
| FLAG_DOCUMENT_16 |
| FLAG_DOCUMENT_17 |
| FLAG_DOCUMENT_18 |
| FLAG_DOCUMENT_19 |
| FLAG_DOCUMENT_20 |
| FLAG_DOCUMENT_21 |
| AMT_REQ_CREDIT_BUREAU_HOUR |
| AMT_REQ_CREDIT_BUREAU_DAY |
| AMT_REQ_CREDIT_BUREAU_WEEK |
| AMT_REQ_CREDIT_BUREAU_MON |
| AMT_REQ_CREDIT_BUREAU_QRT |
| AMT_REQ_CREDIT_BUREAU_YEAR |
cat
Index(['NAME_CONTRACT_TYPE', 'CODE_GENDER', 'FLAG_OWN_CAR', 'FLAG_OWN_REALTY',
'NAME_TYPE_SUITE', 'NAME_INCOME_TYPE', 'NAME_EDUCATION_TYPE',
'NAME_FAMILY_STATUS', 'NAME_HOUSING_TYPE', 'OCCUPATION_TYPE',
'WEEKDAY_APPR_PROCESS_START', 'ORGANIZATION_TYPE', 'HOUSETYPE_MODE',
'WALLSMATERIAL_MODE', 'EMERGENCYSTATE_MODE'],
dtype='object')
OneHotEncoder
?Documentation for OneHotEncoder
Parameters
|
sparse_output
sparse_output: bool, default=True When ``True``, it returns a SciPy sparse matrix/array in "Compressed Sparse Row" (CSR) format. .. versionadded:: 1.2 `sparse` was renamed to `sparse_output` |
False | |
|
handle_unknown
handle_unknown: {'error', 'ignore', 'infrequent_if_exist', 'warn'}, default='error' Specifies the way unknown categories are handled during :meth:`transform`. - 'error' : Raise an error if an unknown category is present during transform. - 'ignore' : When an unknown category is encountered during transform, the resulting one-hot encoded columns for this feature will be all zeros. In the inverse transform, an unknown category will be denoted as None. - 'infrequent_if_exist' : When an unknown category is encountered during transform, the resulting one-hot encoded columns for this feature will map to the infrequent category if it exists. The infrequent category will be mapped to the last position in the encoding. During inverse transform, an unknown category will be mapped to the category denoted `'infrequent'` if it exists. If the `'infrequent'` category does not exist, then :meth:`transform` and :meth:`inverse_transform` will handle an unknown category as with `handle_unknown='ignore'`. Infrequent categories exist based on `min_frequency` and `max_categories`. Read more in the :ref:`User Guide <encoder_infrequent_categories>`. - 'warn' : When an unknown category is encountered during transform a warning is issued, and the encoding then proceeds as described for `handle_unknown="infrequent_if_exist"`. .. versionchanged:: 1.1 `'infrequent_if_exist'` was added to automatically handle unknown categories and infrequent categories. .. versionadded:: 1.6 The option `"warn"` was added in 1.6. |
'ignore' | |
|
categories
categories: 'auto' or a list of array-like, default='auto' Categories (unique values) per feature: - 'auto' : Determine categories automatically from the training data. - list : ``categories[i]`` holds the categories expected in the ith column. The passed categories should not mix strings and numeric values within a single feature, and should be sorted in case of numeric values. The used categories can be found in the ``categories_`` attribute. .. versionadded:: 0.20 |
'auto' | |
|
drop
drop: {'first', 'if_binary'} or an array-like of shape (n_features,), default=None Specifies a methodology to use to drop one of the categories per feature. This is useful in situations where perfectly collinear features cause problems, such as when feeding the resulting data into an unregularized linear regression model. However, dropping one category breaks the symmetry of the original representation and can therefore induce a bias in downstream models, for instance for penalized linear classification or regression models. - None : retain all features (the default). - 'first' : drop the first category in each feature. If only one category is present, the feature will be dropped entirely. - 'if_binary' : drop the first category in each feature with two categories. Features with 1 or more than 2 categories are left intact. - array : ``drop[i]`` is the category in feature ``X[:, i]`` that should be dropped. When `max_categories` or `min_frequency` is configured to group infrequent categories, the dropping behavior is handled after the grouping. .. versionadded:: 0.21 The parameter `drop` was added in 0.21. .. versionchanged:: 0.23 The option `drop='if_binary'` was added in 0.23. .. versionchanged:: 1.1 Support for dropping infrequent categories. |
None | |
|
dtype
dtype: number type, default=np.float64 Desired dtype of output. |
<class 'numpy.float64'> | |
|
min_frequency
min_frequency: int or float, default=None Specifies the minimum frequency below which a category will be considered infrequent. - If `int`, categories with a smaller cardinality will be considered infrequent. - If `float`, categories with a smaller cardinality than `min_frequency * n_samples` will be considered infrequent. .. versionadded:: 1.1 Read more in the :ref:`User Guide <encoder_infrequent_categories>`. |
None | |
|
max_categories
max_categories: int, default=None Specifies an upper limit to the number of output features for each input feature when considering infrequent categories. If there are infrequent categories, `max_categories` includes the category representing the infrequent categories along with the frequent categories. If `None`, there is no limit to the number of output features. .. versionadded:: 1.1 Read more in the :ref:`User Guide <encoder_infrequent_categories>`. |
None | |
|
feature_name_combiner
feature_name_combiner: "concat" or callable, default="concat" Callable with signature `def callable(input_feature, category)` that returns a string. This is used to create feature names to be returned by :meth:`get_feature_names_out`. `"concat"` concatenates encoded feature name and category with `feature + "_" + str(category)`.E.g. feature X with values 1, 6, 7 create feature names `X_1, X_6, X_7`. .. versionadded:: 1.3 |
'concat' |
Fitted attributes
| Name | Type | Value |
|---|---|---|
|
categories_
categories_: list of arrays The categories of each feature determined during fitting (in order of the features in X and corresponding with the output of ``transform``). This includes the category specified in ``drop`` (if any). |
list | [array(['Cash ... dtype=object), array(['F', '... dtype=object), array(['N', '... dtype=object), array(['N', '... dtype=object), ...] |
|
drop_idx_
drop_idx_: array of shape (n_features,) - ``drop_idx_[i]`` is the index in ``categories_[i]`` of the category to be dropped for each feature. - ``drop_idx_[i] = None`` if no category is to be dropped from the feature with index ``i``, e.g. when `drop='if_binary'` and the feature isn't binary. - ``drop_idx_ = None`` if all the transformed features will be retained. If infrequent categories are enabled by setting `min_frequency` or `max_categories` to a non-default value and `drop_idx[i]` corresponds to an infrequent category, then the entire infrequent category is dropped. .. versionchanged:: 0.23 Added the possibility to contain `None` values. |
NoneType | None |
|
feature_names_in_
feature_names_in_: ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 |
ndarray[object](15,) | ['NAME_CONTRACT_TYPE','CODE_GENDER','FLAG_OWN_CAR',...,'HOUSETYPE_MODE', 'WALLSMATERIAL_MODE','EMERGENCYSTATE_MODE'] |
|
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 1.0 |
int | 15 |
141 features
| NAME_CONTRACT_TYPE_Cash loans |
| NAME_CONTRACT_TYPE_Revolving loans |
| CODE_GENDER_F |
| CODE_GENDER_M |
| CODE_GENDER_XNA |
| FLAG_OWN_CAR_N |
| FLAG_OWN_CAR_Y |
| FLAG_OWN_REALTY_N |
| FLAG_OWN_REALTY_Y |
| NAME_TYPE_SUITE_Children |
| NAME_TYPE_SUITE_Family |
| NAME_TYPE_SUITE_Group of people |
| NAME_TYPE_SUITE_Missing |
| NAME_TYPE_SUITE_Other_A |
| NAME_TYPE_SUITE_Other_B |
| NAME_TYPE_SUITE_Spouse, partner |
| NAME_TYPE_SUITE_Unaccompanied |
| NAME_INCOME_TYPE_Businessman |
| NAME_INCOME_TYPE_Commercial associate |
| NAME_INCOME_TYPE_Maternity leave |
| NAME_INCOME_TYPE_Pensioner |
| NAME_INCOME_TYPE_State servant |
| NAME_INCOME_TYPE_Student |
| NAME_INCOME_TYPE_Unemployed |
| NAME_INCOME_TYPE_Working |
| NAME_EDUCATION_TYPE_Academic degree |
| NAME_EDUCATION_TYPE_Higher education |
| NAME_EDUCATION_TYPE_Incomplete higher |
| NAME_EDUCATION_TYPE_Lower secondary |
| NAME_EDUCATION_TYPE_Secondary / secondary special |
| NAME_FAMILY_STATUS_Civil marriage |
| NAME_FAMILY_STATUS_Married |
| NAME_FAMILY_STATUS_Separated |
| NAME_FAMILY_STATUS_Single / not married |
| NAME_FAMILY_STATUS_Unknown |
| NAME_FAMILY_STATUS_Widow |
| NAME_HOUSING_TYPE_Co-op apartment |
| NAME_HOUSING_TYPE_House / apartment |
| NAME_HOUSING_TYPE_Municipal apartment |
| NAME_HOUSING_TYPE_Office apartment |
| NAME_HOUSING_TYPE_Rented apartment |
| NAME_HOUSING_TYPE_With parents |
| OCCUPATION_TYPE_Accountants |
| OCCUPATION_TYPE_Cleaning staff |
| OCCUPATION_TYPE_Cooking staff |
| OCCUPATION_TYPE_Core staff |
| OCCUPATION_TYPE_Drivers |
| OCCUPATION_TYPE_HR staff |
| OCCUPATION_TYPE_High skill tech staff |
| OCCUPATION_TYPE_IT staff |
| OCCUPATION_TYPE_Laborers |
| OCCUPATION_TYPE_Low-skill Laborers |
| OCCUPATION_TYPE_Managers |
| OCCUPATION_TYPE_Medicine staff |
| OCCUPATION_TYPE_Missing |
| OCCUPATION_TYPE_Private service staff |
| OCCUPATION_TYPE_Realty agents |
| OCCUPATION_TYPE_Sales staff |
| OCCUPATION_TYPE_Secretaries |
| OCCUPATION_TYPE_Security staff |
| OCCUPATION_TYPE_Waiters/barmen staff |
| WEEKDAY_APPR_PROCESS_START_FRIDAY |
| WEEKDAY_APPR_PROCESS_START_MONDAY |
| WEEKDAY_APPR_PROCESS_START_SATURDAY |
| WEEKDAY_APPR_PROCESS_START_SUNDAY |
| WEEKDAY_APPR_PROCESS_START_THURSDAY |
| WEEKDAY_APPR_PROCESS_START_TUESDAY |
| WEEKDAY_APPR_PROCESS_START_WEDNESDAY |
| ORGANIZATION_TYPE_Advertising |
| ORGANIZATION_TYPE_Agriculture |
| ORGANIZATION_TYPE_Bank |
| ORGANIZATION_TYPE_Business Entity Type 1 |
| ORGANIZATION_TYPE_Business Entity Type 2 |
| ORGANIZATION_TYPE_Business Entity Type 3 |
| ORGANIZATION_TYPE_Cleaning |
| ORGANIZATION_TYPE_Construction |
| ORGANIZATION_TYPE_Culture |
| ORGANIZATION_TYPE_Electricity |
| ORGANIZATION_TYPE_Emergency |
| ORGANIZATION_TYPE_Government |
| ORGANIZATION_TYPE_Hotel |
| ORGANIZATION_TYPE_Housing |
| ORGANIZATION_TYPE_Industry: type 1 |
| ORGANIZATION_TYPE_Industry: type 10 |
| ORGANIZATION_TYPE_Industry: type 11 |
| ORGANIZATION_TYPE_Industry: type 12 |
| ORGANIZATION_TYPE_Industry: type 13 |
| ORGANIZATION_TYPE_Industry: type 2 |
| ORGANIZATION_TYPE_Industry: type 3 |
| ORGANIZATION_TYPE_Industry: type 4 |
| ORGANIZATION_TYPE_Industry: type 5 |
| ORGANIZATION_TYPE_Industry: type 6 |
| ORGANIZATION_TYPE_Industry: type 7 |
| ORGANIZATION_TYPE_Industry: type 8 |
| ORGANIZATION_TYPE_Industry: type 9 |
| ORGANIZATION_TYPE_Insurance |
| ORGANIZATION_TYPE_Kindergarten |
| ORGANIZATION_TYPE_Legal Services |
| ORGANIZATION_TYPE_Medicine |
| ORGANIZATION_TYPE_Military |
| ORGANIZATION_TYPE_Mobile |
| ORGANIZATION_TYPE_Other |
| ORGANIZATION_TYPE_Police |
| ORGANIZATION_TYPE_Postal |
| ORGANIZATION_TYPE_Realtor |
| ORGANIZATION_TYPE_Religion |
| ORGANIZATION_TYPE_Restaurant |
| ORGANIZATION_TYPE_School |
| ORGANIZATION_TYPE_Security |
| ORGANIZATION_TYPE_Security Ministries |
| ORGANIZATION_TYPE_Self-employed |
| ORGANIZATION_TYPE_Services |
| ORGANIZATION_TYPE_Telecom |
| ORGANIZATION_TYPE_Trade: type 1 |
| ORGANIZATION_TYPE_Trade: type 2 |
| ORGANIZATION_TYPE_Trade: type 3 |
| ORGANIZATION_TYPE_Trade: type 4 |
| ORGANIZATION_TYPE_Trade: type 5 |
| ORGANIZATION_TYPE_Trade: type 6 |
| ORGANIZATION_TYPE_Trade: type 7 |
| ORGANIZATION_TYPE_Transport: type 1 |
| ORGANIZATION_TYPE_Transport: type 2 |
| ORGANIZATION_TYPE_Transport: type 3 |
| ORGANIZATION_TYPE_Transport: type 4 |
| ORGANIZATION_TYPE_University |
| ORGANIZATION_TYPE_XNA |
| HOUSETYPE_MODE_Missing |
| HOUSETYPE_MODE_block of flats |
| HOUSETYPE_MODE_specific housing |
| HOUSETYPE_MODE_terraced house |
| WALLSMATERIAL_MODE_Block |
| WALLSMATERIAL_MODE_Missing |
| WALLSMATERIAL_MODE_Mixed |
| WALLSMATERIAL_MODE_Monolithic |
| WALLSMATERIAL_MODE_Others |
| WALLSMATERIAL_MODE_Panel |
| WALLSMATERIAL_MODE_Stone, brick |
| WALLSMATERIAL_MODE_Wooden |
| EMERGENCYSTATE_MODE_Missing |
| EMERGENCYSTATE_MODE_No |
| EMERGENCYSTATE_MODE_Yes |
229 features
| num__CNT_CHILDREN |
| num__AMT_INCOME_TOTAL |
| num__AMT_CREDIT |
| num__AMT_ANNUITY |
| num__AMT_GOODS_PRICE |
| num__REGION_POPULATION_RELATIVE |
| num__DAYS_BIRTH |
| num__DAYS_EMPLOYED |
| num__DAYS_REGISTRATION |
| num__DAYS_ID_PUBLISH |
| num__FLAG_MOBIL |
| num__FLAG_EMP_PHONE |
| num__FLAG_WORK_PHONE |
| num__FLAG_CONT_MOBILE |
| num__FLAG_PHONE |
| num__FLAG_EMAIL |
| num__CNT_FAM_MEMBERS |
| num__REGION_RATING_CLIENT |
| num__REGION_RATING_CLIENT_W_CITY |
| num__HOUR_APPR_PROCESS_START |
| num__REG_REGION_NOT_LIVE_REGION |
| num__REG_REGION_NOT_WORK_REGION |
| num__LIVE_REGION_NOT_WORK_REGION |
| num__REG_CITY_NOT_LIVE_CITY |
| num__REG_CITY_NOT_WORK_CITY |
| num__LIVE_CITY_NOT_WORK_CITY |
| num__EXT_SOURCE_1 |
| num__EXT_SOURCE_2 |
| num__EXT_SOURCE_3 |
| num__APARTMENTS_AVG |
| num__BASEMENTAREA_AVG |
| num__YEARS_BEGINEXPLUATATION_AVG |
| num__ELEVATORS_AVG |
| num__ENTRANCES_AVG |
| num__FLOORSMAX_AVG |
| num__LANDAREA_AVG |
| num__LIVINGAREA_AVG |
| num__NONLIVINGAREA_AVG |
| num__APARTMENTS_MODE |
| num__BASEMENTAREA_MODE |
| num__YEARS_BEGINEXPLUATATION_MODE |
| num__ELEVATORS_MODE |
| num__ENTRANCES_MODE |
| num__FLOORSMAX_MODE |
| num__LANDAREA_MODE |
| num__LIVINGAREA_MODE |
| num__NONLIVINGAREA_MODE |
| num__APARTMENTS_MEDI |
| num__BASEMENTAREA_MEDI |
| num__YEARS_BEGINEXPLUATATION_MEDI |
| num__ELEVATORS_MEDI |
| num__ENTRANCES_MEDI |
| num__FLOORSMAX_MEDI |
| num__LANDAREA_MEDI |
| num__LIVINGAREA_MEDI |
| num__NONLIVINGAREA_MEDI |
| num__TOTALAREA_MODE |
| num__OBS_30_CNT_SOCIAL_CIRCLE |
| num__DEF_30_CNT_SOCIAL_CIRCLE |
| num__OBS_60_CNT_SOCIAL_CIRCLE |
| num__DEF_60_CNT_SOCIAL_CIRCLE |
| num__DAYS_LAST_PHONE_CHANGE |
| num__FLAG_DOCUMENT_2 |
| num__FLAG_DOCUMENT_3 |
| num__FLAG_DOCUMENT_4 |
| num__FLAG_DOCUMENT_5 |
| num__FLAG_DOCUMENT_6 |
| num__FLAG_DOCUMENT_7 |
| num__FLAG_DOCUMENT_8 |
| num__FLAG_DOCUMENT_9 |
| num__FLAG_DOCUMENT_10 |
| num__FLAG_DOCUMENT_11 |
| num__FLAG_DOCUMENT_12 |
| num__FLAG_DOCUMENT_13 |
| num__FLAG_DOCUMENT_14 |
| num__FLAG_DOCUMENT_15 |
| num__FLAG_DOCUMENT_16 |
| num__FLAG_DOCUMENT_17 |
| num__FLAG_DOCUMENT_18 |
| num__FLAG_DOCUMENT_19 |
| num__FLAG_DOCUMENT_20 |
| num__FLAG_DOCUMENT_21 |
| num__AMT_REQ_CREDIT_BUREAU_HOUR |
| num__AMT_REQ_CREDIT_BUREAU_DAY |
| num__AMT_REQ_CREDIT_BUREAU_WEEK |
| num__AMT_REQ_CREDIT_BUREAU_MON |
| num__AMT_REQ_CREDIT_BUREAU_QRT |
| num__AMT_REQ_CREDIT_BUREAU_YEAR |
| cat__NAME_CONTRACT_TYPE_Cash loans |
| cat__NAME_CONTRACT_TYPE_Revolving loans |
| cat__CODE_GENDER_F |
| cat__CODE_GENDER_M |
| cat__CODE_GENDER_XNA |
| cat__FLAG_OWN_CAR_N |
| cat__FLAG_OWN_CAR_Y |
| cat__FLAG_OWN_REALTY_N |
| cat__FLAG_OWN_REALTY_Y |
| cat__NAME_TYPE_SUITE_Children |
| cat__NAME_TYPE_SUITE_Family |
| cat__NAME_TYPE_SUITE_Group of people |
| cat__NAME_TYPE_SUITE_Missing |
| cat__NAME_TYPE_SUITE_Other_A |
| cat__NAME_TYPE_SUITE_Other_B |
| cat__NAME_TYPE_SUITE_Spouse, partner |
| cat__NAME_TYPE_SUITE_Unaccompanied |
| cat__NAME_INCOME_TYPE_Businessman |
| cat__NAME_INCOME_TYPE_Commercial associate |
| cat__NAME_INCOME_TYPE_Maternity leave |
| cat__NAME_INCOME_TYPE_Pensioner |
| cat__NAME_INCOME_TYPE_State servant |
| cat__NAME_INCOME_TYPE_Student |
| cat__NAME_INCOME_TYPE_Unemployed |
| cat__NAME_INCOME_TYPE_Working |
| cat__NAME_EDUCATION_TYPE_Academic degree |
| cat__NAME_EDUCATION_TYPE_Higher education |
| cat__NAME_EDUCATION_TYPE_Incomplete higher |
| cat__NAME_EDUCATION_TYPE_Lower secondary |
| cat__NAME_EDUCATION_TYPE_Secondary / secondary special |
| cat__NAME_FAMILY_STATUS_Civil marriage |
| cat__NAME_FAMILY_STATUS_Married |
| cat__NAME_FAMILY_STATUS_Separated |
| cat__NAME_FAMILY_STATUS_Single / not married |
| cat__NAME_FAMILY_STATUS_Unknown |
| cat__NAME_FAMILY_STATUS_Widow |
| cat__NAME_HOUSING_TYPE_Co-op apartment |
| cat__NAME_HOUSING_TYPE_House / apartment |
| cat__NAME_HOUSING_TYPE_Municipal apartment |
| cat__NAME_HOUSING_TYPE_Office apartment |
| cat__NAME_HOUSING_TYPE_Rented apartment |
| cat__NAME_HOUSING_TYPE_With parents |
| cat__OCCUPATION_TYPE_Accountants |
| cat__OCCUPATION_TYPE_Cleaning staff |
| cat__OCCUPATION_TYPE_Cooking staff |
| cat__OCCUPATION_TYPE_Core staff |
| cat__OCCUPATION_TYPE_Drivers |
| cat__OCCUPATION_TYPE_HR staff |
| cat__OCCUPATION_TYPE_High skill tech staff |
| cat__OCCUPATION_TYPE_IT staff |
| cat__OCCUPATION_TYPE_Laborers |
| cat__OCCUPATION_TYPE_Low-skill Laborers |
| cat__OCCUPATION_TYPE_Managers |
| cat__OCCUPATION_TYPE_Medicine staff |
| cat__OCCUPATION_TYPE_Missing |
| cat__OCCUPATION_TYPE_Private service staff |
| cat__OCCUPATION_TYPE_Realty agents |
| cat__OCCUPATION_TYPE_Sales staff |
| cat__OCCUPATION_TYPE_Secretaries |
| cat__OCCUPATION_TYPE_Security staff |
| cat__OCCUPATION_TYPE_Waiters/barmen staff |
| cat__WEEKDAY_APPR_PROCESS_START_FRIDAY |
| cat__WEEKDAY_APPR_PROCESS_START_MONDAY |
| cat__WEEKDAY_APPR_PROCESS_START_SATURDAY |
| cat__WEEKDAY_APPR_PROCESS_START_SUNDAY |
| cat__WEEKDAY_APPR_PROCESS_START_THURSDAY |
| cat__WEEKDAY_APPR_PROCESS_START_TUESDAY |
| cat__WEEKDAY_APPR_PROCESS_START_WEDNESDAY |
| cat__ORGANIZATION_TYPE_Advertising |
| cat__ORGANIZATION_TYPE_Agriculture |
| cat__ORGANIZATION_TYPE_Bank |
| cat__ORGANIZATION_TYPE_Business Entity Type 1 |
| cat__ORGANIZATION_TYPE_Business Entity Type 2 |
| cat__ORGANIZATION_TYPE_Business Entity Type 3 |
| cat__ORGANIZATION_TYPE_Cleaning |
| cat__ORGANIZATION_TYPE_Construction |
| cat__ORGANIZATION_TYPE_Culture |
| cat__ORGANIZATION_TYPE_Electricity |
| cat__ORGANIZATION_TYPE_Emergency |
| cat__ORGANIZATION_TYPE_Government |
| cat__ORGANIZATION_TYPE_Hotel |
| cat__ORGANIZATION_TYPE_Housing |
| cat__ORGANIZATION_TYPE_Industry: type 1 |
| cat__ORGANIZATION_TYPE_Industry: type 10 |
| cat__ORGANIZATION_TYPE_Industry: type 11 |
| cat__ORGANIZATION_TYPE_Industry: type 12 |
| cat__ORGANIZATION_TYPE_Industry: type 13 |
| cat__ORGANIZATION_TYPE_Industry: type 2 |
| cat__ORGANIZATION_TYPE_Industry: type 3 |
| cat__ORGANIZATION_TYPE_Industry: type 4 |
| cat__ORGANIZATION_TYPE_Industry: type 5 |
| cat__ORGANIZATION_TYPE_Industry: type 6 |
| cat__ORGANIZATION_TYPE_Industry: type 7 |
| cat__ORGANIZATION_TYPE_Industry: type 8 |
| cat__ORGANIZATION_TYPE_Industry: type 9 |
| cat__ORGANIZATION_TYPE_Insurance |
| cat__ORGANIZATION_TYPE_Kindergarten |
| cat__ORGANIZATION_TYPE_Legal Services |
| cat__ORGANIZATION_TYPE_Medicine |
| cat__ORGANIZATION_TYPE_Military |
| cat__ORGANIZATION_TYPE_Mobile |
| cat__ORGANIZATION_TYPE_Other |
| cat__ORGANIZATION_TYPE_Police |
| cat__ORGANIZATION_TYPE_Postal |
| cat__ORGANIZATION_TYPE_Realtor |
| cat__ORGANIZATION_TYPE_Religion |
| cat__ORGANIZATION_TYPE_Restaurant |
| cat__ORGANIZATION_TYPE_School |
| cat__ORGANIZATION_TYPE_Security |
| cat__ORGANIZATION_TYPE_Security Ministries |
| cat__ORGANIZATION_TYPE_Self-employed |
| cat__ORGANIZATION_TYPE_Services |
| cat__ORGANIZATION_TYPE_Telecom |
| cat__ORGANIZATION_TYPE_Trade: type 1 |
| cat__ORGANIZATION_TYPE_Trade: type 2 |
| cat__ORGANIZATION_TYPE_Trade: type 3 |
| cat__ORGANIZATION_TYPE_Trade: type 4 |
| cat__ORGANIZATION_TYPE_Trade: type 5 |
| cat__ORGANIZATION_TYPE_Trade: type 6 |
| cat__ORGANIZATION_TYPE_Trade: type 7 |
| cat__ORGANIZATION_TYPE_Transport: type 1 |
| cat__ORGANIZATION_TYPE_Transport: type 2 |
| cat__ORGANIZATION_TYPE_Transport: type 3 |
| cat__ORGANIZATION_TYPE_Transport: type 4 |
| cat__ORGANIZATION_TYPE_University |
| cat__ORGANIZATION_TYPE_XNA |
| cat__HOUSETYPE_MODE_Missing |
| cat__HOUSETYPE_MODE_block of flats |
| cat__HOUSETYPE_MODE_specific housing |
| cat__HOUSETYPE_MODE_terraced house |
| cat__WALLSMATERIAL_MODE_Block |
| cat__WALLSMATERIAL_MODE_Missing |
| cat__WALLSMATERIAL_MODE_Mixed |
| cat__WALLSMATERIAL_MODE_Monolithic |
| cat__WALLSMATERIAL_MODE_Others |
| cat__WALLSMATERIAL_MODE_Panel |
| cat__WALLSMATERIAL_MODE_Stone, brick |
| cat__WALLSMATERIAL_MODE_Wooden |
| cat__EMERGENCYSTATE_MODE_Missing |
| cat__EMERGENCYSTATE_MODE_No |
| cat__EMERGENCYSTATE_MODE_Yes |
HistGradientBoostingClassifier
?Documentation for HistGradientBoostingClassifier
Parameters
|
learning_rate
learning_rate: float, default=0.1 The learning rate, also known as *shrinkage*. This is used as a multiplicative factor for the leaves values. Use ``1`` for no shrinkage. |
0.05 | |
|
max_iter
max_iter: int, default=100 The maximum number of iterations of the boosting process, i.e. the maximum number of trees for binary classification. For multiclass classification, `n_classes` trees per iteration are built. |
200 | |
|
l2_regularization
l2_regularization: float, default=0 The L2 regularization parameter penalizing leaves with small hessians. Use ``0`` for no regularization (default). |
1.0 | |
|
random_state
random_state: int, RandomState instance or None, default=None Pseudo-random number generator to control the subsampling in the binning process, and the train/validation data split if early stopping is enabled. Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`. |
42 | |
|
loss
loss: {'log_loss'}, default='log_loss' The loss function to use in the boosting process. For binary classification problems, 'log_loss' is also known as logistic loss, binomial deviance or binary crossentropy. Internally, the model fits one tree per boosting iteration and uses the logistic sigmoid function (expit) as inverse link function to compute the predicted positive class probability. For multiclass classification problems, 'log_loss' is also known as multinomial deviance or categorical crossentropy. Internally, the model fits one tree per boosting iteration and per class and uses the softmax function as inverse link function to compute the predicted probabilities of the classes. |
'log_loss' | |
|
max_leaf_nodes
max_leaf_nodes: int or None, default=31 The maximum number of leaves for each tree. Must be strictly greater than 1. If None, there is no maximum limit. |
31 | |
|
max_depth
max_depth: int or None, default=None The maximum depth of each tree. The depth of a tree is the number of edges to go from the root to the deepest leaf. Depth isn't constrained by default. |
None | |
|
min_samples_leaf
min_samples_leaf: int, default=20 The minimum number of samples per leaf. For small datasets with less than a few hundred samples, it is recommended to lower this value since only very shallow trees would be built. |
20 | |
|
max_features
max_features: float, default=1.0 Proportion of randomly chosen features in each and every node split. This is a form of regularization, smaller values make the trees weaker learners and might prevent overfitting. If interaction constraints from `interaction_cst` are present, only allowed features are taken into account for the subsampling. .. versionadded:: 1.4 |
1.0 | |
|
max_bins
max_bins: int, default=255 The maximum number of bins to use for non-missing values. Before training, each feature of the input array `X` is binned into integer-valued bins, which allows for a much faster training stage. Features with a small number of unique values may use less than ``max_bins`` bins. In addition to the ``max_bins`` bins, one more bin is always reserved for missing values. Must be no larger than 255. |
255 | |
|
categorical_features
categorical_features: array-like of {bool, int, str} of shape (n_features) or shape (n_categorical_features,), default='from_dtype' Indicates the categorical features. - None : no feature will be considered categorical. - boolean array-like : boolean mask indicating categorical features. - integer array-like : integer indices indicating categorical features. - str array-like: names of categorical features (assuming the training data has feature names). - `"from_dtype"`: dataframe columns with dtype "Categorical" and "Enum" are considered to be categorical features. The input must be a dataframe that is supported by narwhals (or supports it): :func:`narwhals.from_native` must work. This is the case, for instance, for pandas and polars DataFrames. For each categorical feature, there must be at most `max_bins` unique categories. Negative values for categorical features encoded as numeric dtypes are treated as missing values. All categorical values are converted to floating point numbers. This means that categorical values of 1.0 and 1 are treated as the same category. Read more in the :ref:`User Guide <categorical_support_gbdt>`. .. versionadded:: 0.24 .. versionchanged:: 1.2 Added support for feature names. .. versionchanged:: 1.4 Added `"from_dtype"` option. .. versionchanged:: 1.6 The default value changed from `None` to `"from_dtype"`. |
'from_dtype' | |
|
monotonic_cst
monotonic_cst: array-like of int of shape (n_features) or dict, default=None Monotonic constraint to enforce on each feature are specified using the following integer values: - 1: monotonic increase - 0: no constraint - -1: monotonic decrease If a dict with str keys, map feature to monotonic constraints by name. If an array, the features are mapped to constraints by position. See :ref:`monotonic_cst_features_names` for a usage example. The constraints are only valid for binary classifications and hold over the probability of the positive class. Read more in the :ref:`User Guide <monotonic_cst_gbdt>`. .. versionadded:: 0.23 .. versionchanged:: 1.2 Accept dict of constraints with feature names as keys. |
None | |
|
interaction_cst
interaction_cst: {"pairwise", "no_interactions"} or sequence of lists/tuples/sets of int, default=None Specify interaction constraints, the sets of features which can interact with each other in child node splits. Each item specifies the set of feature indices that are allowed to interact with each other. If there are more features than specified in these constraints, they are treated as if they were specified as an additional set. The strings "pairwise" and "no_interactions" are shorthands for allowing only pairwise or no interactions, respectively. For instance, with 5 features in total, `interaction_cst=[{0, 1}]` is equivalent to `interaction_cst=[{0, 1}, {2, 3, 4}]`, and specifies that each branch of a tree will either only split on features 0 and 1 or only split on features 2, 3 and 4. See :ref:`this example<ice-vs-pdp>` on how to use `interaction_cst`. .. versionadded:: 1.2 |
None | |
|
warm_start
warm_start: bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble. For results to be valid, the estimator should be re-trained on the same data only. See :term:`the Glossary <warm_start>`. |
False | |
|
early_stopping
early_stopping: 'auto' or bool, default='auto' If 'auto', early stopping is enabled if the sample size is larger than 10000 or if `X_val` and `y_val` are passed to `fit`. If True, early stopping is enabled, otherwise early stopping is disabled. .. versionadded:: 0.23 |
'auto' | |
|
scoring
scoring: str or callable or None, default='loss' Scoring method to use for early stopping. Only used if `early_stopping` is enabled. Options: - str: see :ref:`scoring_string_names` for options. - callable: a scorer callable object (e.g., function) with signature ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. - `None`: :ref:`accuracy <accuracy_score>` is used. - 'loss': early stopping is checked w.r.t the loss value. |
'loss' | |
|
validation_fraction
validation_fraction: int or float or None, default=0.1 Proportion (or absolute size) of training data to set aside as validation data for early stopping. If None, early stopping is done on the training data. The value is ignored if either early stopping is not performed, e.g. `early_stopping=False`, or if `X_val` and `y_val` are passed to fit. |
0.1 | |
|
n_iter_no_change
n_iter_no_change: int, default=10 Used to determine when to "early stop". The fitting process is stopped when none of the last ``n_iter_no_change`` scores are better than the ``n_iter_no_change - 1`` -th-to-last one, up to some tolerance. Only used if early stopping is performed. |
10 | |
|
tol
tol: float, default=1e-7 The absolute tolerance to use when comparing scores. The higher the tolerance, the more likely we are to early stop: higher tolerance means that it will be harder for subsequent iterations to be considered an improvement upon the reference score. |
1e-07 | |
|
verbose
verbose: int, default=0 The verbosity level. If not zero, print some information about the fitting process. ``1`` prints only summary info, ``2`` prints info per iteration. |
0 | |
|
class_weight
class_weight: dict or 'balanced', default=None Weights associated with classes in the form `{class_label: weight}`. If not given, all classes are supposed to have weight one. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as `n_samples / (n_classes * np.bincount(y))`. Note that these weights will be multiplied with sample_weight (passed through the fit method) if `sample_weight` is specified. .. versionadded:: 1.2 |
None |
Fitted attributes
| Name | Type | Value |
|---|---|---|
|
classes_
classes_: array, shape = (n_classes,) Class labels. |
ndarray[int64](2,) | [0,1] |
|
do_early_stopping_
do_early_stopping_: bool Indicates whether early stopping is used during training. |
bool | True |
|
is_categorical_
is_categorical_: ndarray, shape (n_features, ) or None Boolean mask for the categorical features. ``None`` if there are no categorical features. |
NoneType | None |
|
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 0.24 |
int | 229 |
|
n_iter_
n_iter_: int The number of iterations as selected by early stopping, depending on the `early_stopping` parameter. Otherwise it corresponds to max_iter. |
int | 200 |
|
n_trees_per_iteration_
n_trees_per_iteration_: int The number of tree that are built at each iteration. This is equal to 1 for binary classification, and to ``n_classes`` for multiclass classification. |
int | 1 |
|
train_score_
train_score_: ndarray, shape (n_iter_+1,) The scores at each iteration on the training data. The first entry is the score of the ensemble before the first iteration. Scores are computed according to the ``scoring`` parameter. If ``scoring`` is not 'loss', scores are computed on a subset of at most 10 000 samples. Empty if no early stopping. |
ndarray[float64](201,) | [-0.28,-0.28,-0.28,...,-0.24,-0.24,-0.24] |
|
validation_score_
validation_score_: ndarray, shape (n_iter_+1,) The scores at each iteration on the held-out validation data. The first entry is the score of the ensemble before the first iteration. Scores are computed according to the ``scoring`` parameter. Empty if no early stopping or if ``validation_fraction`` is None. |
ndarray[float64](201,) | [-0.28,-0.28,-0.28,...,-0.25,-0.25,-0.25] |
In [84]
final_prob = final_pipeline.predict_proba(X_test)[:, 1]
final_pred = (final_prob >= 0.15).astype(int)In [85]
from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
f1_score,
roc_auc_score
)
print("=== FINAL MODEL ===")
print("Accuracy :", accuracy_score(y_test, final_pred))
print("Precision:", precision_score(y_test, final_pred))
print("Recall :", recall_score(y_test, final_pred))
print("F1 Score :", f1_score(y_test, final_pred))
print("ROC-AUC :", roc_auc_score(y_test, final_prob))=== FINAL MODEL === Accuracy : 0.8516820317708079 Precision: 0.24978933429637654 Recall : 0.4179254783484391 F1 Score : 0.31268836648583487 ROC-AUC : 0.759978307952619
In [86]
import joblib
joblib.dump(
{
"pipeline": final_pipeline,
"threshold": 0.15
},
"../models/credit_risk_model.joblib"
)['../models/credit_risk_model.joblib']
In [87]
import os
print(os.path.exists("../models/credit_risk_model.joblib"))
print(
os.path.getsize("../models/credit_risk_model.joblib") / (1024 * 1024),
"MB"
)True 0.7658452987670898 MB
In [88]
import joblib
saved_model = joblib.load("../models/credit_risk_model.joblib")
print(type(saved_model))
print(saved_model.keys())
print("Threshold:", saved_model["threshold"])<class 'dict'> dict_keys(['pipeline', 'threshold']) Threshold: 0.15
In [89]
loaded_pipeline = saved_model["pipeline"]
threshold = saved_model["threshold"]
sample = X_test.iloc[:5]
sample_prob = loaded_pipeline.predict_proba(sample)[:, 1]
sample_pred = (sample_prob >= threshold).astype(int)
print("Probabilities:", sample_prob)
print("Predictions:", sample_pred)Probabilities: [0.04600577 0.04040459 0.23743445 0.06401579 0.08211444] Predictions: [0 0 1 0 0]
In
#Gemini Code
import os
import joblib
# Target paths relative to notebook directory
model_save_path = "../models/credit_risk_model.joblib"
defaults_save_path = "../models/app_defaults.joblib"
# 1. Create app_defaults if missing (using training features sample/median)
app_defaults = X_train.iloc[0].to_dict()
# 2. Save Model Dictionary
joblib.dump(
{
"pipeline": final_pipeline,
"threshold": 0.15
},
model_save_path
)
# 3. Save App Defaults
joblib.dump(app_defaults, defaults_save_path)
print("Models and defaults successfully re-saved!")Models and defaults successfully re-saved!
In [94]
app_defaults = X_train.iloc[0].to_dict()
joblib.dump(app_defaults, "../models/app_defaults.joblib")['../models/app_defaults.joblib']