Time-related feature engineering from sklearn.datasets import fetch_openml
bike_sharing = fetch_openml ( "Bike_Sharing_Demand" , version = 2 , as_frame = True )
df = bike_sharing . frame
To get a quick understanding of the periodic patterns of the data, let us
have a look at the average demand per hour during a week.
Note that the week starts on a Sunday, during the weekend. We can clearly
distinguish the commute patterns in the morning and evenings of the work days
and the leisure use of the bikes on the weekends with a more spread peak
demand around the middle of the days:
import matplotlib.pyplot as plt
fig , ax = plt . subplots ( figsize = ( 12 , 4 ))
average_week_demand = df . groupby ([ "weekday" , "hour" ])[ "count" ] . mean ()
average_week_demand . plot ( ax = ax )
_ = ax . set (
title = "Average hourly bike demand during the week" ,
xticks = [ i * 24 for i in range ( 7 )],
xticklabels = [ "Sun" , "Mon" , "Tue" , "Wed" , "Thu" , "Fri" , "Sat" ],
xlabel = "Time of the week" ,
ylabel = "Number of bike rentals" ,
)
The target of the prediction problem is the absolute count of bike rentals on
an hourly basis:
Let us rescale the target variable (number of hourly bike rentals) to predict
a relative demand so that the mean absolute error is more easily interpreted
as a fraction of the maximum demand.
The fit method of the models used in this notebook all minimizes the
mean squared error to estimate the conditional mean.
The absolute error, however, would estimate the conditional median.
Nevertheless, when reporting performance measures on the test set in
the discussion, we choose to focus on the mean absolute error instead
of the (root) mean squared error because it is more intuitive to
interpret. Note, however, that in this study the best models for one
metric are also the best ones in terms of the other metric.
y = df [ "count" ] / df [ "count" ] . max ()
fig , ax = plt . subplots ( figsize = ( 12 , 4 ))
y . hist ( bins = 30 , ax = ax )
_ = ax . set (
xlabel = "Fraction of rented fleet demand" ,
ylabel = "Number of hours" ,
)
The input feature data frame is a time annotated hourly log of variables
describing the weather conditions. It includes both numerical and categorical
variables. Note that the time information has already been expanded into
several complementary columns.
X = df . drop ( "count" , axis = "columns" )
X
season year month hour holiday weekday workingday weather temp feel_temp humidity windspeed 0 spring 0 1 0 False 6 False clear 9.84 14.395 0.81 0.0000 1 spring 0 1
17379 rows × 12 columns
We now introspect the distribution of the categorical variables, starting
with "weather" :
X [ "weather" ] . value_counts ()
weather
clear 11413
misty 4544
rain 1419
heavy_rain 3
Name: count, dtype: int64
Since there are only 3 "heavy_rain" events, we cannot use this category to
train machine learning models with cross validation. Instead, we simplify the
representation by collapsing those into the "rain" category.
X [ "weather" ] = (
X [ "weather" ]
. astype ( object )
. replace ( to_replace = "heavy_rain" , value = "rain" )
. astype ( "category" )
)
X [ "weather" ] . value_counts ()
weather
clear 11413
misty 4544
rain 1422
Name: count, dtype: int64
As expected, the "season" variable is well balanced:
X [ "season" ] . value_counts ()
season
fall 4496
summer 4409
spring 4242
winter 4232
Name: count, dtype: int64
Modeling non-linear feature interactions with kernels
The previous analysis highlighted the need to model the interactions between
"workingday" and "hours" . Another example of a such a non-linear
interaction that we would like to model could be the impact of the rain that
might not be the same during the working days and the week-ends and holidays
for instance.
To model all such interactions, we could either use a polynomial expansion on
all marginal features at once, after their spline-based expansion. However,
this would create a quadratic number of features which can cause overfitting
and computational tractability issues.
Alternatively, we can use the Nyström method to compute an approximate
polynomial kernel expansion. Let us try the latter:
from sklearn.kernel_approximation import Nystroem
cyclic_spline_poly_pipeline = make_pipeline (
cyclic_spline_transformer ,
Nystroem ( kernel = "poly" , degree = 2 , n_components = 300 , random_state = 0 ),
RidgeCV ( alphas = alphas ),
)
evaluate ( cyclic_spline_poly_pipeline , X , y , cv = ts_cv )
Mean Absolute Error: 0.053 +/- 0.002
Root Mean Squared Error: 0.076 +/- 0.004
We observe that this model can almost rival the performance of the gradient
boosted trees with an average error around 5% of the maximum demand.
Note that while the final step of this pipeline is a linear regression model,
the intermediate steps such as the spline feature extraction and the Nyström
kernel approximation are highly non-linear. As a result the compound pipeline
is much more expressive than a simple linear regression model with raw features.
For the sake of completeness, we also evaluate the combination of one-hot
encoding and kernel approximation:
one_hot_poly_pipeline = make_pipeline (
ColumnTransformer (
transformers = [
( "categorical" , one_hot_encoder , categorical_columns ),
( "one_hot_time" , one_hot_encoder , [ "hour" , "weekday" , "month" ]),
Mean Absolute Error: 0.082 +/- 0.006
Root Mean Squared Error: 0.111 +/- 0.011
While one-hot encoded features were competitive with spline-based features
when using linear models, this is no longer the case when using a low-rank
approximation of a non-linear kernel: this can be explained by the fact that
spline features are smoother and allow the kernel approximation to find a
more expressive decision function.
Let us now have a qualitative look at the predictions of the kernel models
and of the gradient boosted trees that should be able to better model
non-linear interactions between features:
gbrt . fit ( X . iloc [ train_0 ], y . iloc [ train_0 ])
gbrt_predictions = gbrt . predict ( X . iloc [ test_0 ])
one_hot_poly_pipeline . fit ( X . iloc [ train_0 ], y
Again we zoom on the last 4 days of the test set:
last_hours = slice ( - 96 , None )
fig , ax = plt . subplots ( figsize = ( 12 , 4 ))
fig . suptitle ( "Predictions by non-linear regression models" )
ax . plot (
First, note that trees can naturally model non-linear feature interactions
since, by default, decision trees are allowed to grow beyond a depth of 2
levels.
Here, we can observe that the combinations of spline features and non-linear
kernels works quite well and can almost rival the accuracy of the gradient
boosting regression trees.
On the contrary, one-hot encoded time features do not perform that well with
the low rank kernel model. In particular, they significantly over-estimate
the low demand hours more than the competing models.
We also observe that none of the models can successfully predict some of the
peak rentals at the rush hours during the working days. It is possible that
access to additional features would be required to further improve the
accuracy of the predictions. For instance, it could be useful to have access
to the geographical repartition of the fleet at any point in time or the
fraction of bikes that are immobilized because they need servicing.
Let us finally get a more quantitative look at the prediction errors of those
three models using the true vs predicted demand scatter plots:
from sklearn.metrics import PredictionErrorDisplay
fig , axes = plt . subplots ( nrows = 2 , ncols = 3 , figsize = ( 13 , 7 ), sharex = True , sharey =
This visualization confirms the conclusions we draw on the previous plot.
All models under-estimate the high demand events (working day rush hours),
but gradient boosting a bit less so. The low demand events are well predicted
on average by gradient boosting while the one-hot polynomial regression
pipeline seems to systematically over-estimate demand in that regime. Overall
the predictions of the gradient boosted trees are closer to the diagonal than
for the kernel models.
2 spring 0 1 2 False 6 False clear 9.02 13.635 0.80 0.0000
3 spring 0 1 3 False 6 False clear 9.84 14.395 0.75 0.0000
4 spring 0 1 4 False 6 False clear 9.84 14.395 0.75 0.0000
... ... ... ... ... ... ... ... ... ... ... ... ...
17374 spring 1 12 19 False 1 True misty 10.66 12.880 0.60 11.0014
17375 spring 1 12 20 False 1 True misty 10.66 12.880 0.60 11.0014
17376 spring 1 12 21 False 1 True clear 10.66 12.880 0.60 11.0014
17377 spring 1 12 22 False 1 True clear 10.66 13.635 0.56 8.9981
17378 spring 1 12 23 False 1 True clear 10.66 13.635 0.65 8.9981
12379 summer 1 6 0 False 2 True clear 22.14 25.760 0.68 27.9993 12380 summer 1 6 1 False 2 True misty 21.32 25.000 0.77 22.0028 12381 summer 1 6 2 False 2 True rain 21.32 25.000 0.72 19.9995 12382 summer 1 6 3 False 2 True rain 20.50 24.240 0.82 12.9980 12383 summer 1 6 4 False 2 True rain 20.50 24.240 0.82 12.9980 ... ... ... ... ... ... ... ... ... ... ... ... ... 13374 fall 1 7 11 False 1 True clear 34.44 40.150 0.53 15.0013 13375 fall 1 7 12 False 1 True clear 34.44 39.395 0.49 8.9981 13376 fall 1 7 13 False 1 True clear 34.44 39.395 0.49 19.0012 13377 fall 1 7 14 False 1 True clear 36.08 40.910 0.42 7.0015 13378 fall 1 7 15 False 1 True clear 35.26 40.150 0.47 16.9979
2331 summer 0 4 1 False 2 True misty 25.42 31.060 0.50 6.0032 2332 summer 0 4 2 False 2 True misty 24.60 31.060 0.53 8.9981 2333 summer 0 4 3 False 2 True misty 23.78 27.275 0.56 8.9981 2334 summer 0 4 4 False 2 True misty 22.96 26.515 0.64 8.9981 2335 summer 0 4 5 False 2 True misty 22.14 25.760 0.68 8.9981 ... ... ... ... ... ... ... ... ... ... ... ... ... 12326 summer 1 6 19 False 6 False clear 26.24 31.060 0.36 11.0014 12327 summer 1 6 20 False 6 False clear 25.42 31.060 0.35 19.0012 12328 summer 1 6 21 False 6 False clear 24.60 31.060 0.40 7.0015 12329 summer 1 6 22 False 6 False clear 23.78 27.275 0.46 8.9981 12330 summer 1 6 23 False 6 False clear 22.96 26.515 0.52 7.0015
16379 winter 1 11 5 False 2 True misty 13.94 16.665 0.66 8.9981 16380 winter 1 11 6 False 2 True misty 13.94 16.665 0.71 11.0014 16381 winter 1 11 7 False 2 True clear 13.12 16.665 0.76 6.0032 16382 winter 1 11 8 False 2 True clear 13.94 16.665 0.71 8.9981 16383 winter 1 11 9 False 2 True misty 14.76 18.940 0.71 0.0000 ... ... ... ... ... ... ... ... ... ... ... ... ... 17374 spring 1 12 19 False 1 True misty 10.66 12.880 0.60 11.0014 17375 spring 1 12 20 False 1 True misty 10.66 12.880 0.60 11.0014 17376 spring 1 12 21 False 1 True clear 10.66 12.880 0.60 11.0014 17377 spring 1 12 22 False 1 True clear 10.66 13.635 0.56 8.9981 17378 spring 1 12 23 False 1 True clear 10.66 13.635 0.65 8.9981
6331 winter 0 9 9 False 1 True misty 26.24 28.790 0.89 12.9980 6332 winter 0 9 10 False 1 True misty 26.24 28.790 0.89 12.9980 6333 winter 0 9 11 False 1 True clear 27.88 31.820 0.79 15.0013 6334 winter 0 9 12 False 1 True misty 27.88 31.820 0.79 11.0014 6335 winter 0 9 13 False 1 True misty 28.70 33.335 0.74 11.0014 ... ... ... ... ... ... ... ... ... ... ... ... ... 16326 winter 1 11 0 False 0 False misty 12.30 15.150 0.70 11.0014 16327 winter 1 11 1 False 0 False clear 12.30 14.395 0.70 12.9980 16328 winter 1 11 2 False 0 False clear 11.48 14.395 0.81 7.0015 16329 winter 1 11 3 False 0 False misty 12.30 15.150 0.81 11.0014 16330 winter 1 11 4 False 0 False misty 12.30 14.395 0.81 12.9980
y
,
cv
=
cv
,
scoring
=
[
"neg_mean_absolute_error"
,
"neg_root_mean_squared_error"
],
return_estimator
=
True
,
)
if
model_prop
is
not
None
:
if
model_step
is
not
None
:
values
=
[
getattr
(
m
[
model_step
],
model_prop
)
for
m
in
cv_results
[
"estimator"
]
]
else
:
values
=
[
getattr
(
m
,
model_prop
)
for
m
in
cv_results
[
"estimator"
]]
print
(
f
"Mean model.
{
model_prop
}
=
{
(
values
)
}
"
)
mae
=
-
cv_results
[
"test_neg_mean_absolute_error"
]
rmse
=
-
cv_results
[
"test_neg_root_mean_squared_error"
]
print
(
f
"Mean Absolute Error:
{
mae
.
mean
()
:
.3f
}
+/-
{
mae
.
std
()
:
.3f
}
\n
"
f
"Root Mean Squared Error:
{
rmse
.
mean
()
:
.3f
}
+/-
{
rmse
.
std
()
:
.3f
}
"
)
return
cv_results
[
"estimator"
][
0
]
evaluate
(
gbrt
,
X
,
y
,
cv
=
ts_cv
,
model_prop
=
"n_iter_"
)
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>`.
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
Fitted attributes
Name Type Value
do_early_stopping_
do_early_stopping_: bool Indicates whether early stopping is used during training.
bool False
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](12,) ['season','year','month',...,'feel_temp','humidity','windspeed']
is_categorical_
is_categorical_: ndarray, shape (n_features, ) or None Boolean mask for the categorical features. ``None`` if there are no categorical features.
ndarray[bool](12,) [ True,False,False,...,False,False,False]
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 0.24
int 12
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 100
n_trees_per_iteration_
n_trees_per_iteration_: int The number of tree that are built at each iteration. For regressors, this is always 1.
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](0,) []
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](0,) []
iFitted
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.
[('columntransformer', ...), ('ridgecv', ...)]
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
columntransformer: 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`.
[('categorical', ...)]
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.
MinMaxScaler()
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.
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
Index(['season', 'holiday', 'workingday', 'weather'], dtype='str')
19 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False workingday_True weather_clear
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.
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.
[('columntransformer', ...), ('ridgecv', ...)]
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
columntransformer: 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`.
hour_df
[
"hour_sin"
]
=
sin_transformer
(
24
)
.
fit_transform
(
hour_df
)[
"hour"
]
hour_df
[
"hour_cos"
]
=
cos_transformer
(
24
)
.
fit_transform
(
hour_df
)[
"hour"
]
hour_df
.
plot
(
x
=
"hour"
)
_
=
(
"Trigonometric encoding for the 'hour' feature"
)
ax
.
set
(
xlabel
=
"sin(hour)"
,
ylabel
=
"cos(hour)"
,
)
_
=
fig
.
colorbar
(
sp
)
]),
(
"weekday_sin"
,
sin_transformer
(
7
),
[
"weekday"
]),
(
"weekday_cos"
,
cos_transformer
(
7
),
[
"weekday"
]),
(
"hour_sin"
,
sin_transformer
(
24
),
[
"hour"
]),
(
"hour_cos"
,
cos_transformer
(
24
),
[
"hour"
]),
],
remainder
=
(),
verbose_feature_names_out
=
True
,
)
cyclic_cossin_linear_pipeline
=
(
cyclic_cossin_transformer
,
(
alphas
=
alphas
),
)
evaluate
(
cyclic_cossin_linear_pipeline
,
X
,
y
,
cv
=
ts_cv
)
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.
[('columntransformer', ...), ('ridgecv', ...)]
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
columntransformer: 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`.
periodic_spline_transformer
(
24
,
n_splines
=
12
)
.
fit_transform
(
hour_df
)
splines_df
=
(
splines
,
columns
=
[
f
"spline_
{
i
}
"
for
i
in
range
(
splines
.
shape
[
1
])],
)
([
hour_df
,
splines_df
],
axis
=
"columns"
)
.
plot
(
x
=
"hour"
,
cmap
=
plt
.
cm
.
tab20b
)
_
=
(
"Periodic spline-based encoding for the 'hour' feature"
)
(
7
,
n_splines
=
3
),
[
"weekday"
]),
(
"cyclic_hour"
,
periodic_spline_transformer
(
24
,
n_splines
=
12
),
[
"hour"
]),
],
remainder
=
(),
verbose_feature_names_out
=
False
,
)
cyclic_spline_linear_pipeline
=
(
cyclic_spline_transformer
,
(
alphas
=
alphas
),
)
evaluate
(
cyclic_spline_linear_pipeline
,
X
,
y
,
cv
=
ts_cv
)
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.
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.
[('columntransformer', ...), ('ridgecv', ...)]
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
columntransformer: 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`.
.
iloc
[
test_0
]
.
values
[
last_hours
],
"x-"
,
alpha
=
0.2
,
label
=
"Actual demand"
,
color
=
"black"
,
)
ax
.
plot
(
naive_linear_predictions
[
last_hours
],
"x-"
,
label
=
"Ordinal time features"
)
ax
.
plot
(
cyclic_cossin_linear_predictions
[
last_hours
],
"x-"
,
label
=
"Trigonometric time features"
,
)
ax
.
plot
(
cyclic_spline_linear_predictions
[
last_hours
],
"x-"
,
label
=
"Spline-based time features"
,
)
ax
.
plot
(
one_hot_linear_predictions
[
last_hours
],
"x-"
,
label
=
"One-hot time features"
,
)
_
=
ax
.
legend
()
"pandas"
),
(
alphas
=
alphas
),
)
evaluate
(
cyclic_spline_interactions_pipeline
,
X
,
y
,
cv
=
ts_cv
)
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.
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.
[('featureunion', ...), ('ridgecv', ...)]
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
featureunion: FeatureUnion
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.
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.
[('columntransformer', ...), ('nystroem', ...), ...]
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
columntransformer: 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`.
],
remainder
=
"passthrough"
,
verbose_feature_names_out
=
False
,
),
(
kernel
=
"poly"
,
degree
=
2
,
n_components
=
300
,
random_state
=
0
),
(
alphas
=
alphas
),
)
.
set_output
(
transform
=
"pandas"
)
evaluate
(
one_hot_poly_pipeline
,
X
,
y
,
cv
=
ts_cv
)
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.
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.
[('columntransformer', ...), ('nystroem', ...), ...]
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
columntransformer: 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`.
.
iloc
[
train_0
])
one_hot_poly_predictions
=
one_hot_poly_pipeline
.
predict
(
X
.
iloc
[
test_0
])
cyclic_spline_poly_pipeline
.
fit
(
X
.
iloc
[
train_0
],
y
.
iloc
[
train_0
])
cyclic_spline_poly_predictions
=
cyclic_spline_poly_pipeline
.
predict
(
X
.
iloc
[
test_0
])
y
.
iloc
[
test_0
]
.
values
[
last_hours
],
"x-"
,
alpha
=
0.2
,
label
=
"Actual demand"
,
color
=
"black"
,
)
ax
.
plot
(
gbrt_predictions
[
last_hours
],
"x-"
,
label
=
"Gradient Boosted Trees"
,
)
ax
.
plot
(
one_hot_poly_predictions
[
last_hours
],
"x-"
,
label
=
"One-hot + polynomial kernel"
,
)
ax
.
plot
(
cyclic_spline_poly_predictions
[
last_hours
],
"x-"
,
label
=
"Splines + polynomial kernel"
,
)
_
=
ax
.
legend
()
"row"
)
fig
.
suptitle
(
"Non-linear regression models"
,
y
=
1.0
)
predictions
=
[
one_hot_poly_predictions
,
cyclic_spline_poly_predictions
,
gbrt_predictions
,
]
labels
=
[
"One hot +
\n
polynomial kernel"
,
"Splines +
\n
polynomial kernel"
,
"Gradient Boosted
\n
Trees"
,
]
plot_kinds
=
[
"actual_vs_predicted"
,
"residual_vs_predicted"
]
for
axis_idx
,
kind
in
enumerate
(
plot_kinds
):
for
ax
,
pred
,
label
in
zip
(
axes
[
axis_idx
],
predictions
,
labels
):
disp
=
(
y_true
=
y
.
iloc
[
test_0
],
y_pred
=
pred
,
kind
=
kind
,
scatter_kwargs
=
{
"alpha"
:
0.3
},
ax
=
ax
,
)
ax
.
set_xticks
(
(
0
,
1
,
num
=
5
))
if
axis_idx
==
0
:
ax
.
set_yticks
(
(
0
,
1
,
num
=
5
))
ax
.
legend
(
[
"Best model"
,
label
],
loc
=
"upper center"
,
bbox_to_anchor
=
(
0.5
,
1.3
),
ncol
=
2
,
)
ax
.
set_aspect
(
"equal"
,
adjustable
=
"box"
)
()
Download zipped: plot_cyclical_feature_engineering.zip
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 [('ca...al', OneHotEncoder..._output=False), Index(['seaso..., dtype='str')), ('re...er', MinMaxScaler(), ['year', 'month', 'hour', 'weekday', ...])]
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`
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'
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(['fall'... dtype=object), array(['False... dtype=object), array(['False... dtype=object), array(['clear... 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](4,) ['season','holiday','workingday','weather']
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 1.0
int 4
11 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False workingday_True weather_clear weather_misty weather_rain
['year', 'month', 'hour', 'weekday', 'temp', 'feel_temp', 'humidity', 'windspeed']
8 features
year month hour weekday temp feel_temp humidity windspeed
array([1.0000...00000000e+06])
cv
cv: int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the efficient Leave-One-Out cross-validation - integer, to specify the number of folds, - :term:`CV splitter`, - an iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if ``y`` is binary or multiclass, :class:`~sklearn.model_selection.StratifiedKFold` is used, else, :class:`~sklearn.model_selection.KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here.
None
Fitted attributes
Name Type Value
alpha_
alpha_: float or ndarray of shape (n_targets,) Estimated regularization parameter, or, if ``alpha_per_target=True``, the estimated regularization parameter for each target.
float 3.162
best_score_
best_score_: float or ndarray of shape (n_targets,) Score of base estimator with best alpha, or, if ``alpha_per_target=True``, a score for each target. .. versionadded:: 0.23
float64 -0.01722
coef_
coef_: ndarray of shape (n_features) or (n_targets, n_features) Weight vector(s).
ndarray[float64](19,) [-0.03,-0.01, 0.01,..., 0.2 ,-0.16, 0.02]
intercept_
intercept_: float or ndarray of shape (n_targets,) Independent term in decision function. Set to 0.0 if ``fit_intercept = False``.
float64 -0.07789
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 0.24
int 19
[('categorical', ...), ('one_hot_time', ...)]
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.
False
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](12,) ['season','year','month',...,'feel_temp','humidity','windspeed']
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 12
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 {'categorical...inMaxScaler()}
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 {'ca...al': slice(0, 11, None), 'on...me': slice(11, 54, None), 're...er': slice(54, 59, 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 [('ca...al', OneHotEncoder..._output=False), Index(['seaso..., dtype='str')), ('on...me', OneHotEncoder..._output=False), ['hour', 'weekday', 'month']), ('re...er', MinMaxScaler(), ['year', 'temp', 'fe...mp', 'hu...ty', ...])]
Index(['season', 'holiday', 'workingday', 'weather'], dtype='str')
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.
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.
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'
11 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False workingday_True
['hour', 'weekday', 'month']['year', 'temp', 'feel_temp', 'humidity', 'windspeed']
59 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False workingday_True weather_clear weather_misty weather_rain hour_0 hour_1 hour_2 hour_3 hour_4 hour_5 hour_6 hour_7 hour_8 hour_9 hour_10 hour_11 hour_12 hour_13 hour_14 hour_15 hour_16 hour_17 hour_18 hour_19 hour_20 hour_21 hour_22 hour_23 weekday_0 weekday_1 weekday_2 weekday_3 weekday_4 weekday_5 weekday_6 month_1 month_2 month_3 month_4 month_5 month_6 month_7 month_8 month_9 month_10 month_11 month_12 year temp feel_temp humidity windspeed
Parameters
alphas
alphas: array-like of shape (n_alphas,), default=(0.1, 1.0, 10.0) Array of alpha values to try. Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to ``1 / (2C)`` in other linear models such as :class:`~sklearn.linear_model.LogisticRegression` or :class:`~sklearn.svm.LinearSVC`. If using Leave-One-Out cross-validation, alphas must be strictly positive. For an example on how regularization strength affects the model coefficients, see :ref:`sphx_glr_auto_examples_linear_model_plot_ridge_coeffs.py`.
array([1.0000...00000000e+06])
fit_intercept
fit_intercept: bool, default=True Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
True
scoring
scoring: str, callable, default=None The scoring method to use for cross-validation. 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`: negative :ref:`mean squared error <mean_squared_error>` if cv is None (i.e. when using leave-one-out cross-validation), or :ref:`coefficient of determination <r2_score>` (:math:`R^2`) otherwise.
None
cv
cv: int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the efficient Leave-One-Out cross-validation - integer, to specify the number of folds, - :term:`CV splitter`, - an iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if ``y`` is binary or multiclass, :class:`~sklearn.model_selection.StratifiedKFold` is used, else, :class:`~sklearn.model_selection.KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here.
None
gcv_mode
gcv_mode: {'auto', 'svd', 'eigen'}, default='auto' Flag indicating which strategy to use when performing Leave-One-Out Cross-Validation. Options are:: 'auto' : same as 'eigen' 'svd' : use singular value decomposition of X when X is dense, fallback to 'eigen' when X is sparse 'eigen' : use eigendecomposition of X X' when n_samples <= n_features or X' X when n_features < n_samples The 'auto' mode is the default and is intended to pick the cheaper option depending on the shape and sparsity of the training data.
None
store_cv_results
store_cv_results: bool, default=False Flag indicating if the cross-validation values corresponding to each alpha should be stored in the ``cv_results_`` attribute (see below). This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). .. versionchanged:: 1.5 Parameter name changed from `store_cv_values` to `store_cv_results`.
False
alpha_per_target
alpha_per_target: bool, default=False Flag indicating whether to optimize the alpha value (picked from the `alphas` parameter list) for each target separately (for multi-output settings: multiple prediction targets). When set to `True`, after fitting, the `alpha_` attribute will contain a value for each target. When set to `False`, a single alpha is used for all targets. This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). .. versionadded:: 0.24
False
[('categorical', ...), ('month_sin', ...), ...]
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](12,) ['season','year','month',...,'feel_temp','humidity','windspeed']
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 12
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 {'categorical...inMaxScaler()}
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 {'ca...al': slice(0, 11, None), 'ho...os': slice(16, 17, None), 'ho...in': slice(15, 16, None), 'mo...os': slice(12, 13, 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 [('ca...al', OneHotEncoder..._output=False), Index(['seaso..., dtype='str')), ('mo...in', FunctionTrans...7e1dbc43da60>), ['month']), ('mo...os', FunctionTrans...7e1dbc43db10>), ['month']), ('we...in', FunctionTrans...7e1dbc43dbc0>), ['weekday']), ...]
Index(['season', 'holiday', 'workingday', 'weather'], dtype='str')
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.
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.
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'
11 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False workingday_True
<lambda>
FunctionTransformer
<lambda>
FunctionTransformer
<lambda>
FunctionTransformer
<lambda>
FunctionTransformer
<lambda>
FunctionTransformer
<lambda>
FunctionTransformer
['year', 'temp', 'feel_temp', 'humidity', 'windspeed']
22 features
categorical__season_fall categorical__season_spring categorical__season_summer categorical__season_winter categorical__holiday_False categorical__holiday_True categorical__workingday_False categorical__workingday_True categorical__weather_clear categorical__weather_misty categorical__weather_rain month_sin__month month_cos__month weekday_sin__weekday weekday_cos__weekday hour_sin__hour hour_cos__hour remainder__year remainder__temp remainder__feel_temp remainder__humidity remainder__windspeed
Parameters
alphas
alphas: array-like of shape (n_alphas,), default=(0.1, 1.0, 10.0) Array of alpha values to try. Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to ``1 / (2C)`` in other linear models such as :class:`~sklearn.linear_model.LogisticRegression` or :class:`~sklearn.svm.LinearSVC`. If using Leave-One-Out cross-validation, alphas must be strictly positive. For an example on how regularization strength affects the model coefficients, see :ref:`sphx_glr_auto_examples_linear_model_plot_ridge_coeffs.py`.
array([1.0000...00000000e+06])
fit_intercept
fit_intercept: bool, default=True Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
True
scoring
scoring: str, callable, default=None The scoring method to use for cross-validation. 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`: negative :ref:`mean squared error <mean_squared_error>` if cv is None (i.e. when using leave-one-out cross-validation), or :ref:`coefficient of determination <r2_score>` (:math:`R^2`) otherwise.
None
cv
cv: int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the efficient Leave-One-Out cross-validation - integer, to specify the number of folds, - :term:`CV splitter`, - an iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if ``y`` is binary or multiclass, :class:`~sklearn.model_selection.StratifiedKFold` is used, else, :class:`~sklearn.model_selection.KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here.
None
gcv_mode
gcv_mode: {'auto', 'svd', 'eigen'}, default='auto' Flag indicating which strategy to use when performing Leave-One-Out Cross-Validation. Options are:: 'auto' : same as 'eigen' 'svd' : use singular value decomposition of X when X is dense, fallback to 'eigen' when X is sparse 'eigen' : use eigendecomposition of X X' when n_samples <= n_features or X' X when n_features < n_samples The 'auto' mode is the default and is intended to pick the cheaper option depending on the shape and sparsity of the training data.
None
store_cv_results
store_cv_results: bool, default=False Flag indicating if the cross-validation values corresponding to each alpha should be stored in the ``cv_results_`` attribute (see below). This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). .. versionchanged:: 1.5 Parameter name changed from `store_cv_values` to `store_cv_results`.
False
alpha_per_target
alpha_per_target: bool, default=False Flag indicating whether to optimize the alpha value (picked from the `alphas` parameter list) for each target separately (for multi-output settings: multiple prediction targets). When set to `True`, after fitting, the `alpha_` attribute will contain a value for each target. When set to `False`, a single alpha is used for all targets. This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). .. versionadded:: 0.24
False
[('categorical', ...), ('cyclic_month', ...), ...]
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.
False
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](12,) ['season','year','month',...,'feel_temp','humidity','windspeed']
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 12
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 {'categorical...inMaxScaler()}
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 {'ca...al': slice(0, 11, None), 'cy...ur': slice(20, 32, None), 'cy...th': slice(11, 17, None), 'cy...ay': slice(17, 20, 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 [('ca...al', OneHotEncoder..._output=False), Index(['seaso..., dtype='str')), ('cy...th', SplineTransfo... n_knots=7), ['month']), ('cy...ay', SplineTransfo... n_knots=4), ['weekday']), ('cy...ur', SplineTransfo... n_knots=13), ['hour']), ...]
Index(['season', 'holiday', 'workingday', 'weather'], dtype='str')
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.
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.
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'
11 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False workingday_True
['year', 'temp', 'feel_temp', 'humidity', 'windspeed']
37 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False workingday_True weather_clear weather_misty weather_rain month_sp_0 month_sp_1 month_sp_2 month_sp_3 month_sp_4 month_sp_5 weekday_sp_0 weekday_sp_1 weekday_sp_2 hour_sp_0 hour_sp_1 hour_sp_2 hour_sp_3 hour_sp_4 hour_sp_5 hour_sp_6 hour_sp_7 hour_sp_8 hour_sp_9 hour_sp_10 hour_sp_11 year temp feel_temp humidity windspeed
Parameters
alphas
alphas: array-like of shape (n_alphas,), default=(0.1, 1.0, 10.0) Array of alpha values to try. Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to ``1 / (2C)`` in other linear models such as :class:`~sklearn.linear_model.LogisticRegression` or :class:`~sklearn.svm.LinearSVC`. If using Leave-One-Out cross-validation, alphas must be strictly positive. For an example on how regularization strength affects the model coefficients, see :ref:`sphx_glr_auto_examples_linear_model_plot_ridge_coeffs.py`.
array([1.0000...00000000e+06])
fit_intercept
fit_intercept: bool, default=True Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
True
scoring
scoring: str, callable, default=None The scoring method to use for cross-validation. 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`: negative :ref:`mean squared error <mean_squared_error>` if cv is None (i.e. when using leave-one-out cross-validation), or :ref:`coefficient of determination <r2_score>` (:math:`R^2`) otherwise.
None
cv
cv: int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the efficient Leave-One-Out cross-validation - integer, to specify the number of folds, - :term:`CV splitter`, - an iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if ``y`` is binary or multiclass, :class:`~sklearn.model_selection.StratifiedKFold` is used, else, :class:`~sklearn.model_selection.KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here.
None
gcv_mode
gcv_mode: {'auto', 'svd', 'eigen'}, default='auto' Flag indicating which strategy to use when performing Leave-One-Out Cross-Validation. Options are:: 'auto' : same as 'eigen' 'svd' : use singular value decomposition of X when X is dense, fallback to 'eigen' when X is sparse 'eigen' : use eigendecomposition of X X' when n_samples <= n_features or X' X when n_features < n_samples The 'auto' mode is the default and is intended to pick the cheaper option depending on the shape and sparsity of the training data.
None
store_cv_results
store_cv_results: bool, default=False Flag indicating if the cross-validation values corresponding to each alpha should be stored in the ``cv_results_`` attribute (see below). This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). .. versionchanged:: 1.5 Parameter name changed from `store_cv_values` to `store_cv_results`.
False
alpha_per_target
alpha_per_target: bool, default=False Flag indicating whether to optimize the alpha value (picked from the `alphas` parameter list) for each target separately (for multi-output settings: multiple prediction targets). When set to `True`, after fitting, the `alpha_` attribute will contain a value for each target. When set to `False`, a single alpha is used for all targets. This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). .. versionadded:: 0.24
False
[('marginal', ...), ('interactions', ...)]
Index(['season', 'holiday', 'workingday', 'weather'], dtype='str')
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.
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.
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'
11 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False
['year', 'temp', 'feel_temp', 'humidity', 'windspeed']
37 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False
columntransformer: 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`.
82 features
marginal__season_fall marginal__season_spring marginal__season_summer marginal__season_winter marginal__holiday_False marginal__holiday_True marginal__workingday_False marginal__workingday_True marginal__weather_clear marginal__weather_misty marginal__weather_rain marginal__month_sp_0 marginal__month_sp_1 marginal__month_sp_2 marginal__month_sp_3 marginal__month_sp_4 marginal__month_sp_5 marginal__weekday_sp_0 marginal__weekday_sp_1 marginal__weekday_sp_2 marginal__hour_sp_0 marginal__hour_sp_1 marginal__hour_sp_2 marginal__hour_sp_3 marginal__hour_sp_4 marginal__hour_sp_5 marginal__hour_sp_6 marginal__hour_sp_7 marginal__hour_sp_8 marginal__hour_sp_9 marginal__hour_sp_10 marginal__hour_sp_11 marginal__year marginal__temp marginal__feel_temp marginal__humidity marginal__windspeed interactions__hour_sp_0 interactions__hour_sp_1 interactions__hour_sp_2 interactions__hour_sp_3 interactions__hour_sp_4 interactions__hour_sp_5 interactions__hour_sp_6 interactions__hour_sp_7 interactions__workingday interactions__hour_sp_0 hour_sp_1 interactions__hour_sp_0 hour_sp_2 interactions__hour_sp_0 hour_sp_3 interactions__hour_sp_0 hour_sp_4 interactions__hour_sp_0 hour_sp_5 interactions__hour_sp_0 hour_sp_6 interactions__hour_sp_0 hour_sp_7 interactions__hour_sp_0 workingday interactions__hour_sp_1 hour_sp_2 interactions__hour_sp_1 hour_sp_3 interactions__hour_sp_1 hour_sp_4 interactions__hour_sp_1 hour_sp_5 interactions__hour_sp_1 hour_sp_6 interactions__hour_sp_1 hour_sp_7 interactions__hour_sp_1 workingday interactions__hour_sp_2 hour_sp_3 interactions__hour_sp_2 hour_sp_4 interactions__hour_sp_2 hour_sp_5 interactions__hour_sp_2 hour_sp_6 interactions__hour_sp_2 hour_sp_7 interactions__hour_sp_2 workingday interactions__hour_sp_3 hour_sp_4 interactions__hour_sp_3 hour_sp_5 interactions__hour_sp_3 hour_sp_6 interactions__hour_sp_3 hour_sp_7 interactions__hour_sp_3 workingday interactions__hour_sp_4 hour_sp_5 interactions__hour_sp_4 hour_sp_6 interactions__hour_sp_4 hour_sp_7 interactions__hour_sp_4 workingday interactions__hour_sp_5 hour_sp_6 interactions__hour_sp_5 hour_sp_7 interactions__hour_sp_5 workingday interactions__hour_sp_6 hour_sp_7 interactions__hour_sp_6 workingday interactions__hour_sp_7 workingday
Parameters
alphas
alphas: array-like of shape (n_alphas,), default=(0.1, 1.0, 10.0) Array of alpha values to try. Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to ``1 / (2C)`` in other linear models such as :class:`~sklearn.linear_model.LogisticRegression` or :class:`~sklearn.svm.LinearSVC`. If using Leave-One-Out cross-validation, alphas must be strictly positive. For an example on how regularization strength affects the model coefficients, see :ref:`sphx_glr_auto_examples_linear_model_plot_ridge_coeffs.py`.
array([1.0000...00000000e+06])
fit_intercept
fit_intercept: bool, default=True Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
True
scoring
scoring: str, callable, default=None The scoring method to use for cross-validation. 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`: negative :ref:`mean squared error <mean_squared_error>` if cv is None (i.e. when using leave-one-out cross-validation), or :ref:`coefficient of determination <r2_score>` (:math:`R^2`) otherwise.
None
cv
cv: int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the efficient Leave-One-Out cross-validation - integer, to specify the number of folds, - :term:`CV splitter`, - an iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if ``y`` is binary or multiclass, :class:`~sklearn.model_selection.StratifiedKFold` is used, else, :class:`~sklearn.model_selection.KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here.
None
gcv_mode
gcv_mode: {'auto', 'svd', 'eigen'}, default='auto' Flag indicating which strategy to use when performing Leave-One-Out Cross-Validation. Options are:: 'auto' : same as 'eigen' 'svd' : use singular value decomposition of X when X is dense, fallback to 'eigen' when X is sparse 'eigen' : use eigendecomposition of X X' when n_samples <= n_features or X' X when n_features < n_samples The 'auto' mode is the default and is intended to pick the cheaper option depending on the shape and sparsity of the training data.
None
store_cv_results
store_cv_results: bool, default=False Flag indicating if the cross-validation values corresponding to each alpha should be stored in the ``cv_results_`` attribute (see below). This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). .. versionchanged:: 1.5 Parameter name changed from `store_cv_values` to `store_cv_results`.
False
alpha_per_target
alpha_per_target: bool, default=False Flag indicating whether to optimize the alpha value (picked from the `alphas` parameter list) for each target separately (for multi-output settings: multiple prediction targets). When set to `True`, after fitting, the `alpha_` attribute will contain a value for each target. When set to `False`, a single alpha is used for all targets. This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). .. versionadded:: 0.24
False
[('categorical', ...), ('cyclic_month', ...), ...]
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.
False
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](12,) ['season','year','month',...,'feel_temp','humidity','windspeed']
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 12
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 {'categorical...inMaxScaler()}
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 {'ca...al': slice(0, 11, None), 'cy...ur': slice(20, 32, None), 'cy...th': slice(11, 17, None), 'cy...ay': slice(17, 20, 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 [('ca...al', OneHotEncoder..._output=False), Index(['seaso..., dtype='str')), ('cy...th', SplineTransfo... n_knots=7), ['month']), ('cy...ay', SplineTransfo... n_knots=4), ['weekday']), ('cy...ur', SplineTransfo... n_knots=13), ['hour']), ...]
Index(['season', 'holiday', 'workingday', 'weather'], dtype='str')
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.
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.
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'
11 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False workingday_True
['year', 'temp', 'feel_temp', 'humidity', 'windspeed']
37 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False workingday_True weather_clear weather_misty weather_rain month_sp_0 month_sp_1 month_sp_2 month_sp_3 month_sp_4 month_sp_5 weekday_sp_0 weekday_sp_1 weekday_sp_2 hour_sp_0 hour_sp_1 hour_sp_2 hour_sp_3 hour_sp_4 hour_sp_5 hour_sp_6 hour_sp_7 hour_sp_8 hour_sp_9 hour_sp_10 hour_sp_11 year temp feel_temp humidity windspeed
Parameters
kernel
kernel: str or callable, default='rbf' Kernel map to be approximated. A callable should accept two arguments and the keyword arguments passed to this object as `kernel_params`, and should return a floating point number.
'poly'
degree
degree: float, default=None Degree of the polynomial kernel. Ignored by other kernels.
2
n_components
n_components: int, default=100 Number of features to construct. How many data points will be used to construct the mapping.
300
random_state
random_state: int, RandomState instance or None, default=None Pseudo-random number generator to control the uniform sampling without replacement of `n_components` of the training data to construct the basis kernel. Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`.
0
gamma
gamma: float, default=None Gamma parameter for the RBF, laplacian, polynomial, exponential chi2 and sigmoid kernels. Interpretation of the default value is left to the kernel; see the documentation for sklearn.metrics.pairwise. Ignored by other kernels.
None
coef0
coef0: float, default=None Zero coefficient for polynomial and sigmoid kernels. Ignored by other kernels.
None
kernel_params
kernel_params: dict, default=None Additional parameters (keyword arguments) for kernel function passed as callable object.
None
n_jobs
n_jobs: int, default=None The number of jobs to use for the computation. This works by breaking down the kernel matrix into `n_jobs` even slices and computing them 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. .. versionadded:: 0.24
None
100 of 300 features
nystroem0 nystroem1 nystroem2 nystroem3 nystroem4 nystroem5 nystroem6 nystroem7 nystroem8 nystroem9 nystroem10 nystroem11 nystroem12 nystroem13 nystroem14 nystroem15 nystroem16 nystroem17 nystroem18 nystroem19 nystroem20 nystroem21 nystroem22 nystroem23 nystroem24 nystroem25 nystroem26 nystroem27 nystroem28 nystroem29 nystroem30 nystroem31 nystroem32 nystroem33 nystroem34 nystroem35 nystroem36 nystroem37 nystroem38 nystroem39 nystroem40 nystroem41 nystroem42 nystroem43 nystroem44 nystroem45 nystroem46 nystroem47 nystroem48 nystroem49 nystroem50 nystroem51 nystroem52 nystroem53 nystroem54 nystroem55 nystroem56 nystroem57 nystroem58 nystroem59 nystroem60 nystroem61 nystroem62 nystroem63 nystroem64 nystroem65 nystroem66 nystroem67 nystroem68 nystroem69 nystroem70 nystroem71 nystroem72 nystroem73 nystroem74 nystroem75 nystroem76 nystroem77 nystroem78 nystroem79 nystroem80 nystroem81 nystroem82 nystroem83 nystroem84 nystroem85 nystroem86 nystroem87 nystroem88 nystroem89 nystroem90 nystroem91 nystroem92 nystroem93 nystroem94 nystroem95 nystroem96 nystroem97 nystroem98 nystroem99
Parameters
alphas
alphas: array-like of shape (n_alphas,), default=(0.1, 1.0, 10.0) Array of alpha values to try. Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to ``1 / (2C)`` in other linear models such as :class:`~sklearn.linear_model.LogisticRegression` or :class:`~sklearn.svm.LinearSVC`. If using Leave-One-Out cross-validation, alphas must be strictly positive. For an example on how regularization strength affects the model coefficients, see :ref:`sphx_glr_auto_examples_linear_model_plot_ridge_coeffs.py`.
array([1.0000...00000000e+06])
fit_intercept
fit_intercept: bool, default=True Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
True
scoring
scoring: str, callable, default=None The scoring method to use for cross-validation. 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`: negative :ref:`mean squared error <mean_squared_error>` if cv is None (i.e. when using leave-one-out cross-validation), or :ref:`coefficient of determination <r2_score>` (:math:`R^2`) otherwise.
None
cv
cv: int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the efficient Leave-One-Out cross-validation - integer, to specify the number of folds, - :term:`CV splitter`, - an iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if ``y`` is binary or multiclass, :class:`~sklearn.model_selection.StratifiedKFold` is used, else, :class:`~sklearn.model_selection.KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here.
None
gcv_mode
gcv_mode: {'auto', 'svd', 'eigen'}, default='auto' Flag indicating which strategy to use when performing Leave-One-Out Cross-Validation. Options are:: 'auto' : same as 'eigen' 'svd' : use singular value decomposition of X when X is dense, fallback to 'eigen' when X is sparse 'eigen' : use eigendecomposition of X X' when n_samples <= n_features or X' X when n_features < n_samples The 'auto' mode is the default and is intended to pick the cheaper option depending on the shape and sparsity of the training data.
None
store_cv_results
store_cv_results: bool, default=False Flag indicating if the cross-validation values corresponding to each alpha should be stored in the ``cv_results_`` attribute (see below). This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). .. versionchanged:: 1.5 Parameter name changed from `store_cv_values` to `store_cv_results`.
False
alpha_per_target
alpha_per_target: bool, default=False Flag indicating whether to optimize the alpha value (picked from the `alphas` parameter list) for each target separately (for multi-output settings: multiple prediction targets). When set to `True`, after fitting, the `alpha_` attribute will contain a value for each target. When set to `False`, a single alpha is used for all targets. This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). .. versionadded:: 0.24
False
[('categorical', ...), ('one_hot_time', ...)]
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.
False
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](12,) ['season','year','month',...,'feel_temp','humidity','windspeed']
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 12
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 {'categorical...'one-to-one')}
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 {'ca...al': slice(0, 11, None), 'on...me': slice(11, 54, None), 're...er': slice(54, 59, 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 [('ca...al', OneHotEncoder..._output=False), Index(['seaso..., dtype='str')), ('on...me', OneHotEncoder..._output=False), ['hour', 'weekday', 'month']), ('re...er', FunctionTrans...='one-to-one'), ['year', 'temp', 'fe...mp', 'hu...ty', ...])]
Index(['season', 'holiday', 'workingday', 'weather'], dtype='str')
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.
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.
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'
11 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False workingday_True
['hour', 'weekday', 'month']['year', 'temp', 'feel_temp', 'humidity', 'windspeed']
59 features
season_fall season_spring season_summer season_winter holiday_False holiday_True workingday_False workingday_True weather_clear weather_misty weather_rain hour_0 hour_1 hour_2 hour_3 hour_4 hour_5 hour_6 hour_7 hour_8 hour_9 hour_10 hour_11 hour_12 hour_13 hour_14 hour_15 hour_16 hour_17 hour_18 hour_19 hour_20 hour_21 hour_22 hour_23 weekday_0 weekday_1 weekday_2 weekday_3 weekday_4 weekday_5 weekday_6 month_1 month_2 month_3 month_4 month_5 month_6 month_7 month_8 month_9 month_10 month_11 month_12 year temp feel_temp humidity windspeed
Parameters
kernel
kernel: str or callable, default='rbf' Kernel map to be approximated. A callable should accept two arguments and the keyword arguments passed to this object as `kernel_params`, and should return a floating point number.
'poly'
degree
degree: float, default=None Degree of the polynomial kernel. Ignored by other kernels.
2
n_components
n_components: int, default=100 Number of features to construct. How many data points will be used to construct the mapping.
300
random_state
random_state: int, RandomState instance or None, default=None Pseudo-random number generator to control the uniform sampling without replacement of `n_components` of the training data to construct the basis kernel. Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`.
0
gamma
gamma: float, default=None Gamma parameter for the RBF, laplacian, polynomial, exponential chi2 and sigmoid kernels. Interpretation of the default value is left to the kernel; see the documentation for sklearn.metrics.pairwise. Ignored by other kernels.
None
coef0
coef0: float, default=None Zero coefficient for polynomial and sigmoid kernels. Ignored by other kernels.
None
kernel_params
kernel_params: dict, default=None Additional parameters (keyword arguments) for kernel function passed as callable object.
None
n_jobs
n_jobs: int, default=None The number of jobs to use for the computation. This works by breaking down the kernel matrix into `n_jobs` even slices and computing them 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. .. versionadded:: 0.24
None
100 of 300 features
nystroem0 nystroem1 nystroem2 nystroem3 nystroem4 nystroem5 nystroem6 nystroem7 nystroem8 nystroem9 nystroem10 nystroem11 nystroem12 nystroem13 nystroem14 nystroem15 nystroem16 nystroem17 nystroem18 nystroem19 nystroem20 nystroem21 nystroem22 nystroem23 nystroem24 nystroem25 nystroem26 nystroem27 nystroem28 nystroem29 nystroem30 nystroem31 nystroem32 nystroem33 nystroem34 nystroem35 nystroem36 nystroem37 nystroem38 nystroem39 nystroem40 nystroem41 nystroem42 nystroem43 nystroem44 nystroem45 nystroem46 nystroem47 nystroem48 nystroem49 nystroem50 nystroem51 nystroem52 nystroem53 nystroem54 nystroem55 nystroem56 nystroem57 nystroem58 nystroem59 nystroem60 nystroem61 nystroem62 nystroem63 nystroem64 nystroem65 nystroem66 nystroem67 nystroem68 nystroem69 nystroem70 nystroem71 nystroem72 nystroem73 nystroem74 nystroem75 nystroem76 nystroem77 nystroem78 nystroem79 nystroem80 nystroem81 nystroem82 nystroem83 nystroem84 nystroem85 nystroem86 nystroem87 nystroem88 nystroem89 nystroem90 nystroem91 nystroem92 nystroem93 nystroem94 nystroem95 nystroem96 nystroem97 nystroem98 nystroem99
Parameters
alphas
alphas: array-like of shape (n_alphas,), default=(0.1, 1.0, 10.0) Array of alpha values to try. Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to ``1 / (2C)`` in other linear models such as :class:`~sklearn.linear_model.LogisticRegression` or :class:`~sklearn.svm.LinearSVC`. If using Leave-One-Out cross-validation, alphas must be strictly positive. For an example on how regularization strength affects the model coefficients, see :ref:`sphx_glr_auto_examples_linear_model_plot_ridge_coeffs.py`.
array([1.0000...00000000e+06])
fit_intercept
fit_intercept: bool, default=True Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
True
scoring
scoring: str, callable, default=None The scoring method to use for cross-validation. 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`: negative :ref:`mean squared error <mean_squared_error>` if cv is None (i.e. when using leave-one-out cross-validation), or :ref:`coefficient of determination <r2_score>` (:math:`R^2`) otherwise.
None
cv
cv: int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the efficient Leave-One-Out cross-validation - integer, to specify the number of folds, - :term:`CV splitter`, - an iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if ``y`` is binary or multiclass, :class:`~sklearn.model_selection.StratifiedKFold` is used, else, :class:`~sklearn.model_selection.KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here.
None
gcv_mode
gcv_mode: {'auto', 'svd', 'eigen'}, default='auto' Flag indicating which strategy to use when performing Leave-One-Out Cross-Validation. Options are:: 'auto' : same as 'eigen' 'svd' : use singular value decomposition of X when X is dense, fallback to 'eigen' when X is sparse 'eigen' : use eigendecomposition of X X' when n_samples <= n_features or X' X when n_features < n_samples The 'auto' mode is the default and is intended to pick the cheaper option depending on the shape and sparsity of the training data.
None
store_cv_results
store_cv_results: bool, default=False Flag indicating if the cross-validation values corresponding to each alpha should be stored in the ``cv_results_`` attribute (see below). This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). .. versionchanged:: 1.5 Parameter name changed from `store_cv_values` to `store_cv_results`.
False
alpha_per_target
alpha_per_target: bool, default=False Flag indicating whether to optimize the alpha value (picked from the `alphas` parameter list) for each target separately (for multi-output settings: multiple prediction targets). When set to `True`, after fitting, the `alpha_` attribute will contain a value for each target. When set to `False`, a single alpha is used for all targets. This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). .. versionadded:: 0.24
False
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`
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'
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([ 0, 1..., 21, 22, 23]), array([0, 1, 2, 3, 4, 5, 6]), array([ 1, 2..., 10, 11, 12])]
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](3,) ['hour','weekday','month']
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 1.0
int 3
43 features
hour_0 hour_1 hour_2 hour_3 hour_4 hour_5 hour_6 hour_7 hour_8 hour_9 hour_10 hour_11 hour_12 hour_13 hour_14 hour_15 hour_16 hour_17 hour_18 hour_19 hour_20 hour_21 hour_22 hour_23 weekday_0 weekday_1 weekday_2 weekday_3 weekday_4 weekday_5 weekday_6 month_1 month_2 month_3 month_4 month_5 month_6 month_7 month_8 month_9 month_10 month_11 month_12
feature_range: tuple (min, max), default=(0, 1) Desired range of transformed data.
Fitted attributes
Name Type Value
data_max_
data_max_: ndarray of shape (n_features,) Per feature maximum seen in the data .. versionadded:: 0.17 *data_max_*
ndarray[float64](5,) [ 1. ,39.36,50. , 1. ,57. ]
data_min_
data_min_: ndarray of shape (n_features,) Per feature minimum seen in the data .. versionadded:: 0.17 *data_min_*
ndarray[float64](5,) [0. ,0.82,0.76,0.16,0. ]
data_range_
data_range_: ndarray of shape (n_features,) Per feature range ``(data_max_ - data_min_)`` seen in the data .. versionadded:: 0.17 *data_range_*
ndarray[float64](5,) [ 1. ,38.54,49.24, 0.84,57. ]
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](5,) ['year','temp','feel_temp','humidity','windspeed']
min_
min_: ndarray of shape (n_features,) Per feature adjustment for minimum. Equivalent to ``min - X.min(axis=0) * self.scale_``
ndarray[float64](5,) [ 0. ,-0.02,-0.02,-0.19, 0. ]
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 0.24
int 5
n_samples_seen_
n_samples_seen_: int The number of samples processed by the estimator. It will be reset on new calls to fit, but increments across ``partial_fit`` calls.
int 10000
scale_
scale_: ndarray of shape (n_features,) Per feature relative scaling of the data. Equivalent to ``(max - min) / (X.max(axis=0) - X.min(axis=0))`` .. versionadded:: 0.17 *scale_* attribute.
ndarray[float64](5,) [1. ,0.03,0.02,1.19,0.02]
5 features
year temp feel_temp humidity windspeed
func: callable, default=None The callable to use for the transformation. This will be passed the same arguments as transform, with args and kwargs forwarded. If func is None, then func will be the identity function.
<function sin...x7e1dbc43da60>
func: callable, default=None The callable to use for the transformation. This will be passed the same arguments as transform, with args and kwargs forwarded. If func is None, then func will be the identity function.
<function cos...x7e1dbc43db10>
func: callable, default=None The callable to use for the transformation. This will be passed the same arguments as transform, with args and kwargs forwarded. If func is None, then func will be the identity function.
<function sin...x7e1dbc43dbc0>
func: callable, default=None The callable to use for the transformation. This will be passed the same arguments as transform, with args and kwargs forwarded. If func is None, then func will be the identity function.
<function cos...x7e1dbc43dc70>
func: callable, default=None The callable to use for the transformation. This will be passed the same arguments as transform, with args and kwargs forwarded. If func is None, then func will be the identity function.
<function sin...x7e1dbc43dd20>
func: callable, default=None The callable to use for the transformation. This will be passed the same arguments as transform, with args and kwargs forwarded. If func is None, then func will be the identity function.
<function cos...x7e1dbc43ddd0>
feature_range: tuple (min, max), default=(0, 1) Desired range of transformed data.
Fitted attributes
Name Type Value
data_max_
data_max_: ndarray of shape (n_features,) Per feature maximum seen in the data .. versionadded:: 0.17 *data_max_*
ndarray[float64](5,) [ 1. ,39.36,50. , 1. ,57. ]
data_min_
data_min_: ndarray of shape (n_features,) Per feature minimum seen in the data .. versionadded:: 0.17 *data_min_*
ndarray[float64](5,) [0. ,0.82,0.76,0.16,0. ]
data_range_
data_range_: ndarray of shape (n_features,) Per feature range ``(data_max_ - data_min_)`` seen in the data .. versionadded:: 0.17 *data_range_*
ndarray[float64](5,) [ 1. ,38.54,49.24, 0.84,57. ]
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](5,) ['year','temp','feel_temp','humidity','windspeed']
min_
min_: ndarray of shape (n_features,) Per feature adjustment for minimum. Equivalent to ``min - X.min(axis=0) * self.scale_``
ndarray[float64](5,) [ 0. ,-0.02,-0.02,-0.19, 0. ]
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 0.24
int 5
n_samples_seen_
n_samples_seen_: int The number of samples processed by the estimator. It will be reset on new calls to fit, but increments across ``partial_fit`` calls.
int 10000
scale_
scale_: ndarray of shape (n_features,) Per feature relative scaling of the data. Equivalent to ``(max - min) / (X.max(axis=0) - X.min(axis=0))`` .. versionadded:: 0.17 *scale_* attribute.
ndarray[float64](5,) [1. ,0.03,0.02,1.19,0.02]
5 features
year temp feel_temp humidity windspeed
n_knots: int, default=5 Number of knots of the splines if `knots` equals one of {'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots` is array-like.
knots
knots: {'uniform', 'quantile'} or array-like of shape (n_knots, n_features), default='uniform' Set knot positions such that first knot <= features <= last knot. - If 'uniform', `n_knots` number of knots are distributed uniformly from min to max values of the features. - If 'quantile', they are distributed uniformly along the quantiles of the features. - If an array-like is given, it directly specifies the sorted knot positions including the boundary knots. Note that, internally, `degree` number of knots are added before the first knot, the same after the last knot.
array([[ 0.],... [12.]])
extrapolation
extrapolation: {'error', 'constant', 'linear', 'continue', 'periodic'}, default='constant' If 'error', values outside the min and max values of the training features raises a `ValueError`. If 'constant', the value of the splines at minimum and maximum value of the features is used as constant extrapolation. If 'linear', a linear extrapolation is used. If 'continue', the splines are extrapolated as is, i.e. option `extrapolate=True` in :class:`scipy.interpolate.BSpline`. If 'periodic', periodic splines with a periodicity equal to the distance between the first and last knot are used. Periodic splines enforce equal function values and derivatives at the first and last knot. For example, this makes it possible to avoid introducing an arbitrary jump between Dec 31st and Jan 1st in spline features derived from a naturally periodic "day-of-year" input feature. In this case it is recommended to manually set the knot values to control the period.
'periodic'
6 features
month_sp_0 month_sp_1 month_sp_2 month_sp_3 month_sp_4 month_sp_5
n_knots: int, default=5 Number of knots of the splines if `knots` equals one of {'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots` is array-like.
extrapolation
extrapolation: {'error', 'constant', 'linear', 'continue', 'periodic'}, default='constant' If 'error', values outside the min and max values of the training features raises a `ValueError`. If 'constant', the value of the splines at minimum and maximum value of the features is used as constant extrapolation. If 'linear', a linear extrapolation is used. If 'continue', the splines are extrapolated as is, i.e. option `extrapolate=True` in :class:`scipy.interpolate.BSpline`. If 'periodic', periodic splines with a periodicity equal to the distance between the first and last knot are used. Periodic splines enforce equal function values and derivatives at the first and last knot. For example, this makes it possible to avoid introducing an arbitrary jump between Dec 31st and Jan 1st in spline features derived from a naturally periodic "day-of-year" input feature. In this case it is recommended to manually set the knot values to control the period.
'periodic'
3 features
weekday_sp_0 weekday_sp_1 weekday_sp_2
n_knots: int, default=5 Number of knots of the splines if `knots` equals one of {'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots` is array-like.
knots
knots: {'uniform', 'quantile'} or array-like of shape (n_knots, n_features), default='uniform' Set knot positions such that first knot <= features <= last knot. - If 'uniform', `n_knots` number of knots are distributed uniformly from min to max values of the features. - If 'quantile', they are distributed uniformly along the quantiles of the features. - If an array-like is given, it directly specifies the sorted knot positions including the boundary knots. Note that, internally, `degree` number of knots are added before the first knot, the same after the last knot.
array([[ 0.],... [24.]])
extrapolation
extrapolation: {'error', 'constant', 'linear', 'continue', 'periodic'}, default='constant' If 'error', values outside the min and max values of the training features raises a `ValueError`. If 'constant', the value of the splines at minimum and maximum value of the features is used as constant extrapolation. If 'linear', a linear extrapolation is used. If 'continue', the splines are extrapolated as is, i.e. option `extrapolate=True` in :class:`scipy.interpolate.BSpline`. If 'periodic', periodic splines with a periodicity equal to the distance between the first and last knot are used. Periodic splines enforce equal function values and derivatives at the first and last knot. For example, this makes it possible to avoid introducing an arbitrary jump between Dec 31st and Jan 1st in spline features derived from a naturally periodic "day-of-year" input feature. In this case it is recommended to manually set the knot values to control the period.
'periodic'
12 features
hour_sp_0 hour_sp_1 hour_sp_2 hour_sp_3 hour_sp_4 hour_sp_5 hour_sp_6 hour_sp_7 hour_sp_8 hour_sp_9 hour_sp_10 hour_sp_11
feature_range: tuple (min, max), default=(0, 1) Desired range of transformed data.
Fitted attributes
Name Type Value
data_max_
data_max_: ndarray of shape (n_features,) Per feature maximum seen in the data .. versionadded:: 0.17 *data_max_*
ndarray[float64](5,) [ 1. ,39.36,50. , 1. ,57. ]
data_min_
data_min_: ndarray of shape (n_features,) Per feature minimum seen in the data .. versionadded:: 0.17 *data_min_*
ndarray[float64](5,) [0. ,0.82,0.76,0.16,0. ]
data_range_
data_range_: ndarray of shape (n_features,) Per feature range ``(data_max_ - data_min_)`` seen in the data .. versionadded:: 0.17 *data_range_*
ndarray[float64](5,) [ 1. ,38.54,49.24, 0.84,57. ]
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](5,) ['year','temp','feel_temp','humidity','windspeed']
min_
min_: ndarray of shape (n_features,) Per feature adjustment for minimum. Equivalent to ``min - X.min(axis=0) * self.scale_``
ndarray[float64](5,) [ 0. ,-0.02,-0.02,-0.19, 0. ]
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 0.24
int 5
n_samples_seen_
n_samples_seen_: int The number of samples processed by the estimator. It will be reset on new calls to fit, but increments across ``partial_fit`` calls.
int 10000
scale_
scale_: ndarray of shape (n_features,) Per feature relative scaling of the data. Equivalent to ``(max - min) / (X.max(axis=0) - X.min(axis=0))`` .. versionadded:: 0.17 *scale_* attribute.
ndarray[float64](5,) [1. ,0.03,0.02,1.19,0.02]
5 features
year temp feel_temp humidity windspeed
[array(['fall'... dtype=object), array(['False... dtype=object), array(['False... dtype=object), array(['clear... dtype=object)]
n_knots: int, default=5 Number of knots of the splines if `knots` equals one of {'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots` is array-like.
knots
knots: {'uniform', 'quantile'} or array-like of shape (n_knots, n_features), default='uniform' Set knot positions such that first knot <= features <= last knot. - If 'uniform', `n_knots` number of knots are distributed uniformly from min to max values of the features. - If 'quantile', they are distributed uniformly along the quantiles of the features. - If an array-like is given, it directly specifies the sorted knot positions including the boundary knots. Note that, internally, `degree` number of knots are added before the first knot, the same after the last knot.
array([[ 0.],... [12.]])
extrapolation
extrapolation: {'error', 'constant', 'linear', 'continue', 'periodic'}, default='constant' If 'error', values outside the min and max values of the training features raises a `ValueError`. If 'constant', the value of the splines at minimum and maximum value of the features is used as constant extrapolation. If 'linear', a linear extrapolation is used. If 'continue', the splines are extrapolated as is, i.e. option `extrapolate=True` in :class:`scipy.interpolate.BSpline`. If 'periodic', periodic splines with a periodicity equal to the distance between the first and last knot are used. Periodic splines enforce equal function values and derivatives at the first and last knot. For example, this makes it possible to avoid introducing an arbitrary jump between Dec 31st and Jan 1st in spline features derived from a naturally periodic "day-of-year" input feature. In this case it is recommended to manually set the knot values to control the period.
'periodic'
6 features
month_sp_0 month_sp_1 month_sp_2 month_sp_3 month_sp_4 month_sp_5
n_knots: int, default=5 Number of knots of the splines if `knots` equals one of {'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots` is array-like.
extrapolation
extrapolation: {'error', 'constant', 'linear', 'continue', 'periodic'}, default='constant' If 'error', values outside the min and max values of the training features raises a `ValueError`. If 'constant', the value of the splines at minimum and maximum value of the features is used as constant extrapolation. If 'linear', a linear extrapolation is used. If 'continue', the splines are extrapolated as is, i.e. option `extrapolate=True` in :class:`scipy.interpolate.BSpline`. If 'periodic', periodic splines with a periodicity equal to the distance between the first and last knot are used. Periodic splines enforce equal function values and derivatives at the first and last knot. For example, this makes it possible to avoid introducing an arbitrary jump between Dec 31st and Jan 1st in spline features derived from a naturally periodic "day-of-year" input feature. In this case it is recommended to manually set the knot values to control the period.
'periodic'
3 features
weekday_sp_0 weekday_sp_1 weekday_sp_2
n_knots: int, default=5 Number of knots of the splines if `knots` equals one of {'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots` is array-like.
knots
knots: {'uniform', 'quantile'} or array-like of shape (n_knots, n_features), default='uniform' Set knot positions such that first knot <= features <= last knot. - If 'uniform', `n_knots` number of knots are distributed uniformly from min to max values of the features. - If 'quantile', they are distributed uniformly along the quantiles of the features. - If an array-like is given, it directly specifies the sorted knot positions including the boundary knots. Note that, internally, `degree` number of knots are added before the first knot, the same after the last knot.
array([[ 0.],... [24.]])
extrapolation
extrapolation: {'error', 'constant', 'linear', 'continue', 'periodic'}, default='constant' If 'error', values outside the min and max values of the training features raises a `ValueError`. If 'constant', the value of the splines at minimum and maximum value of the features is used as constant extrapolation. If 'linear', a linear extrapolation is used. If 'continue', the splines are extrapolated as is, i.e. option `extrapolate=True` in :class:`scipy.interpolate.BSpline`. If 'periodic', periodic splines with a periodicity equal to the distance between the first and last knot are used. Periodic splines enforce equal function values and derivatives at the first and last knot. For example, this makes it possible to avoid introducing an arbitrary jump between Dec 31st and Jan 1st in spline features derived from a naturally periodic "day-of-year" input feature. In this case it is recommended to manually set the knot values to control the period.
'periodic'
12 features
hour_sp_0 hour_sp_1 hour_sp_2 hour_sp_3 hour_sp_4 hour_sp_5 hour_sp_6 hour_sp_7 hour_sp_8 hour_sp_9 hour_sp_10 hour_sp_11
Fitted attributes
Name Type Value
data_max_
data_max_: ndarray of shape (n_features,) Per feature maximum seen in the data .. versionadded:: 0.17 *data_max_*
ndarray[float64](5,) [ 1. ,39.36,50. , 1. ,57. ]
data_min_
data_min_: ndarray of shape (n_features,) Per feature minimum seen in the data .. versionadded:: 0.17 *data_min_*
ndarray[float64](5,) [0. ,0.82,0.76,0.16,0. ]
data_range_
data_range_: ndarray of shape (n_features,) Per feature range ``(data_max_ - data_min_)`` seen in the data .. versionadded:: 0.17 *data_range_*
ndarray[float64](5,) [ 1. ,38.54,49.24, 0.84,57. ]
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](5,) ['year','temp','feel_temp','humidity','windspeed']
min_
min_: ndarray of shape (n_features,) Per feature adjustment for minimum. Equivalent to ``min - X.min(axis=0) * self.scale_``
ndarray[float64](5,) [ 0. ,-0.02,-0.02,-0.19, 0. ]
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 0.24
int 5
n_samples_seen_
n_samples_seen_: int The number of samples processed by the estimator. It will be reset on new calls to fit, but increments across ``partial_fit`` calls.
int 10000
scale_
scale_: ndarray of shape (n_features,) Per feature relative scaling of the data. Equivalent to ``(max - min) / (X.max(axis=0) - X.min(axis=0))`` .. versionadded:: 0.17 *scale_* attribute.
ndarray[float64](5,) [1. ,0.03,0.02,1.19,0.02]
5 features
year temp feel_temp humidity windspeed
[('cyclic_hour', ...), ('workingday', ...)]
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.
False
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](12,) ['season','year','month',...,'feel_temp','humidity','windspeed']
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 12
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 {'cyclic_hour...nder': 'drop'}
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 {'cy...ur': slice(0, 8, None), 're...er': slice(0, 0, None), 'wo...ay': slice(8, 9, 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
Parameters
n_knots
n_knots: int, default=5 Number of knots of the splines if `knots` equals one of {'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots` is array-like.
9
knots
knots: {'uniform', 'quantile'} or array-like of shape (n_knots, n_features), default='uniform' Set knot positions such that first knot <= features <= last knot. - If 'uniform', `n_knots` number of knots are distributed uniformly from min to max values of the features. - If 'quantile', they are distributed uniformly along the quantiles of the features. - If an array-like is given, it directly specifies the sorted knot positions including the boundary knots. Note that, internally, `degree` number of knots are added before the first knot, the same after the last knot.
array([[ 0.],... [24.]])
extrapolation
extrapolation: {'error', 'constant', 'linear', 'continue', 'periodic'}, default='constant' If 'error', values outside the min and max values of the training features raises a `ValueError`. If 'constant', the value of the splines at minimum and maximum value of the features is used as constant extrapolation. If 'linear', a linear extrapolation is used. If 'continue', the splines are extrapolated as is, i.e. option `extrapolate=True` in :class:`scipy.interpolate.BSpline`. If 'periodic', periodic splines with a periodicity equal to the distance between the first and last knot are used. Periodic splines enforce equal function values and derivatives at the first and last knot. For example, this makes it possible to avoid introducing an arbitrary jump between Dec 31st and Jan 1st in spline features derived from a naturally periodic "day-of-year" input feature. In this case it is recommended to manually set the knot values to control the period.
'periodic'
degree
degree: int, default=3 The polynomial degree of the spline basis. Must be a non-negative integer.
3
include_bias
include_bias: bool, default=True If False, then the last spline element inside the data range of a feature is dropped. As B-splines sum to one over the spline basis functions for each data point, they implicitly include a bias term, i.e. a column of ones. It acts as an intercept term in a linear models.
True
order
order: {'C', 'F'}, default='C' Order of output array in the dense case. `'F'` order is faster to compute, but may slow down subsequent estimators.
'C'
handle_missing
handle_missing: {'error', 'zeros'}, default='error' Specifies the way missing values are handled. - 'error' : Raise an error if `np.nan` values are present during :meth:`fit`. - 'zeros' : Encode splines of missing values with values `0`. Note that `handle_missing='zeros'` differs from first imputing missing values with zeros and then creating the spline basis. The latter creates spline basis functions which have non-zero values at the missing values whereas this option simply sets all spline basis function values to zero at the missing values. .. versionadded:: 1.8
'error'
sparse_output
sparse_output: bool, default=False Will return sparse CSR matrix if set True else will return an array. .. versionadded:: 1.2
False
8 features
hour_sp_0 hour_sp_1 hour_sp_2 hour_sp_3 hour_sp_4 hour_sp_5 hour_sp_6
<lambda>
FunctionTransformer
9 features
hour_sp_0 hour_sp_1 hour_sp_2 hour_sp_3 hour_sp_4 hour_sp_5 hour_sp_6 hour_sp_7 workingday
Parameters
interaction_only
interaction_only: bool, default=False If `True`, only interaction features are produced: features that are products of at most `degree` *distinct* input features, i.e. terms with power of 2 or higher of the same input feature are excluded: - included: `x[0]`, `x[1]`, `x[0] * x[1]`, etc. - excluded: `x[0] ** 2`, `x[0] ** 2 * x[1]`, etc.
True
include_bias
include_bias: bool, default=True If `True` (default), then include a bias column, the feature in which all polynomial powers are zero (i.e. a column of ones - acts as an intercept term in a linear model).
False
degree
degree: int or tuple (min_degree, max_degree), default=2 If a single int is given, it specifies the maximal degree of the polynomial features. If a tuple `(min_degree, max_degree)` is passed, then `min_degree` is the minimum and `max_degree` is the maximum polynomial degree of the generated features. Note that `min_degree=0` and `min_degree=1` are equivalent as outputting the degree zero term is determined by `include_bias`.
2
order
order: {'C', 'F'}, default='C' Order of output array in the dense case. `'F'` order is faster to compute, but may slow down subsequent estimators. .. versionadded:: 0.21
'C'
45 features
hour_sp_0 hour_sp_1 hour_sp_2 hour_sp_3 hour_sp_4 hour_sp_5 hour_sp_6 hour_sp_7 workingday hour_sp_0 hour_sp_1 hour_sp_0 hour_sp_2 hour_sp_0 hour_sp_3 hour_sp_0 hour_sp_4 hour_sp_0 hour_sp_5 hour_sp_0 hour_sp_6 hour_sp_0 hour_sp_7 hour_sp_0 workingday hour_sp_1 hour_sp_2 hour_sp_1 hour_sp_3 hour_sp_1 hour_sp_4 hour_sp_1 hour_sp_5 hour_sp_1 hour_sp_6 hour_sp_1 hour_sp_7 hour_sp_1 workingday hour_sp_2 hour_sp_3 hour_sp_2 hour_sp_4 hour_sp_2 hour_sp_5 hour_sp_2 hour_sp_6 hour_sp_2 hour_sp_7 hour_sp_2 workingday hour_sp_3 hour_sp_4 hour_sp_3 hour_sp_5 hour_sp_3 hour_sp_6 hour_sp_3 hour_sp_7 hour_sp_3 workingday hour_sp_4 hour_sp_5 hour_sp_4 hour_sp_6 hour_sp_4 hour_sp_7 hour_sp_4 workingday hour_sp_5 hour_sp_6 hour_sp_5 hour_sp_7 hour_sp_5 workingday hour_sp_6 hour_sp_7 hour_sp_6 workingday hour_sp_7 workingday
n_knots: int, default=5 Number of knots of the splines if `knots` equals one of {'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots` is array-like.
knots
knots: {'uniform', 'quantile'} or array-like of shape (n_knots, n_features), default='uniform' Set knot positions such that first knot <= features <= last knot. - If 'uniform', `n_knots` number of knots are distributed uniformly from min to max values of the features. - If 'quantile', they are distributed uniformly along the quantiles of the features. - If an array-like is given, it directly specifies the sorted knot positions including the boundary knots. Note that, internally, `degree` number of knots are added before the first knot, the same after the last knot.
array([[ 0.],... [12.]])
extrapolation
extrapolation: {'error', 'constant', 'linear', 'continue', 'periodic'}, default='constant' If 'error', values outside the min and max values of the training features raises a `ValueError`. If 'constant', the value of the splines at minimum and maximum value of the features is used as constant extrapolation. If 'linear', a linear extrapolation is used. If 'continue', the splines are extrapolated as is, i.e. option `extrapolate=True` in :class:`scipy.interpolate.BSpline`. If 'periodic', periodic splines with a periodicity equal to the distance between the first and last knot are used. Periodic splines enforce equal function values and derivatives at the first and last knot. For example, this makes it possible to avoid introducing an arbitrary jump between Dec 31st and Jan 1st in spline features derived from a naturally periodic "day-of-year" input feature. In this case it is recommended to manually set the knot values to control the period.
'periodic'
6 features
month_sp_0 month_sp_1 month_sp_2 month_sp_3 month_sp_4 month_sp_5
n_knots: int, default=5 Number of knots of the splines if `knots` equals one of {'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots` is array-like.
extrapolation
extrapolation: {'error', 'constant', 'linear', 'continue', 'periodic'}, default='constant' If 'error', values outside the min and max values of the training features raises a `ValueError`. If 'constant', the value of the splines at minimum and maximum value of the features is used as constant extrapolation. If 'linear', a linear extrapolation is used. If 'continue', the splines are extrapolated as is, i.e. option `extrapolate=True` in :class:`scipy.interpolate.BSpline`. If 'periodic', periodic splines with a periodicity equal to the distance between the first and last knot are used. Periodic splines enforce equal function values and derivatives at the first and last knot. For example, this makes it possible to avoid introducing an arbitrary jump between Dec 31st and Jan 1st in spline features derived from a naturally periodic "day-of-year" input feature. In this case it is recommended to manually set the knot values to control the period.
'periodic'
3 features
weekday_sp_0 weekday_sp_1 weekday_sp_2
n_knots: int, default=5 Number of knots of the splines if `knots` equals one of {'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots` is array-like.
knots
knots: {'uniform', 'quantile'} or array-like of shape (n_knots, n_features), default='uniform' Set knot positions such that first knot <= features <= last knot. - If 'uniform', `n_knots` number of knots are distributed uniformly from min to max values of the features. - If 'quantile', they are distributed uniformly along the quantiles of the features. - If an array-like is given, it directly specifies the sorted knot positions including the boundary knots. Note that, internally, `degree` number of knots are added before the first knot, the same after the last knot.
array([[ 0.],... [24.]])
extrapolation
extrapolation: {'error', 'constant', 'linear', 'continue', 'periodic'}, default='constant' If 'error', values outside the min and max values of the training features raises a `ValueError`. If 'constant', the value of the splines at minimum and maximum value of the features is used as constant extrapolation. If 'linear', a linear extrapolation is used. If 'continue', the splines are extrapolated as is, i.e. option `extrapolate=True` in :class:`scipy.interpolate.BSpline`. If 'periodic', periodic splines with a periodicity equal to the distance between the first and last knot are used. Periodic splines enforce equal function values and derivatives at the first and last knot. For example, this makes it possible to avoid introducing an arbitrary jump between Dec 31st and Jan 1st in spline features derived from a naturally periodic "day-of-year" input feature. In this case it is recommended to manually set the knot values to control the period.
'periodic'
12 features
hour_sp_0 hour_sp_1 hour_sp_2 hour_sp_3 hour_sp_4 hour_sp_5 hour_sp_6 hour_sp_7 hour_sp_8 hour_sp_9 hour_sp_10 hour_sp_11
feature_range: tuple (min, max), default=(0, 1) Desired range of transformed data.
Fitted attributes
Name Type Value
data_max_
data_max_: ndarray of shape (n_features,) Per feature maximum seen in the data .. versionadded:: 0.17 *data_max_*
ndarray[float64](5,) [ 1. ,39.36,50. , 1. ,57. ]
data_min_
data_min_: ndarray of shape (n_features,) Per feature minimum seen in the data .. versionadded:: 0.17 *data_min_*
ndarray[float64](5,) [0. ,0.82,0.76,0.16,0. ]
data_range_
data_range_: ndarray of shape (n_features,) Per feature range ``(data_max_ - data_min_)`` seen in the data .. versionadded:: 0.17 *data_range_*
ndarray[float64](5,) [ 1. ,38.54,49.24, 0.84,57. ]
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](5,) ['year','temp','feel_temp','humidity','windspeed']
min_
min_: ndarray of shape (n_features,) Per feature adjustment for minimum. Equivalent to ``min - X.min(axis=0) * self.scale_``
ndarray[float64](5,) [ 0. ,-0.02,-0.02,-0.19, 0. ]
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 0.24
int 5
n_samples_seen_
n_samples_seen_: int The number of samples processed by the estimator. It will be reset on new calls to fit, but increments across ``partial_fit`` calls.
int 10000
scale_
scale_: ndarray of shape (n_features,) Per feature relative scaling of the data. Equivalent to ``(max - min) / (X.max(axis=0) - X.min(axis=0))`` .. versionadded:: 0.17 *scale_* attribute.
ndarray[float64](5,) [1. ,0.03,0.02,1.19,0.02]
5 features
year temp feel_temp humidity windspeed
components_: ndarray of shape (n_components, n_features) Subset of training points used to construct the feature map.
ndarray[float64](300, 37)
[[0. ,0. ,1. ,...,0.6 ,0.63,0.33],
[0. ,0. ,1. ,...,0.51,0.86,0.19],
[1. ,0. ,0. ,...,0.74,0.7 ,0.3 ],
...,
[1. ,0. ,0. ,...,0.65,0.64,0.11],
[0. ,0. ,0. ,...,0.43,1. ,0. ],
[0. ,1. ,0. ,...,0.63,0.25,0.12]]
normalization_
normalization_: ndarray of shape (n_components, n_components) Normalization matrix needed for embedding. Square root of the kernel matrix on ``components_``.
ndarray[float64](300, 300) [[ 71.07, 2.07, 11.92,..., -3.79, -1.28, -4.85],
[ 2.07, 42.81, 2.42,..., 1.85, -1.69, -0.97],
[ 11.92, 2.42,149.76,...,-20.1 , 0.77, -2.76],
...,
[ -3.79, 1.85,-20.1 ,...,112.03, -0.52, -2.54],
[ -1.28, -1.69, 0.77,..., -0.52, 27.07, 1.13],
[ -4.85, -0.97, -2.76,..., -2.54, 1.13, 82.79]]
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`
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'
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([ 0, 1..., 21, 22, 23]), array([0, 1, 2, 3, 4, 5, 6]), array([ 1, 2..., 10, 11, 12])]
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](3,) ['hour','weekday','month']
n_features_in_
n_features_in_: int Number of features seen during :term:`fit`. .. versionadded:: 1.0
int 3
43 features
hour_0 hour_1 hour_2 hour_3 hour_4 hour_5 hour_6 hour_7 hour_8 hour_9 hour_10 hour_11 hour_12 hour_13 hour_14 hour_15 hour_16 hour_17 hour_18 hour_19 hour_20 hour_21 hour_22 hour_23 weekday_0 weekday_1 weekday_2 weekday_3 weekday_4 weekday_5 weekday_6 month_1 month_2 month_3 month_4 month_5 month_6 month_7 month_8 month_9 month_10 month_11 month_12
components_: ndarray of shape (n_components, n_features) Subset of training points used to construct the feature map.
ndarray[float64](300, 59)
[[ 0. , 0. , 1. ,...,30.3 , 0.69,19. ],
[ 0. , 0. , 1. ,...,25.76, 0.88,11. ],
[ 1. , 0. , 0. ,...,37.12, 0.75,17. ],
...,
[ 1. , 0. , 0. ,...,32.58, 0.7 , 6. ],
[ 0. , 0. , 0. ,...,21.97, 1. , 0. ],
[ 0. , 1. , 0. ,...,31.82, 0.37, 7. ]]
normalization_
normalization_: ndarray of shape (n_components, n_components) Normalization matrix needed for embedding. Square root of the kernel matrix on ``components_``.
ndarray[float64](300, 300) [[14.11,-0.59, 0.34,..., 0.2 ,-0.49,-0.07],
[-0.59,11.24, 0.12,...,-0.03, 0.18,-0.09],
[ 0.34, 0.12,11.45,...,-0.43,-0.15, 0.04],
...,
[ 0.2 ,-0.03,-0.43,...,11.77,-0.74, 0.35],
[-0.49, 0.18,-0.15,...,-0.74,10.65, 0.24],
[-0.07,-0.09, 0.04,..., 0.35, 0.24, 8.52]]
[('cy...ur', SplineTransfo... n_knots=9), ['hour']), ('wo...ay', FunctionTrans...7e1dbc22ec40>), ['wo...ay']), ('re...er', 'drop', ['season', 'year', 'month', 'holiday', ...])]
<function <la...x7e1dbc22ec40>
['hour_sp_0','hour_sp_1','hour_sp_2',...,'hour_sp_6','hour_sp_7',
'workingday']
powers_
powers_: ndarray of shape (`n_output_features_`, `n_features_in_`) `powers_[i, j]` is the exponent of the jth input in the ith output.
ndarray[int64](45, 9) [[1,0,0,...,0,0,0],
[0,1,0,...,0,0,0],
[0,0,1,...,0,0,0],
...,
[0,0,0,...,1,1,0],
[0,0,0,...,1,0,1],
[0,0,0,...,0,1,1]]