Preprocessing¶
sklego.preprocessing.columncapper.ColumnCapper
¶
Bases: TransformerMixin
, BaseEstimator
The ColumnCapper
transformer caps the values of columns according to the given quantile thresholds.
The capping is performed independently for each column of the input data. The quantile thresholds are computed during the fitting phase. The capping is performed during the transformation phase.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
quantile_range
|
Tuple[float, float] | List[float]
|
The quantile ranges to perform the capping. Their values must be in the interval [0; 100]. |
(5.0, 95.0)
|
interpolation
|
Literal[linear, lower, higher, midpoint, nearest]
|
The interpolation method to compute the quantiles when the desired quantile lies between two data points The Available values are:
|
"linear"
|
discard_infs
|
bool
|
Whether to discard Info Setting |
False
|
copy
|
bool
|
If False, try to avoid a copy and do inplace capping instead. This is not guaranteed to always work inplace; e.g. if the data is not a NumPy array or scipy.sparse CSR matrix, a copy may still be returned. |
True
|
Attributes:
Name | Type | Description |
---|---|---|
quantiles_ |
np.ndarray of shape (2, n_features)
|
The computed quantiles for each column of the input data. The first row contains the lower quantile, the second row contains the upper quantile. |
n_features_in_ |
int
|
Number of features seen during |
n_columns_ |
int
|
Deprecated, please use |
Examples:
import pandas as pd
import numpy as np
from sklego.preprocessing import ColumnCapper
df = pd.DataFrame({'a':[2, 4.5, 7, 9], 'b':[11, 12, np.inf, 14]})
df
'''
a b
0 2.0 11.0
1 4.5 12.0
2 7.0 inf
3 9.0 14.0
'''
capper = ColumnCapper()
capper.fit_transform(df)
'''
array([[ 2.375, 11.1 ],
[ 4.5 , 12. ],
[ 7. , 13.8 ],
[ 8.7 , 13.8 ]])
'''
capper = ColumnCapper(discard_infs=True) # Discarding infs
df[['a', 'b']] = capper.fit_transform(df)
df
'''
a b
0 2.375 11.1
1 4.500 12.0
2 7.000 NaN
3 8.700 13.8
'''
Source code in sklego/preprocessing/columncapper.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
|
fit(X, y=None)
¶
Fit the ColumnCapper
transformer by computing quantiles for each column of X
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data used to compute the quantiles for capping. |
required |
y
|
array-like of shape (n_samples,)
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
ColumnCapper
|
The fitted transformer. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
Source code in sklego/preprocessing/columncapper.py
transform(X)
¶
Performs the capping on the column(s) of X
according to the quantile thresholds computed during fitting.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data for which the capping limit(s) will be applied. |
required |
Returns:
Name | Type | Description |
---|---|---|
X |
np.ndarray of shape (n_samples, n_features)
|
|
Raises:
Type | Description |
---|---|
ValueError
|
If the number of columns from |
Source code in sklego/preprocessing/columncapper.py
sklego.preprocessing.pandastransformers.ColumnDropper
¶
Bases: BaseEstimator
, TransformerMixin
The ColumnDropper
transformer allows dropping specific columns from a DataFrame by name.
Can be useful in a sklearn Pipeline.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
columns
|
str | list[str]
|
Column name(s) to be selected. |
required |
Attributes:
Name | Type | Description |
---|---|---|
feature_names_ |
list[str]
|
The names of the features to keep during transform. |
Notes
Native cross-dataframe support is achieved using Narwhals.
Supported dataframes are:
- pandas
- Polars (eager or lazy)
- Modin
- cuDF
See Narwhals docs for an up-to-date list (and to learn how you can add your dataframe library to it!).
Examples:
# Selecting a single column from a pandas DataFrame
import pandas as pd
from sklego.preprocessing import ColumnDropper
df = pd.DataFrame({
"name": ["Swen", "Victor", "Alex"],
"length": [1.82, 1.85, 1.80],
"shoesize": [42, 44, 45]
})
ColumnDropper(["name"]).fit_transform(df)
'''
length shoesize
0 1.82 42
1 1.85 44
2 1.80 45
'''
# Dropping multiple columns from a pandas DataFrame
ColumnDropper(["length", "shoesize"]).fit_transform(df)
'''
name
0 Swen
1 Victor
2 Alex
'''
# Dropping non-existent columns results in a KeyError
ColumnDropper(["weight"]).fit_transform(df)
# Traceback (most recent call last):
# ...
# KeyError: "['weight'] column(s) not in DataFrame"
# How to use the ColumnSelector in a sklearn Pipeline
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
pipe = Pipeline([
("select", ColumnDropper(["name", "shoesize"])),
("scale", StandardScaler()),
])
pipe.fit_transform(df)
# array([[-0.16222142],
# [ 1.29777137],
# [-1.13554995]])
Raises:
Type | Description |
---|---|
TypeError
|
If input provided is not a DataFrame. |
KeyError
|
If columns provided are not in the input DataFrame. |
ValueError
|
If dropping the specified columns would result in an empty output DataFrame. |
Source code in sklego/preprocessing/pandastransformers.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
|
fit(X, y=None)
¶
Fit the transformer by storing the column names to keep during .transform()
step.
Checks:
- If input is a supported DataFrame
- If column names are in such DataFrame
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
DataFrame
|
The data on which we apply the column selection. |
required |
y
|
Series
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
ColumnDropper
|
The fitted transformer. |
Raises:
Type | Description |
---|---|
TypeError
|
If |
KeyError
|
If one or more of the columns provided doesn't exist in the input DataFrame. |
ValueError
|
If dropping the specified columns would result in an empty output DataFrame. |
Source code in sklego/preprocessing/pandastransformers.py
get_feature_names()
¶
transform(X)
¶
Returns a DataFrame with only the specified columns.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
DataFrame
|
The data on which we apply the column selection. |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
The data with the specified columns dropped. |
Raises:
Type | Description |
---|---|
TypeError
|
If |
Source code in sklego/preprocessing/pandastransformers.py
sklego.preprocessing.pandastransformers.ColumnSelector
¶
Bases: BaseEstimator
, TransformerMixin
The ColumnSelector
transformer allows selecting specific columns from a DataFrame by name.
Can be useful in a sklearn Pipeline.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
columns
|
str | list[str]
|
Column name(s) to be selected. |
required |
Notes
Native cross-dataframe support is achieved using Narwhals.
Supported dataframes are:
- pandas
- Polars (eager or lazy)
- Modin
- cuDF
See Narwhals docs for an up-to-date list (and to learn how you can add your dataframe library to it!).
Attributes:
Name | Type | Description |
---|---|---|
columns_ |
list[str]
|
The names of the features to keep during transform. |
Examples:
# Selecting a single column from a pandas DataFrame
import pandas as pd
from sklego.preprocessing import ColumnSelector
df_pd = pd.DataFrame({
"name": ["Swen", "Victor", "Alex"],
"length": [1.82, 1.85, 1.80],
"shoesize": [42, 44, 45]
})
ColumnSelector(["length"]).fit_transform(df_pd)
'''
length
0 1.82
1 1.85
2 1.80
'''
# Selecting multiple columns from a polars DataFrame
import polars as pl
from sklego.preprocessing import ColumnSelector
df_pl = pl.DataFrame({
"name": ["Swen", "Victor", "Alex"],
"length": [1.82, 1.85, 1.80],
"shoesize": [42, 44, 45]
})
ColumnSelector(["length", "shoesize"]).fit_transform(df_pl)
'''
shape: (3, 2)
┌────────┬──────────┐
│ length ┆ shoesize │
│ --- ┆ --- │
│ f64 ┆ i64 │
╞════════╪══════════╡
│ 1.82 ┆ 42 │
│ 1.85 ┆ 44 │
│ 1.8 ┆ 45 │
└────────┴──────────┘
'''
# Selecting non-existent columns results in a KeyError
ColumnSelector(["weight"]).fit_transform(df_pd)
# Traceback (most recent call last):
# ...
# KeyError: "['weight'] column(s) not in DataFrame"
# How to use the ColumnSelector in a sklearn Pipeline
import polars as pl
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklego.preprocessing import ColumnSelector
pipe = Pipeline([
("select", ColumnSelector(["length"])),
("scale", StandardScaler()),
])
pipe.fit_transform(df_pl)
# array([[-0.16222142],
# [ 1.29777137],
# [-1.13554995]])
Raises:
Type | Description |
---|---|
TypeError
|
If input provided is not a supported DataFrame. |
KeyError
|
If columns provided are not in the input DataFrame. |
ValueError
|
If provided list of columns to select is empty and would result in an empty output DataFrame. |
Source code in sklego/preprocessing/pandastransformers.py
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 |
|
fit(X, y=None)
¶
Fit the transformer by storing the column names to keep during transform.
Checks:
- If input is a supported DataFrame
- If column names are in such DataFrame
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
DataFrame
|
The data on which we apply the column selection. |
required |
y
|
Series
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
ColumnSelector
|
The fitted transformer. |
Raises:
Type | Description |
---|---|
TypeError
|
If |
KeyError
|
If one or more of the columns provided doesn't exist in the input DataFrame. |
ValueError
|
If provided list of columns to select is empty and would result in an empty output DataFrame. |
Source code in sklego/preprocessing/pandastransformers.py
get_feature_names()
¶
transform(X)
¶
Returns a DataFrame with only the specified columns.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
DataFrame
|
The data on which we apply the column selection. |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
The data with the specified columns dropped. |
Raises:
Type | Description |
---|---|
TypeError
|
If |
Source code in sklego/preprocessing/pandastransformers.py
sklego.preprocessing.dictmapper.DictMapper
¶
Bases: TransformerMixin
, BaseEstimator
The DictMapper
transformer maps the values of columns according to the input mapper
dictionary, fall back to
the default
value if the key is not present in the dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mapper
|
dict[..., int]
|
The dictionary containing the mapping of the values. |
required |
default
|
int
|
The value to fall back to if the value is not in the mapper. |
required |
Attributes:
Name | Type | Description |
---|---|---|
n_features_in_ |
int
|
Number of features seen during |
dim_ |
int
|
Deprecated, please use |
Examples:
import pandas as pd
from sklego.preprocessing.dictmapper import DictMapper
from sklearn.compose import ColumnTransformer
X = pd.DataFrame({
"city_pop": ["Amsterdam", "Leiden", "Utrecht", "None", "Haarlem"]
})
mapper = {
"Amsterdam": 1_181_817,
"Leiden": 130_181,
"Utrecht": 367_984,
"Haarlem": 165_396,
}
ct = ColumnTransformer([("dictmapper", DictMapper(mapper, 0), ["city_pop"])])
X_trans = ct.fit_transform(X)
X_trans
# array([[1181817],
# [ 130181],
# [ 367984],
# [ 0],
# [ 165396]])
Source code in sklego/preprocessing/dictmapper.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
|
fit(X, y=None)
¶
Checks the input data and records the number of features.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to fit. |
required |
y
|
array-like of shape (n_samples,)
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
DictMapper
|
The fitted transformer. |
Source code in sklego/preprocessing/dictmapper.py
transform(X)
¶
Performs the mapping on the column(s) of X
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data for which the mapping will be applied. |
required |
Returns:
Type | Description |
---|---|
np.ndarray of shape (n_samples, n_features)
|
The data with the mapping applied. |
Raises:
Type | Description |
---|---|
ValueError
|
If the number of columns from |
Source code in sklego/preprocessing/dictmapper.py
sklego.preprocessing.identitytransformer.IdentityTransformer
¶
Bases: BaseEstimator
, TransformerMixin
The IdentityTransformer
returns what it is fed. Does not apply any transformation.
The reason for having it is because you can build more expressive pipelines.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
check_X
|
bool
|
Whether to validate |
False
|
Attributes:
Name | Type | Description |
---|---|---|
n_samples_ |
int
|
The number of samples seen during |
n_features_in_ |
int
|
The number of features seen during |
shape_ |
tuple[int, int]
|
Deprecated, please use |
Examples:
import pandas as pd
from sklego.preprocessing import IdentityTransformer
df = pd.DataFrame({
"name": ["Swen", "Victor", "Alex"],
"length": [1.82, 1.85, 1.80],
"shoesize": [42, 44, 45]
})
IdentityTransformer().fit_transform(df)
# name length shoesize
# 0 Swen 1.82 42
# 1 Victor 1.85 44
# 2 Alex 1.80 45
#using check_X=True to validate `X` to be non-empty 2D array of finite values and attempt to cast `X` to float
IdentityTransformer(check_X=True).fit_transform(df.drop(columns="name"))
# array([[ 1.82, 42. ],
# [ 1.85, 44. ],
# [ 1.8 , 45. ]])
Source code in sklego/preprocessing/identitytransformer.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
|
shape_
property
¶
Returns the shape of the estimator.
fit(X, y=None)
¶
Check the input data if check_X
is enabled and and records its shape.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to fit. |
required |
y
|
array-like of shape (n_samples,)
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
IdentityTransformer
|
The fitted transformer. |
Source code in sklego/preprocessing/identitytransformer.py
transform(X)
¶
Performs identity "transformation" on X
- which is no transformation at all.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Input data. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples, n_features)
|
Unchanged input data. |
Raises:
Type | Description |
---|---|
ValueError
|
If the number of columns from |
Source code in sklego/preprocessing/identitytransformer.py
sklego.preprocessing.projections.InformationFilter
¶
Bases: BaseEstimator
, TransformerMixin
The InformationFilter
transformer uses a variant of the
Gram-Schmidt process to filter information out of the
dataset.
This can be useful if you want to filter information out of a dataset because of fairness.
To explain how it works: given a training matrix \(X\) that contains columns \(x_1, ..., x_k\). If we assume columns \(x_1\) and \(x_2\) to be the sensitive columns then the information-filter will remove information by applying these transformations:
Concatenating our vectors (but removing the sensitive ones) gives us a new training matrix
Parameters:
Name | Type | Description | Default |
---|---|---|---|
columns
|
int | str | Sequence[int] | Sequence[str]
|
The columns to filter out. This can be a sequence of either int (in the case of numpy) or string (in the case of pandas). |
required |
alpha
|
float
|
Parameter to control how much to filter:
Should be between 0 and 1. |
1.0
|
Attributes:
Name | Type | Description |
---|---|---|
projection_ |
array-like of shape (n_features, n_features)
|
The projection matrix that can be used to filter information out of a dataset. |
col_ids_ |
List[int] of length `len(columns)`
|
The list of column ids of the sensitive columns. |
Examples:
import pandas as pd
from sklego.preprocessing import InformationFilter
df = pd.DataFrame({
"user_id": [101, 102, 103],
"length": [1.82, 1.85, 1.80],
"age": [21, 37, 45]
})
InformationFilter(columns=["length", "age"], alpha=0.5).fit_transform(df)
# array([[50.10152483, 3.87905643],
# [50.26253897, 19.59684308],
# [52.66084873, 28.06719867]])
Source code in sklego/preprocessing/projections.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 |
|
fit(X, y=None)
¶
Fit the transformer by learning the projection required to make the dataset orthogonal to sensitive columns.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to fit. |
required |
y
|
array-like of shape (n_samples,)
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
InformationFilter
|
The fitted transformer. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
Source code in sklego/preprocessing/projections.py
transform(X)
¶
Transforms X
by applying the information filter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to transform. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples, n_features)
|
The transformed data. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
Source code in sklego/preprocessing/projections.py
sklego.preprocessing.intervalencoder.IntervalEncoder
¶
Bases: TransformerMixin
, BaseEstimator
The IntervalEncoder
transformer bends features in X
with regards toy
.
We take each column in X
separately and smooth it towards y
using the strategy that is defined in method
.
Note that this allows us to make certain features strictly monotonic in your machine learning model if you follow this with an appropriate model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_chunks
|
int
|
The number of cuts that makes the interval. |
10
|
span
|
float
|
A hyperparameter for the interpolation method, if the method is |
1.0
|
method
|
Literal[average, normal, increasing, decreasing]
|
The interpolation method used, can be either |
"normal"
|
Attributes:
Name | Type | Description |
---|---|---|
quantiles_ |
np.ndarray of shape (n_features, n_chunks)
|
The quantiles that are used to cut the interval. |
heights_ |
np.ndarray of shape (n_features, n_chunks)
|
The heights of the quantiles that are used to cut the interval. |
n_features_in_ |
int
|
Number of features seen during |
num_cols_ |
int
|
Deprecated, please use |
Source code in sklego/preprocessing/intervalencoder.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
|
fit(X, y)
¶
Fit the IntervalEncoder
transformer by computing interpolation quantiles for each column of X
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
required |
Returns:
Name | Type | Description |
---|---|---|
self |
IntervalEncoder
|
The fitted transformer. |
Raises:
Type | Description |
---|---|
ValueError
|
|
Source code in sklego/preprocessing/intervalencoder.py
transform(X)
¶
Performs smoothing on the column(s) of X
according to the quantile values computed during fitting.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data for which the smoothing will be applied. |
required |
Returns:
Name | Type | Description |
---|---|---|
X |
np.ndarray of shape (n_samples, n_features)
|
|
Raises:
Type | Description |
---|---|
ValueError
|
If the number of columns from |
Source code in sklego/preprocessing/intervalencoder.py
sklego.preprocessing.formulaictransformer.FormulaicTransformer
¶
Bases: TransformerMixin
, BaseEstimator
The FormulaicTransformer
offers a method to select the right columns from a dataframe as well as a DSL for
transformations.
It is inspired from R formulas. This is can be useful as a first step in the pipeline.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
formula
|
str
|
A formulaic-compatible formula. Refer to the formulaic documentation for more details. |
required |
return_type
|
Literal[pandas, numpy, sparse]
|
The type of the returned matrix. Refer to the formulaic documentation for more details. |
"numpy"
|
Attributes:
Name | Type | Description |
---|---|---|
formula_ |
Formula
|
The parsed formula specification. |
model_spec_ |
ModelSpec
|
The parsed model specification. |
n_features_in_ |
int
|
Number of features seen during |
Examples:
import formulaic
import pandas as pd
import numpy as np
from sklego.preprocessing import FormulaicTransformer
df = pd.DataFrame({
'a': ['A', 'B', 'C'],
'b': [0.3, 0.1, 0.2],
})
#default type of returned matrix - numpy
FormulaicTransformer("a + b + a:b").fit_transform(df)
# array([[1. , 0. , 0. , 0.3, 0. , 0. ],
# [1. , 1. , 0. , 0.1, 0.1, 0. ],
# [1. , 0. , 1. , 0.2, 0. , 0.2]])
#pandas return type
FormulaicTransformer("a + b + a:b", "pandas").fit_transform(df)
# Intercept a[T.B] a[T.C] b a[T.B]:b a[T.C]:b
#0 1.0 0 0 0.3 0.0 0.0
#1 1.0 1 0 0.1 0.1 0.0
#2 1.0 0 1 0.2 0.0 0.2
Source code in sklego/preprocessing/formulaictransformer.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
|
fit(X, y=None)
¶
Fit the FormulaicTransformer
to the data by compiling the formula specification into a model spec.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
pd.DataFrame of (n_samples, n_features)
|
The data used to compile model spec. |
required |
y
|
array-like of shape (n_samples,)
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
FormulaicTransformer
|
The fitted transformer. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
Source code in sklego/preprocessing/formulaictransformer.py
transform(X, y=None)
¶
Transform X
by generating a model matrix from it based on the fit model spec.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
pd.DataFrame of shape (n_samples, n_features)
|
The data for transformation will be applied. |
required |
y
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
X |
array-like of shape (n_samples, n_features), and type `return_type`
|
Transformed data. |
Raises:
Type | Description |
---|---|
ValueError
|
If the number of columns from |
Source code in sklego/preprocessing/formulaictransformer.py
sklego.preprocessing.monotonicspline.MonotonicSplineTransformer
¶
Bases: TransformerMixin
, BaseEstimator
The MonotonicSplineTransformer
integrates the output of the SplineTransformer
in an attempt to make monotonic features.
This estimator is heavily inspired by this blogpost by Mate Kadlicsko.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_knots
|
int
|
The number of knots to use in the spline transformation. |
3
|
degree
|
int
|
The polynomial degree to use in the spline transformation |
3
|
knots
|
Literal[uniform, quantile]
|
Knots argument of spline transformer |
"uniform"
|
Attributes:
Name | Type | Description |
---|---|---|
spline_transformer_ |
trained SplineTransformer
|
|
features_in_ |
int
|
The number of features seen in the training data. |
Source code in sklego/preprocessing/monotonicspline.py
fit(X, y=None)
¶
Fit the MonotonicSplineTransformer
transformer by computing the spline transformation of X
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to transform. |
required |
y
|
array-like of shape (n_samples,)
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
MonotonicSplineTransformer
|
The fitted transformer. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
Source code in sklego/preprocessing/monotonicspline.py
transform(X)
¶
Performs the Ispline transformation on X
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
|
required |
Returns:
Name | Type | Description |
---|---|---|
X |
np.ndarray of shape (n_samples, n_out)
|
Transformed |
Raises:
Type | Description |
---|---|
ValueError
|
If the number of columns from |
Source code in sklego/preprocessing/monotonicspline.py
sklego.preprocessing.projections.OrthogonalTransformer
¶
Bases: BaseEstimator
, TransformerMixin
The OrthogonalTransformer
transforms the columns of a dataframe or numpy array to orthogonal (or
orthonormal if normalize=True
) matrix.
It learns matrices \(Q, R\) such that \(X = Q \cdot R\), with \(Q\) orthogonal, from which follows \(Q = X \cdot R^{-1}\)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
normalize
|
bool
|
Whether or not orthogonal matrix should be orthonormal as well. |
False
|
Attributes:
Name | Type | Description |
---|---|---|
inv_R_ |
array-like of shape (n_features, n_features)
|
The inverse of R of the QR decomposition of |
normalization_vector_ |
array-like of shape (n_features,)
|
The normalization terms to make the orthogonal matrix orthonormal. |
Examples:
from sklearn.datasets import make_regression
from sklego.preprocessing import OrthogonalTransformer
# Generate a synthetic dataset
X, y = make_regression(n_samples=100, n_features=3, noise=0.1, random_state=42)
# Instantiate the transformer
transformer = OrthogonalTransformer(normalize=True)
# Fit the pipeline with the training data
transformer.fit(X)
# Transform the data using the fitted transformer
X_transformed = transformer.transform(X)
Source code in sklego/preprocessing/projections.py
fit(X, y=None)
¶
Fit the transformer to the input data by calculating the inverse of R of the QR decomposition of X
.
This can be used to calculate the orthogonal projection of X
.
If normalization is required, also stores a vector with normalization terms.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to fit. |
required |
y
|
array-like of shape (n_samples,)
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
OrthogonalTransformer
|
The fitted transformer. |
Source code in sklego/preprocessing/projections.py
transform(X)
¶
Transforms X
using the fitted inverse of R. Normalizes the result if required.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to transform. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples, n_features)
|
The transformed data. |
Source code in sklego/preprocessing/projections.py
sklego.preprocessing.outlier_remover.OutlierRemover
¶
Bases: TrainOnlyTransformerMixin
, BaseEstimator
The OutlierRemover
transformer removes outliers (train-time only) using the supplied removal model. The
removal model should implement .fit()
and .predict()
methods.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
outlier_detector
|
scikit-learn compatible estimator
|
An outlier detector that implements |
required |
refit
|
bool
|
Whether or not to fit the underlying estimator during |
True
|
Attributes:
Name | Type | Description |
---|---|---|
estimator_ |
object
|
The fitted outlier detector. |
Examples:
import numpy as np
from sklearn.ensemble import IsolationForest
from sklego.preprocessing import OutlierRemover
np.random.seed(0)
X = np.random.randn(10000, 2)
isolation_forest = IsolationForest()
isolation_forest.fit(X)
detector_preds = isolation_forest.predict(X)
outlier_remover = OutlierRemover(isolation_forest, refit=True)
outlier_remover.fit(X)
X_trans = outlier_remover.transform_train(X)
Source code in sklego/preprocessing/outlier_remover.py
fit(X, y=None)
¶
Fit the estimator on training data X
and y
by fitting the underlying outlier detector if refit
is True.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
OutlierRemover
|
The fitted transformer. |
Source code in sklego/preprocessing/outlier_remover.py
transform_train(X)
¶
Removes outliers from X
using the fitted estimator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data for which the outliers will be removed. |
required |
Returns:
Type | Description |
---|---|
np.ndarray of shape (n_not_outliers, n_features)
|
The data with the outliers removed, where |
Source code in sklego/preprocessing/outlier_remover.py
sklego.preprocessing.pandastransformers.PandasTypeSelector
¶
Bases: TypeSelector
Deprecated since version 0.9.0, please use TypeSelector instead
Source code in sklego/preprocessing/pandastransformers.py
sklego.preprocessing.randomadder.RandomAdder
¶
Bases: TrainOnlyTransformerMixin
, BaseEstimator
The RandomAdder
transformer adds random noise to the input data.
This class is designed to be used during the training phase and not for transforming test data.
Noise added is sampled from a normal distribution with mean 0 and standard deviation noise
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
noise
|
float
|
The standard deviation of the normal distribution from which the noise is sampled. |
1.0
|
random_state
|
int | None
|
The seed used by the random number generator. |
None
|
Attributes:
Name | Type | Description |
---|---|---|
n_features_in_ |
int
|
Number of features seen during |
dim_ |
int
|
Deprecated, please use |
Examples:
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
from sklego.preprocessing import RandomAdder
# Create a pipeline with the RandomAdder and a LinearRegression model
pipeline = Pipeline([
('random_adder', RandomAdder(noise=0.5, random_state=42)),
('linear_regression', LinearRegression())
])
# Fit the pipeline with training data
pipeline.fit(X_train, y_train)
# Use the fitted pipeline to make predictions
y_pred = pipeline.predict(X_test)
Source code in sklego/preprocessing/randomadder.py
fit(X, y)
¶
Fit the transformer on training data X
and y
by checking the input data and record the number of
input features.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
required |
Returns:
Name | Type | Description |
---|---|---|
self |
RandomAdder
|
The fitted transformer. |
Source code in sklego/preprocessing/randomadder.py
transform_train(X)
¶
Transform training data by adding random noise sampled from \(N(0, \text{noise})\).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data for which the noise will be added. |
required |
Returns:
Type | Description |
---|---|
np.ndarray of shape (n_samples, n_features)
|
The data with the noise added. |
Source code in sklego/preprocessing/randomadder.py
sklego.preprocessing.repeatingbasis.RepeatingBasisFunction
¶
Bases: TransformerMixin
, BaseEstimator
The RepeatingBasisFunction
transformer is designed to be used when the input data has a circular nature.
For example, for days of the week you might face the problem that, conceptually, day 7 is as close to day 6 as it is to day 1. While numerically their distance is different.
This transformer remedies that problem. The transformer selects a column and transforms it with a given number of repeating (radial) basis functions.
Radial basis functions are bell-curve shaped functions which take the original data as input. The basis functions are equally spaced over the input range. The key feature of repeating basis functions is that they are continuous when moving from the max to the min of the input range. As a result these repeating basis functions can capture how close each datapoint is to the center of each repeating basis function, even when the input data has a circular nature.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column
|
int | str
|
Index or column name of the data to transform. Integers are interpreted as positional columns, while strings can reference DataFrame columns by name. |
0
|
remainder
|
Literal[drop, passthrough]
|
By default, only the specified column is transformed, and the non-specified columns are dropped.
By specifying |
"drop"
|
n_periods
|
int
|
Number of basis functions to create, i.e., the number of columns that will exit the transformer. |
12
|
input_range
|
Tuple[float, float] | List[float] | None
|
The values at which the data repeats itself. For example, for days of the week this is (1,7).
If |
None
|
width
|
float
|
Determines the width of the radial basis functions. |
1.0.
|
Attributes:
Name | Type | Description |
---|---|---|
pipeline_ |
ColumnTransformer
|
Fitted |
Examples:
import pandas as pd
from sklego.preprocessing import RepeatingBasisFunction
df = pd.DataFrame({
"user_id": [101, 102, 103],
"created_day": [5, 1, 7]
})
RepeatingBasisFunction(column="created_day", input_range=(1,7)).fit_transform(df)
# array([[0.06217652, 0.00432024, 0.16901332, 0.89483932, 0.64118039],
# [1. , 0.36787944, 0.01831564, 0.01831564, 0.36787944],
# [1. , 0.36787944, 0.01831564, 0.01831564, 0.36787944]])
Source code in sklego/preprocessing/repeatingbasis.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
|
fit(X, y=None)
¶
Fit RepeatingBasisFunction
transformer on input data X
.
It uses sklearn.compose.ColumnTransformer
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data used to compute the quantiles for capping. |
required |
y
|
array-like of shape (n_samples,)
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
RepeatingBasisFunction
|
The fitted transformer. |
Source code in sklego/preprocessing/repeatingbasis.py
transform(X)
¶
Transform input data X
with fitted RepeatingBasisFunction
transformer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to transform. |
required |
Returns:
Name | Type | Description |
---|---|---|
X_transformed |
array-like of shape (n_samples, n_periods)
|
Transformed data. |
Source code in sklego/preprocessing/repeatingbasis.py
sklego.preprocessing.pandastransformers.TypeSelector
¶
Bases: BaseEstimator
, TransformerMixin
The TypeSelector
transformer allows to select columns in a DataFrame based on their type.
Can be useful in a sklearn Pipeline.
- For pandas, it uses pandas.DataFrame.select_dtypes method.
-
For non-pandas dataframes (e.g. Polars), the following inputs are allowed:
- 'number'
- 'string'
- 'bool'
- 'category'
New in version 0.9.0
Notes
Native cross-dataframe support is achieved using Narwhals.
Supported dataframes are:
- pandas
- Polars (eager or lazy)
- Modin
- cuDF
See Narwhals docs for an up-to-date list (and to learn how you can add your dataframe library to it!).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
include
|
scalar or list - like
|
Column type(s) to be selected |
None
|
exclude
|
scalar or list - like
|
Column type(s) to be excluded from selection |
None
|
Attributes:
Name | Type | Description |
---|---|---|
feature_names_ |
list[str]
|
The names of the features to keep during transform. |
X_dtypes_ |
Series | dict[str, DType]
|
The dtypes of the columns in the input DataFrame. |
!!! warning |
Raises a |
Examples:
import pandas as pd
from sklego.preprocessing import TypeSelector
df = pd.DataFrame({
"name": ["Swen", "Victor", "Alex"],
"length": [1.82, 1.85, 1.80],
"shoesize": [42, 44, 45]
})
#Excluding single column
TypeSelector(exclude="int64").fit_transform(df)
# name length
#0 Swen 1.82
#1 Victor 1.85
#2 Alex 1.80
#Including multiple columns
TypeSelector(include=["int64", "object"]).fit_transform(df)
# name shoesize
#0 Swen 42
#1 Victor 44
#2 Alex 45
Source code in sklego/preprocessing/pandastransformers.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
|
fit(X, y=None)
¶
Fit the transformer by saving the column names to keep during transform.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
DataFrame
|
The data on which we apply the column selection. |
required |
y
|
Series
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
TypeSelector
|
The fitted transformer. |
Raises:
Type | Description |
---|---|
TypeError
|
If |
ValueError
|
If provided type(s) results in empty dataframe. |
Source code in sklego/preprocessing/pandastransformers.py
get_feature_names(*args, **kwargs)
¶
transform(X)
¶
Returns a DataFrame with columns (de)selected based on their dtype.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
DataFrame
|
The data to select dtype for. |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
The data with the specified columns selected. |
Raises:
Type | Description |
---|---|
TypeError
|
If |
ValueError
|
If column dtypes were not equal during fit and transform. |