Airbnb Review Activity Prediction¶

A supervised machine learning study using the New York City Airbnb Open Data (2019) dataset to predict reviews_per_month from listing attributes. Monthly review activity is treated as a proxy for popularity, rather than a direct measure of bookings or revenue.

Recorded result: tuned Random Forest CV MAE 0.8660; test MAE 0.8656 reviews/month.

Scope: evaluation uses a random train/test split and excludes listings with missing targets. These results do not establish performance on future listings or zero-review listings.

Origin: this analysis originated as a CPSC 330 course project.

Data: New York City Airbnb Open Data, loaded from data/AB_NYC_2019.csv.

Contents¶

  1. Problem and dataset
  2. Data splitting
  3. Exploratory data analysis
  4. Feature engineering
  5. Preprocessing and transformations
  6. Baseline model
  7. Linear model: Ridge
  8. Model comparison
  9. Feature selection
  10. Hyperparameter optimization
  11. Feature importance
  12. Test evaluation and SHAP explanations
  13. Results summary

Imports¶

In [2]:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

1. Problem and dataset¶

  • The prediction target is reviews_per_month
  • This is a regression problem
  • There are 48895 records
  • It includes various of types of variables
  • It includes missing values
In [4]:
airbnb_df = pd.read_csv("data/AB_NYC_2019.csv")
display(airbnb_df)
id name host_id host_name neighbourhood_group neighbourhood latitude longitude room_type price minimum_nights number_of_reviews last_review reviews_per_month calculated_host_listings_count availability_365
0 2539 Clean & quiet apt home by the park 2787 John Brooklyn Kensington 40.64749 -73.97237 Private room 149 1 9 2018-10-19 0.21 6 365
1 2595 Skylit Midtown Castle 2845 Jennifer Manhattan Midtown 40.75362 -73.98377 Entire home/apt 225 1 45 2019-05-21 0.38 2 355
2 3647 THE VILLAGE OF HARLEM....NEW YORK ! 4632 Elisabeth Manhattan Harlem 40.80902 -73.94190 Private room 150 3 0 NaN NaN 1 365
3 3831 Cozy Entire Floor of Brownstone 4869 LisaRoxanne Brooklyn Clinton Hill 40.68514 -73.95976 Entire home/apt 89 1 270 2019-07-05 4.64 1 194
4 5022 Entire Apt: Spacious Studio/Loft by central park 7192 Laura Manhattan East Harlem 40.79851 -73.94399 Entire home/apt 80 10 9 2018-11-19 0.10 1 0
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
48890 36484665 Charming one bedroom - newly renovated rowhouse 8232441 Sabrina Brooklyn Bedford-Stuyvesant 40.67853 -73.94995 Private room 70 2 0 NaN NaN 2 9
48891 36485057 Affordable room in Bushwick/East Williamsburg 6570630 Marisol Brooklyn Bushwick 40.70184 -73.93317 Private room 40 4 0 NaN NaN 2 36
48892 36485431 Sunny Studio at Historical Neighborhood 23492952 Ilgar & Aysel Manhattan Harlem 40.81475 -73.94867 Entire home/apt 115 10 0 NaN NaN 1 27
48893 36485609 43rd St. Time Square-cozy single bed 30985759 Taz Manhattan Hell's Kitchen 40.75751 -73.99112 Shared room 55 1 0 NaN NaN 6 2
48894 36487245 Trendy duplex in the very heart of Hell's Kitchen 68119814 Christophe Manhattan Hell's Kitchen 40.76404 -73.98933 Private room 90 7 0 NaN NaN 1 23

48895 rows × 16 columns

2. Data splitting¶

In [5]:
from sklearn.model_selection import train_test_split

train_df, test_df = train_test_split(airbnb_df, test_size=0.3, random_state=123)

3. Exploratory data analysis¶

  • The training set has a total of 34226 records.

  • Feature'id' is unique for the the listing.

  • This dataset has some missing values in 'last_review', 'reviews_per_month', 'name', 'host_name'.

  • It has some features may not relavent for analyze: 'id', 'name', 'host_id', 'host_name'.

  • neighbourhoods_group only has 5 unique values.

  • most listings are in Manhattan and Brooklyn.

  • There are 6990 records have missing value in the target column.

  • reviews_per_month is right skewed.

  • distribution of reviews of different neighbourhood are different.

  • MAE (mean absolute error): unit is reviews per month.

In [6]:
display(train_df.columns)
display(train_df)
Index(['id', 'name', 'host_id', 'host_name', 'neighbourhood_group',
       'neighbourhood', 'latitude', 'longitude', 'room_type', 'price',
       'minimum_nights', 'number_of_reviews', 'last_review',
       'reviews_per_month', 'calculated_host_listings_count',
       'availability_365'],
      dtype='str')
id name host_id host_name neighbourhood_group neighbourhood latitude longitude room_type price minimum_nights number_of_reviews last_review reviews_per_month calculated_host_listings_count availability_365
36150 28736148 Cozy 1 Bedroom Apt in Hamilton Heights 43431867 Tommy Manhattan Washington Heights 40.83256 -73.94440 Entire home/apt 96 4 0 NaN NaN 1 17
45223 34613254 Amazing One Bedroom at the Time Square Area/72B 48146336 Irina Manhattan Hell's Kitchen 40.76134 -73.99299 Entire home/apt 150 30 0 NaN NaN 20 332
14316 11144496 New Spacious Master, Williamsburg 48819868 Nick Brooklyn Williamsburg 40.71119 -73.95097 Private room 200 1 0 NaN NaN 1 0
1691 766814 Adorable Midtown West Studio! 4022922 Caitlin Manhattan Hell's Kitchen 40.75900 -73.99530 Entire home/apt 95 1 0 NaN NaN 1 0
20195 16162621 NEW! Exceptional 2BR/1BA Williamsburg Oasis 104781467 Russell Brooklyn Williamsburg 40.71306 -73.94856 Entire home/apt 199 3 1 2016-12-11 0.03 1 0
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
7763 5885201 SUNNY ROOM A IN CHARMING AREA :) 4291007 Graham And Ben Brooklyn Bedford-Stuyvesant 40.69363 -73.95980 Private room 95 30 40 2019-06-01 0.80 11 331
15377 12325045 IDEAL One bedroom apt by Central Park! 66501870 K Alexandra Manhattan Midtown 40.76016 -73.96910 Entire home/apt 139 2 132 2019-06-30 3.66 1 154
17730 13915004 Sunlit, spacious NY apartment 7177483 Dani Manhattan Harlem 40.80380 -73.95569 Entire home/apt 250 3 10 2019-01-01 0.28 1 0
28030 21897845 One room. 159769278 Musieka Bronx Pelham Gardens 40.86706 -73.84674 Private room 40 2 17 2019-06-04 1.23 1 17
15725 12711351 Cozy Private Room w/ 1 Queen Bed 65809485 Shirley Queens Flushing 40.74807 -73.82775 Private room 40 7 102 2019-04-29 2.73 12 105

34226 rows × 16 columns

In [7]:
train_df.describe()
Out[7]:
id host_id latitude longitude price minimum_nights number_of_reviews reviews_per_month calculated_host_listings_count availability_365
count 3.422600e+04 3.422600e+04 34226.000000 34226.000000 34226.000000 34226.000000 34226.000000 27236.000000 34226.000000 34226.000000
mean 1.893979e+07 6.726273e+07 40.729142 -73.952083 151.528399 7.094957 23.244814 1.369816 7.042453 112.526004
std 1.101332e+07 7.840511e+07 0.054531 0.046201 236.628392 21.548290 44.573323 1.700737 32.590803 131.420031
min 2.539000e+03 2.438000e+03 40.506410 -74.244420 0.000000 1.000000 0.000000 0.010000 1.000000 0.000000
25% 9.394482e+06 7.721897e+06 40.690193 -73.983030 69.000000 1.000000 1.000000 0.190000 1.000000 0.000000
50% 1.954546e+07 3.074526e+07 40.723240 -73.955550 106.000000 3.000000 5.000000 0.710000 1.000000 45.000000
75% 2.915085e+07 1.068375e+08 40.763287 -73.936270 175.000000 5.000000 23.000000 2.000000 2.000000 225.750000
max 3.648561e+07 2.743213e+08 40.912340 -73.712990 10000.000000 1250.000000 629.000000 58.500000 327.000000 365.000000
In [8]:
train_df.info()
<class 'pandas.DataFrame'>
Index: 34226 entries, 36150 to 15725
Data columns (total 16 columns):
 #   Column                          Non-Null Count  Dtype  
---  ------                          --------------  -----  
 0   id                              34226 non-null  int64  
 1   name                            34216 non-null  str    
 2   host_id                         34226 non-null  int64  
 3   host_name                       34209 non-null  str    
 4   neighbourhood_group             34226 non-null  str    
 5   neighbourhood                   34226 non-null  str    
 6   latitude                        34226 non-null  float64
 7   longitude                       34226 non-null  float64
 8   room_type                       34226 non-null  str    
 9   price                           34226 non-null  int64  
 10  minimum_nights                  34226 non-null  int64  
 11  number_of_reviews               34226 non-null  int64  
 12  last_review                     27236 non-null  str    
 13  reviews_per_month               27236 non-null  float64
 14  calculated_host_listings_count  34226 non-null  int64  
 15  availability_365                34226 non-null  int64  
dtypes: float64(3), int64(7), str(6)
memory usage: 7.2 MB
In [9]:
train_df.isna().sum()
Out[9]:
id                                   0
name                                10
host_id                              0
host_name                           17
neighbourhood_group                  0
neighbourhood                        0
latitude                             0
longitude                            0
room_type                            0
price                                0
minimum_nights                       0
number_of_reviews                    0
last_review                       6990
reviews_per_month                 6990
calculated_host_listings_count       0
availability_365                     0
dtype: int64
In [10]:
print(train_df['neighbourhood_group'].unique().shape[0])
5
In [11]:
train_df["reviews_per_month"].plot.hist(bins=50)
plt.xlabel("Reviews per month")
plt.show()
No description has been provided for this image
In [12]:
train_df["neighbourhood_group"].value_counts().plot.bar(rot=0)
plt.ylabel("Number of listings")
plt.show()
No description has been provided for this image
In [13]:
train_df.boxplot(
    column='reviews_per_month',
    by='neighbourhood_group'
)
plt.suptitle("")
plt.title("Reviews per month by neightbourhood group")
plt.ylabel("Reviews per month")
plt.show()
No description has been provided for this image

4. Feature engineering¶

New feature: minimum_cost: price times minimum_nights, refecting the minimum cost for each listing.

In [16]:
train_df = train_df.assign(
    minimum_cost=train_df["price"] * train_df["minimum_nights"]
)
test_df = test_df.assign(
    minimum_cost=test_df["price"] * test_df["minimum_nights"]
)
train_df
Out[16]:
id name host_id host_name neighbourhood_group neighbourhood latitude longitude room_type price minimum_nights number_of_reviews last_review reviews_per_month calculated_host_listings_count availability_365 minimum_cost
36150 28736148 Cozy 1 Bedroom Apt in Hamilton Heights 43431867 Tommy Manhattan Washington Heights 40.83256 -73.94440 Entire home/apt 96 4 0 NaN NaN 1 17 384
45223 34613254 Amazing One Bedroom at the Time Square Area/72B 48146336 Irina Manhattan Hell's Kitchen 40.76134 -73.99299 Entire home/apt 150 30 0 NaN NaN 20 332 4500
14316 11144496 New Spacious Master, Williamsburg 48819868 Nick Brooklyn Williamsburg 40.71119 -73.95097 Private room 200 1 0 NaN NaN 1 0 200
1691 766814 Adorable Midtown West Studio! 4022922 Caitlin Manhattan Hell's Kitchen 40.75900 -73.99530 Entire home/apt 95 1 0 NaN NaN 1 0 95
20195 16162621 NEW! Exceptional 2BR/1BA Williamsburg Oasis 104781467 Russell Brooklyn Williamsburg 40.71306 -73.94856 Entire home/apt 199 3 1 2016-12-11 0.03 1 0 597
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
7763 5885201 SUNNY ROOM A IN CHARMING AREA :) 4291007 Graham And Ben Brooklyn Bedford-Stuyvesant 40.69363 -73.95980 Private room 95 30 40 2019-06-01 0.80 11 331 2850
15377 12325045 IDEAL One bedroom apt by Central Park! 66501870 K Alexandra Manhattan Midtown 40.76016 -73.96910 Entire home/apt 139 2 132 2019-06-30 3.66 1 154 278
17730 13915004 Sunlit, spacious NY apartment 7177483 Dani Manhattan Harlem 40.80380 -73.95569 Entire home/apt 250 3 10 2019-01-01 0.28 1 0 750
28030 21897845 One room. 159769278 Musieka Bronx Pelham Gardens 40.86706 -73.84674 Private room 40 2 17 2019-06-04 1.23 1 17 80
15725 12711351 Cozy Private Room w/ 1 Queen Bed 65809485 Shirley Queens Flushing 40.74807 -73.82775 Private room 40 7 102 2019-04-29 2.73 12 105 280

34226 rows × 17 columns

5. Preprocessing and transformations¶

  • Drop rows that missed the target value
  • Drop unrelavent features: id, host_id, host_name.
  • Drop last_review feature since the prediction senario is before posting
  • Drop highly informative feature: number_of_reviews

'id', 'name', 'host_id', 'host_name', 'neighbourhood_group', 'neighbourhood', 'latitude', 'longitude', 'room_type', 'price', 'minimum_nights', 'number_of_reviews', 'last_review', 'reviews_per_month', 'calculated_host_listings_count', 'availability_365'

Type Transformation Feature
numeric StandardScaler latitude, longitude, price, minimum_nights, calculated_host_listings_count, availability_365, minimum_cost
categorical OneHotEncoder neighbourhood_group, neighbourhood, room_type
text CountVectorizer name
In [17]:
train_df = train_df.dropna(subset=["reviews_per_month"])
test_df = test_df.dropna(subset=["reviews_per_month"])

train_df = train_df.drop(columns=["id", "host_id", "host_name", "last_review", "number_of_reviews"])
test_df = test_df.drop(columns=["id", "host_id", "host_name", "last_review", "number_of_reviews"])
In [18]:
numeric_feats = ["latitude", "longitude", "price", "minimum_nights", "calculated_host_listings_count", "availability_365", "minimum_cost"]
categorical_feats = ["neighbourhood_group", "neighbourhood", "room_type"]
In [19]:
train_df["name"] = train_df["name"].fillna("")
test_df["name"] = test_df["name"].fillna("")
In [20]:
from sklearn.compose import make_column_transformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.feature_extraction.text import CountVectorizer

ct = make_column_transformer(
    (make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric_feats),
    (OneHotEncoder(handle_unknown="ignore"), categorical_feats),
    (CountVectorizer(max_features=100, stop_words="english"), "name"),
)
In [21]:
X_train = train_df.drop(columns="reviews_per_month")
y_train = train_df["reviews_per_month"]
X_test = test_df.drop(columns="reviews_per_month")
y_test = test_df["reviews_per_month"]

6. Baseline model¶

In [22]:
from sklearn.dummy import DummyRegressor

baseline_pipe = make_pipeline(ct, DummyRegressor(strategy="median"))
In [23]:
from sklearn.model_selection import cross_validate

baseline_results = cross_validate(baseline_pipe, X_train, y_train, cv=5, scoring="neg_mean_absolute_error", return_train_score=True)
In [24]:
pd.DataFrame({
    "train_MAE": -baseline_results["train_score"],
    "validation_MAE": -baseline_results["test_score"],
}).agg(["mean", "std"])
Out[24]:
train_MAE validation_MAE
mean 1.123668 1.123818
std 0.003059 0.012210

7. Linear model: Ridge¶

Use Linear regression with Ridge with alpha=10 has a better performance. Compared with baseline where validation MAE=1.1169, Ridge has small improvement that validation_MAE=1.1238 and validation_std=0.009377.

In [25]:
from sklearn.linear_model import Ridge

alphas = [0.01, 0.1, 1, 10, 100, 1000]
In [26]:
linear_results = []
for a in alphas:
    linear_pipe = make_pipeline(ct, Ridge(alpha=a))
    result = cross_validate(linear_pipe, X_train, y_train, cv=5, scoring="neg_mean_absolute_error", return_train_score=True)
    linear_results.append({
        "alpha": a,
        "train_MAE": -result["train_score"].mean(),
        "validation_MAE": -result["test_score"].mean(),
        "train_std": result["train_score"].std(),
        "validation_std": result["test_score"].std(),
    })
In [27]:
linear_summary = pd.DataFrame(linear_results).set_index("alpha")
linear_summary
Out[27]:
train_MAE validation_MAE train_std validation_std
alpha
0.01 1.100472 1.118380 0.001586 0.009139
0.10 1.100564 1.118216 0.001588 0.009110
1.00 1.101404 1.117498 0.001565 0.009050
10.00 1.104766 1.116937 0.001788 0.009377
100.00 1.112913 1.120241 0.002260 0.009686
1000.00 1.135542 1.138416 0.002857 0.009641

8. Model comparison¶

Overall, kNN model has a significant lower training error on the training set compared with validation set, indicating that it overfitted. Decision tree and Random forest have a smaller gap between training ang validation while with significant lower score timing.

In [29]:
# kNN
from sklearn.neighbors import KNeighborsRegressor

kNN_pipe = make_pipeline(ct, KNeighborsRegressor(n_neighbors=5))
kNN_result = cross_validate(kNN_pipe, X_train, y_train, cv=5, scoring="neg_mean_absolute_error", return_train_score=True)
pd.DataFrame(kNN_result)
Out[29]:
fit_time score_time test_score train_score
0 0.118088 2.147446 -1.096151 -0.882628
1 0.113836 1.882385 -1.085269 -0.873065
2 0.108536 1.890413 -1.086733 -0.876026
3 0.105388 1.882319 -1.075292 -0.879429
4 0.103976 1.531235 -1.096071 -0.873804
In [30]:
# DecisionTreeRegressor
from sklearn.tree import DecisionTreeRegressor

tree_pipe = make_pipeline(ct, DecisionTreeRegressor(random_state=123, max_depth=10))
tree_result = cross_validate(tree_pipe, X_train, y_train, cv=5, scoring="neg_mean_absolute_error", return_train_score=True)
pd.DataFrame(tree_result)
Out[30]:
fit_time score_time test_score train_score
0 0.223306 0.025051 -0.927550 -0.827839
1 0.226473 0.023800 -0.919304 -0.820647
2 0.223552 0.023658 -0.891686 -0.831399
3 0.226796 0.024423 -0.903244 -0.834990
4 0.224581 0.038616 -0.891725 -0.829238
In [31]:
# RandomForestRegressor

from sklearn.ensemble import RandomForestRegressor

rf_pipe = make_pipeline(ct, RandomForestRegressor(n_estimators=10, random_state=123, max_depth=10))
rf_result = cross_validate(rf_pipe, X_train, y_train, cv=5, scoring="neg_mean_absolute_error", return_train_score=True)
pd.DataFrame(rf_result)
Out[31]:
fit_time score_time test_score train_score
0 0.957991 0.026798 -0.904509 -0.828316
1 0.969701 0.026511 -0.888677 -0.826777
2 0.952943 0.026053 -0.873218 -0.830073
3 0.981971 0.030106 -0.879320 -0.828978
4 0.956795 0.026404 -0.874182 -0.831001

9. Feature selection¶

RFECV can reach slightly better performance by using significant less features. But it significantly increase the time. So I keep all the features for the following work.

In [32]:
from sklearn.base import clone
from sklearn.feature_selection import RFECV

# AI was used to explain concept and syntax
rfecv_pipe = make_pipeline(
    ct, 
    RFECV(estimator=clone(rf_pipe[-1]), step=10, min_features_to_select=20, 
          cv=3, scoring="neg_mean_absolute_error"
        )
    )

rfecv_result = cross_validate(
    rfecv_pipe, X_train, y_train, cv=5, scoring="neg_mean_absolute_error", 
    return_train_score=True, return_estimator=True
    )
pd.DataFrame(rfecv_result)
Out[32]:
fit_time score_time estimator test_score train_score
0 72.244002 0.028413 (ColumnTransformer(transformers=[('pipeline',\... -0.901469 -0.826230
1 81.173389 0.033191 (ColumnTransformer(transformers=[('pipeline',\... -0.888320 -0.823452
2 75.348417 0.031062 (ColumnTransformer(transformers=[('pipeline',\... -0.873067 -0.825987
3 64.973110 0.030514 (ColumnTransformer(transformers=[('pipeline',\... -0.878843 -0.828922
4 75.878925 0.030160 (ColumnTransformer(transformers=[('pipeline',\... -0.873859 -0.828575
In [33]:
# AI was used to help analyzing folds
for fold, model in enumerate(rfecv_result["estimator"], start=1):
    original = len(model.steps[0][1].get_feature_names_out())
    selected = model.named_steps["rfecv"].n_features_
    print(f"Fold {fold}: {original} → {selected}")
Fold 1: 328 → 78
Fold 2: 327 → 77
Fold 3: 330 → 60
Fold 4: 326 → 186
Fold 5: 326 → 96

10. Hyperparameter optimization¶

These two parameters control the complexoty of the trees. The best setting is max_depth=20 with min_samples_leaf=10, while reached mean CV MAE at 0.8660.

In [35]:
# Code referenced from book
param_grid = {
    "randomforestregressor__max_depth": [5, 10, 20, 35, 55],
    "randomforestregressor__min_samples_leaf": [1, 5, 10, 20, 25],
}
In [36]:
from sklearn.model_selection import GridSearchCV

rf_search = GridSearchCV(rf_pipe, param_grid, cv=5, scoring="neg_mean_absolute_error", return_train_score=True,)
rf_search.fit(X_train, y_train)
Out[36]:
GridSearchCV(cv=5,
             estimator=Pipeline(steps=[('columntransformer',
                                        ColumnTransformer(transformers=[('pipeline',
                                                                         Pipeline(steps=[('simpleimputer',
                                                                                          SimpleImputer(strategy='median')),
                                                                                         ('standardscaler',
                                                                                          StandardScaler())]),
                                                                         ['latitude',
                                                                          'longitude',
                                                                          'price',
                                                                          'minimum_nights',
                                                                          'calculated_host_listings_count',
                                                                          'availability_365',
                                                                          'minimum_cost']),
                                                                        ('onehotencoder',
                                                                         O...
                                                                        ('countvectorizer',
                                                                         CountVectorizer(max_features=100,
                                                                                         stop_words='english'),
                                                                         'name')])),
                                       ('randomforestregressor',
                                        RandomForestRegressor(max_depth=10,
                                                              n_estimators=10,
                                                              random_state=123))]),
             param_grid={'randomforestregressor__max_depth': [5, 10, 20, 35,
                                                              55],
                         'randomforestregressor__min_samples_leaf': [1, 5, 10,
                                                                     20, 25]},
             return_train_score=True, scoring='neg_mean_absolute_error')
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
estimator estimator: estimator object

This is assumed to implement the scikit-learn estimator interface.
Either estimator needs to provide a ``score`` function,
or ``scoring`` must be passed.
Pipeline(step..._state=123))])
param_grid param_grid: dict or list of dictionaries

Dictionary with parameters names (`str`) as keys and lists of
parameter settings to try as values, or a list of such
dictionaries, in which case the grids spanned by each dictionary
in the list are explored. This enables searching over any sequence
of parameter settings.
{'randomforestregressor__max_depth': [5, 10, ...], 'randomforestregressor__min_samples_leaf': [1, 5, ...]}
scoring scoring: str, callable, list, tuple or dict, default=None

Strategy to evaluate the performance of the cross-validated model on
the test set.

If `scoring` represents a single score, one can use:

- a single string (see :ref:`scoring_string_names`);
- a callable (see :ref:`scoring_callable`) that returns a single value;
- `None`, the `estimator`'s
:ref:`default evaluation criterion <scoring_api_overview>` is used.

If `scoring` represents multiple scores, one can use:

- a list or tuple of unique strings;
- a callable returning a dictionary where the keys are the metric
names and the values are the metric scores;
- a dictionary with metric names as keys and callables as values.

See :ref:`multimetric_grid_search` for an example.
'neg_mean_absolute_error'
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 default 5-fold cross validation,
- integer, to specify the number of folds in a `(Stratified)KFold`,
- :term:`CV splitter`,
- an iterable yielding (train, test) splits as arrays of indices.

For integer/None inputs, if the estimator is a classifier and ``y`` is
either binary or multiclass, :class:`StratifiedKFold` is used. In all
other cases, :class:`KFold` is used. These splitters are instantiated
with `shuffle=False` so the splits will be the same across calls.

Refer :ref:`User Guide <cross_validation>` for the various
cross-validation strategies that can be used here.

.. versionchanged:: 0.22
``cv`` default value if None changed from 3-fold to 5-fold.
5
return_train_score return_train_score: bool, default=False

If ``False``, the ``cv_results_`` attribute will not include training
scores.
Computing training scores is used to get insights on how different
parameter settings impact the overfitting/underfitting trade-off.
However computing the scores on the training set can be computationally
expensive and is not strictly required to select the parameters that
yield the best generalization performance.

.. versionadded:: 0.19

.. versionchanged:: 0.21
Default value was changed from ``True`` to ``False``
True
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.

.. versionchanged:: v0.20
`n_jobs` default changed from 1 to None
None
refit refit: bool, str, or callable, default=True

Refit an estimator using the best found parameters on the whole
dataset.

For multiple metric evaluation, this needs to be a `str` denoting the
scorer that would be used to find the best parameters for refitting
the estimator at the end.

Where there are considerations other than maximum score in
choosing a best estimator, ``refit`` can be set to a function which
returns the selected ``best_index_`` given ``cv_results_``. In that
case, the ``best_estimator_`` and ``best_params_`` will be set
according to the returned ``best_index_`` while the ``best_score_``
attribute will not be available.

The refitted estimator is made available at the ``best_estimator_``
attribute and permits using ``predict`` directly on this
``GridSearchCV`` instance.

Also for multiple metric evaluation, the attributes ``best_index_``,
``best_score_`` and ``best_params_`` will only be available if
``refit`` is set and all of them will be determined w.r.t this specific
scorer.

See ``scoring`` parameter to know more about multiple metric
evaluation.

See :ref:`sphx_glr_auto_examples_model_selection_plot_grid_search_digits.py`
to see how to design a custom selection strategy using a callable
via `refit`.

See :ref:`this example
<sphx_glr_auto_examples_model_selection_plot_grid_search_refit_callable.py>`
for an example of how to use ``refit=callable`` to balance model
complexity and cross-validated score.

.. versionchanged:: 0.20
Support for callable added.
True
verbose verbose: int, default=0

Controls the verbosity of information printed during fitting, with higher
values yielding more detailed logging.

- 0 : no messages are printed;
- >=1 : summary of the total number of fits;
- >=2 : computation time for each fold and parameter candidate;
- >=3 : fold indices and scores;
- >=10 : parameter candidate indices and START messages before each fit.
0
pre_dispatch pre_dispatch: int, or str, default='2*n_jobs'

Controls the number of jobs that get dispatched during parallel
execution. Reducing this number can be useful to avoid an
explosion of memory consumption when more jobs get dispatched
than CPUs can process. This parameter can be:

- None, in which case all the jobs are immediately created and spawned. Use
this for lightweight and fast-running jobs, to avoid delays due to on-demand
spawning of the jobs
- An int, giving the exact number of total jobs that are spawned
- A str, giving an expression as a function of n_jobs, as in '2*n_jobs'
'2*n_jobs'
error_score error_score: 'raise' or numeric, default=np.nan

Value to assign to the score if an error occurs in estimator fitting.
If set to 'raise', the error is raised. If a numeric value is given,
FitFailedWarning is raised. This parameter does not affect the refit
step, which will always raise the error.
nan
Fitted attributes
Name Type Value
best_estimator_ best_estimator_: estimator

Estimator that was chosen by the search, i.e. estimator
which gave highest score (or smallest loss if specified)
on the left out data. Not available if ``refit=False``.

See ``refit`` parameter for more information on allowed values.
Pipeline Pipeline(step..._state=123))])
best_index_ best_index_: int

The index (of the ``cv_results_`` arrays) which corresponds to the best
candidate parameter setting.

The dict at ``search.cv_results_['params'][search.best_index_]`` gives
the parameter setting for the best model, that gives the highest
mean score (``search.best_score_``).

For multi-metric evaluation, this is present only if ``refit`` is
specified.
int64 np.int64(12)
best_params_ best_params_: dict

Parameter setting that gave the best results on the hold out data.

For multi-metric evaluation, this is present only if ``refit`` is
specified.
dict {'ra...th': 20, 'ra...af': 10}
best_score_ best_score_: float

Mean cross-validated score of the best_estimator

For multi-metric evaluation, this is present only if ``refit`` is
specified.

This attribute is not available if ``refit`` is a function.
float64 -0.866
cv_results_ cv_results_: dict of numpy (masked) ndarrays

A dict with keys as column headers and values as columns, that can be
imported into a pandas ``DataFrame``.

For instance the below given table

+------------+-----------+------------+-----------------+---+---------+
|param_kernel|param_gamma|param_degree|split0_test_score|...|rank_t...|
+============+===========+============+=================+===+=========+
| 'poly' | -- | 2 | 0.80 |...| 2 |
+------------+-----------+------------+-----------------+---+---------+
| 'poly' | -- | 3 | 0.70 |...| 4 |
+------------+-----------+------------+-----------------+---+---------+
| 'rbf' | 0.1 | -- | 0.80 |...| 3 |
+------------+-----------+------------+-----------------+---+---------+
| 'rbf' | 0.2 | -- | 0.93 |...| 1 |
+------------+-----------+------------+-----------------+---+---------+

will be represented by a ``cv_results_`` dict of::

{
'param_kernel': masked_array(data = ['poly', 'poly', 'rbf', 'rbf'],
mask = [False False False False]...)
'param_gamma': masked_array(data = [-- -- 0.1 0.2],
mask = [ True True False False]...),
'param_degree': masked_array(data = [2.0 3.0 -- --],
mask = [False False True True]...),
'split0_test_score' : [0.80, 0.70, 0.80, 0.93],
'split1_test_score' : [0.82, 0.50, 0.70, 0.78],
'mean_test_score' : [0.81, 0.60, 0.75, 0.85],
'std_test_score' : [0.01, 0.10, 0.05, 0.08],
'rank_test_score' : [2, 4, 3, 1],
'split0_train_score' : [0.80, 0.92, 0.70, 0.93],
'split1_train_score' : [0.82, 0.55, 0.70, 0.87],
'mean_train_score' : [0.81, 0.74, 0.70, 0.90],
'std_train_score' : [0.01, 0.19, 0.00, 0.03],
'mean_fit_time' : [0.73, 0.63, 0.43, 0.49],
'std_fit_time' : [0.01, 0.02, 0.01, 0.01],
'mean_score_time' : [0.01, 0.06, 0.04, 0.04],
'std_score_time' : [0.00, 0.00, 0.00, 0.01],
'params' : [{'kernel': 'poly', 'degree': 2}, ...],
}

For an example of visualization and interpretation of GridSearch results,
see :ref:`sphx_glr_auto_examples_model_selection_plot_grid_search_stats.py`.

NOTE

The key ``'params'`` is used to store a list of parameter
settings dicts for all the parameter candidates.

The ``mean_fit_time``, ``std_fit_time``, ``mean_score_time`` and
``std_score_time`` are all in seconds.

For multi-metric evaluation, the scores for all the scorers are
available in the ``cv_results_`` dict at the keys ending with that
scorer's name (``'_<scorer_name>'``) instead of ``'_score'`` shown
above. ('split0_test_precision', 'mean_train_precision' etc.)
dict {'me...me': array([0.4424..., 1.31480112]), 'me...me': array([0.0262..., 0.02744746]), 'me...re': array([-0.919... -0.86985135]), 'me...re': array([-0.911... -0.80293016]), ...}
feature_names_in_ feature_names_in_: ndarray of shape (`n_features_in_`,)

Names of features seen during :term:`fit`. Only defined if
`best_estimator_` is defined (see the documentation for the `refit`
parameter for more details) and that `best_estimator_` exposes
`feature_names_in_` when fit.

.. versionadded:: 1.0
ndarray[object](11,) ['name','neighbourhood_group','neighbourhood',..., 'calculated_host_listings_count','availability_365','minimum_cost']
multimetric_ multimetric_: bool

Whether or not the scorers compute several metrics.
bool False
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`. Only defined if
`best_estimator_` is defined (see the documentation for the `refit`
parameter for more details) and that `best_estimator_` exposes
`n_features_in_` when fit.

.. versionadded:: 0.24
int 11
n_splits_ n_splits_: int

The number of cross-validation splits (folds/iterations).
int 5
refit_time_ refit_time_: float

Seconds used for refitting the best model on the whole dataset.

This is present only if ``refit`` is not False.

.. versionadded:: 0.20
float 2.513
scorer_ scorer_: function or a dict

Scorer function used on the held out data to choose the best
parameters for the model.

For multi-metric evaluation, this attribute holds the validated
``scoring`` dict which maps the scorer key to the scorer callable.
_Scorer make_scorer(m...hod='predict')
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`.
[('pipeline', ...), ('onehotencoder', ...), ...]
remainder remainder: {'drop', 'passthrough'} or estimator, default='drop'

By default, only the specified columns in `transformers` are
transformed and combined in the output, and the non-specified
columns are dropped. (default of ``'drop'``).
By specifying ``remainder='passthrough'``, all remaining columns that
were not specified in `transformers`, but present in the data passed
to `fit` will be automatically passed through. This subset of columns
is concatenated with the output of the transformers. For dataframes,
extra columns not seen during `fit` will be excluded from the output
of `transform`.
By setting ``remainder`` to be an estimator, the remaining
non-specified columns will use the ``remainder`` estimator. The
estimator must support :term:`fit` and :term:`transform`.
Note that using this feature requires that the DataFrame columns
input at :term:`fit` and :term:`transform` have identical order.
'drop'
sparse_threshold sparse_threshold: float, default=0.3

If the output of the different transformers contains sparse matrices,
these will be stacked as a sparse matrix if the overall density is
lower than this value. Use ``sparse_threshold=0`` to always return
dense. When the transformed output consists of all dense data, the
stacked result will be dense, and this keyword will be ignored.
0.3
n_jobs n_jobs: int, default=None

Number of jobs to run in parallel.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
None
transformer_weights transformer_weights: dict, default=None

Multiplicative weights for features per transformer. The output of the
transformer is multiplied by these weights. Keys are transformer names,
values the weights.
None
verbose verbose: bool, default=False

If True, the time elapsed while fitting each transformer will be
printed as it is completed.
False
verbose_feature_names_out verbose_feature_names_out: bool, str or Callable[[str, str], str], default=True

- If True, :meth:`ColumnTransformer.get_feature_names_out` will prefix
all feature names with the name of the transformer that generated that
feature. It is equivalent to setting
`verbose_feature_names_out="{transformer_name}__{feature_name}"`.
- If False, :meth:`ColumnTransformer.get_feature_names_out` will not
prefix any feature names and will error if feature names are not
unique.
- If ``Callable[[str, str], str]``,
:meth:`ColumnTransformer.get_feature_names_out` will rename all the features
using the name of the transformer. The first argument of the callable is the
transformer name and the second argument is the feature name. The returned
string will be the new feature name.
- If ``str``, it must be a string ready for formatting. The given string will
be formatted using two field names: ``transformer_name`` and ``feature_name``.
e.g. ``"{feature_name}__{transformer_name}"``. See :meth:`str.format` method
from the standard library for more info.

.. versionadded:: 1.0

.. versionchanged:: 1.6
`verbose_feature_names_out` can be a callable or a string to be formatted.
True
Fitted attributes
Name Type Value
feature_names_in_ feature_names_in_: ndarray of shape (`n_features_in_`,)

Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.

.. versionadded:: 1.0
ndarray[object](11,) ['name','neighbourhood_group','neighbourhood',..., 'calculated_host_listings_count','availability_365','minimum_cost']
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 11
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 {'pipeline': ...ds='english')}
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 {'co...er': slice(230, 330, None), 'on...er': slice(7, 230, None), 'pi...ne': slice(0, 7, None), 're...er': slice(0, 0, None)}
sparse_output_ sparse_output_: bool

Boolean flag indicating whether the output of ``transform`` is a
sparse matrix or a dense numpy array, which depends on the output
of the individual transformers and the `sparse_threshold` keyword.
bool True
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 [('pi...ne', Pipeline(step...ardScaler())]), ['la...de', 'lo...de', 'price', 'mi...ts', ...]), ('on...er', OneHotEncoder...nown='ignore'), ['ne...up', 'ne...od', 'ro...pe']), ('co...er', CountVectoriz...rds='english'), 'name')]
['latitude', 'longitude', 'price', 'minimum_nights', 'calculated_host_listings_count', 'availability_365', 'minimum_cost']
Parameters
strategy strategy: str or Callable, default='mean'

The imputation strategy.

- If "mean", then replace missing values using the mean along
each column. Can only be used with numeric data.
- If "median", then replace missing values using the median along
each column. Can only be used with numeric data.
- If "most_frequent", then replace missing using the most frequent
value along each column. Can be used with strings or numeric data.
If there is more than one such value, only the smallest is returned.
- If "constant", then replace missing values with fill_value. Can be
used with strings or numeric data.
- If an instance of Callable, then replace missing values using the
scalar statistic returned by running the callable over a dense 1d
array containing non-missing values of each column.

.. versionadded:: 0.20
strategy="constant" for fixed value imputation.

.. versionadded:: 1.5
strategy=callable for custom value imputation.
'median'
missing_values missing_values: int, float, str, np.nan, None or pandas.NA, default=np.nan

The placeholder for the missing values. All occurrences of
`missing_values` will be imputed. For pandas' dataframes with
nullable integer dtypes with missing values, `missing_values`
can be set to either `np.nan` or `pd.NA`.
nan
fill_value fill_value: str or numerical value, default=None

When strategy == "constant", `fill_value` is used to replace all
occurrences of missing_values. For string or object data types,
`fill_value` must be a string.
If `None`, `fill_value` will be 0 when imputing numerical
data and "missing_value" for strings or object data types.
None
copy copy: bool, default=True

If True, a copy of X will be created. If False, imputation will
be done in-place whenever possible. Note that, in the following cases,
a new copy will always be made, even if `copy=False`:

- If `X` is not an array of floating values;
- If `X` is encoded as a CSR matrix;
- If `add_indicator=True`.
True
add_indicator add_indicator: bool, default=False

If True, a :class:`MissingIndicator` transform will stack onto output
of the imputer's transform. This allows a predictive estimator
to account for missingness despite imputation. If a feature has no
missing values at fit/train time, the feature won't appear on
the missing indicator even if there are missing values at
transform/test time.
False
keep_empty_features keep_empty_features: bool, default=False

If True, features that consist exclusively of missing values when
`fit` is called are returned in results when `transform` is called.
The imputed value is always `0` except when `strategy="constant"`
in which case `fill_value` will be used instead.

.. versionadded:: 1.2
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](7,) ['latitude','longitude','price',...,'calculated_host_listings_count', 'availability_365','minimum_cost']
indicator_ indicator_: :class:`~sklearn.impute.MissingIndicator`

Indicator used to add binary indicators for missing values.
`None` if `add_indicator=False`.
NoneType None
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`.

.. versionadded:: 0.24
int 7
statistics_ statistics_: array of shape (n_features,)

The imputation fill value for each feature.
Computing statistics can result in `np.nan` values.
During :meth:`transform`, features corresponding to `np.nan`
statistics will be discarded.
ndarray[float64](7,) [ 40.72,-73.95,101. ,..., 1. , 55. ,289.5 ]
7 features
latitude
longitude
price
minimum_nights
calculated_host_listings_count
availability_365
minimum_cost
Parameters
copy copy: bool, default=True

If False, try to avoid a copy and do inplace scaling instead.
This is not guaranteed to always work inplace; e.g. if the data is
not a NumPy array or scipy.sparse CSR matrix, a copy may still be
returned.
True
with_mean with_mean: bool, default=True

If True, center the data before scaling.
This does not work (and will raise an exception) when attempted on
sparse matrices, because centering them entails building a dense
matrix which in common use cases is likely to be too large to fit in
memory.
True
with_std with_std: bool, default=True

If True, scale the data to unit variance (or equivalently,
unit standard deviation).
True
Fitted attributes
Name Type Value
mean_ mean_: ndarray of shape (n_features,) or None

The mean value for each feature in the training set.
Equal to ``None`` when ``with_mean=False`` and ``with_std=False``.
ndarray[float64](7,) [ 40.73,-73.95,141.08,..., 5.12,114.73,909.92]
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`.

.. versionadded:: 0.24
int 7
n_samples_seen_ n_samples_seen_: int or ndarray of shape (n_features,)

The number of samples processed by the estimator for each feature.
If there are no missing samples, the ``n_samples_seen`` will be an
integer, otherwise it will be an array of dtype int. If
`sample_weights` are used it will be a float (if no missing data)
or an array of dtype float that sums the weights seen so far.
Will be reset on new calls to fit, but increments across
``partial_fit`` calls.
float64 2.724e+04
scale_ scale_: ndarray of shape (n_features,) or None

Per feature relative scaling of the data to achieve zero mean and unit
variance. Generally this is calculated using `np.sqrt(var_)`. If a
variance is zero, we can't achieve unit variance, and the data is left
as-is, giving a scaling factor of 1. `scale_` is equal to `None`
when `with_std=False`.

.. versionadded:: 0.17
*scale_*
ndarray[float64](7,) [ 0.05, 0.05, 185.52,..., 26.12, 129.44,7280.98]
var_ var_: ndarray of shape (n_features,) or None

The variance for each feature in the training set. Used to compute
`scale_`. Equal to ``None`` when ``with_mean=False`` and
``with_std=False``.
ndarray[float64](7,) [ 0. , 0. , 34419.5 ,..., 682.11, 16753.83, 53012620.7 ]
7 features
x0
x1
x2
x3
x4
x5
x6
['neighbourhood_group', 'neighbourhood', 'room_type']
Parameters
handle_unknown handle_unknown: {'error', 'ignore', 'infrequent_if_exist', 'warn'}, default='error'

Specifies the way unknown categories are handled during :meth:`transform`.

- 'error' : Raise an error if an unknown category is present during transform.
- 'ignore' : When an unknown category is encountered during
transform, the resulting one-hot encoded columns for this feature
will be all zeros. In the inverse transform, an unknown category
will be denoted as None.
- 'infrequent_if_exist' : When an unknown category is encountered
during transform, the resulting one-hot encoded columns for this
feature will map to the infrequent category if it exists. The
infrequent category will be mapped to the last position in the
encoding. During inverse transform, an unknown category will be
mapped to the category denoted `'infrequent'` if it exists. If the
`'infrequent'` category does not exist, then :meth:`transform` and
:meth:`inverse_transform` will handle an unknown category as with
`handle_unknown='ignore'`. Infrequent categories exist based on
`min_frequency` and `max_categories`. Read more in the
:ref:`User Guide <encoder_infrequent_categories>`.
- 'warn' : When an unknown category is encountered during transform
a warning is issued, and the encoding then proceeds as described for
`handle_unknown="infrequent_if_exist"`.

.. versionchanged:: 1.1
`'infrequent_if_exist'` was added to automatically handle unknown
categories and infrequent categories.

.. versionadded:: 1.6
The option `"warn"` was added in 1.6.
'ignore'
categories categories: 'auto' or a list of array-like, default='auto'

Categories (unique values) per feature:

- 'auto' : Determine categories automatically from the training data.
- list : ``categories[i]`` holds the categories expected in the ith
column. The passed categories should not mix strings and numeric
values within a single feature, and should be sorted in case of
numeric values.

The used categories can be found in the ``categories_`` attribute.

.. versionadded:: 0.20
'auto'
drop drop: {'first', 'if_binary'} or an array-like of shape (n_features,), default=None

Specifies a methodology to use to drop one of the categories per
feature. This is useful in situations where perfectly collinear
features cause problems, such as when feeding the resulting data
into an unregularized linear regression model.

However, dropping one category breaks the symmetry of the original
representation and can therefore induce a bias in downstream models,
for instance for penalized linear classification or regression models.

- None : retain all features (the default).
- 'first' : drop the first category in each feature. If only one
category is present, the feature will be dropped entirely.
- 'if_binary' : drop the first category in each feature with two
categories. Features with 1 or more than 2 categories are
left intact.
- array : ``drop[i]`` is the category in feature ``X[:, i]`` that
should be dropped.

When `max_categories` or `min_frequency` is configured to group
infrequent categories, the dropping behavior is handled after the
grouping.

.. versionadded:: 0.21
The parameter `drop` was added in 0.21.

.. versionchanged:: 0.23
The option `drop='if_binary'` was added in 0.23.

.. versionchanged:: 1.1
Support for dropping infrequent categories.
None
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`
True
dtype dtype: number type, default=np.float64

Desired dtype of output.
<class 'numpy.float64'>
min_frequency min_frequency: int or float, default=None

Specifies the minimum frequency below which a category will be
considered infrequent.

- If `int`, categories with a smaller cardinality will be considered
infrequent.

- If `float`, categories with a smaller cardinality than
`min_frequency * n_samples` will be considered infrequent.

.. versionadded:: 1.1
Read more in the :ref:`User Guide <encoder_infrequent_categories>`.
None
max_categories max_categories: int, default=None

Specifies an upper limit to the number of output features for each input
feature when considering infrequent categories. If there are infrequent
categories, `max_categories` includes the category representing the
infrequent categories along with the frequent categories. If `None`,
there is no limit to the number of output features.

.. versionadded:: 1.1
Read more in the :ref:`User Guide <encoder_infrequent_categories>`.
None
feature_name_combiner feature_name_combiner: "concat" or callable, default="concat"

Callable with signature `def callable(input_feature, category)` that returns a
string. This is used to create feature names to be returned by
:meth:`get_feature_names_out`.

`"concat"` concatenates encoded feature name and category with
`feature + "_" + str(category)`.E.g. feature X with values 1, 6, 7 create
feature names `X_1, X_6, X_7`.

.. versionadded:: 1.3
'concat'
Fitted attributes
Name Type Value
categories_ categories_: list of arrays

The categories of each feature determined during fitting
(in order of the features in X and corresponding with the output
of ``transform``). This includes the category specified in ``drop``
(if any).
list [array(['Bronx... dtype=object), array(['Aller... dtype=object), array(['Entir... 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](3,) ['neighbourhood_group','neighbourhood','room_type']
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`.

.. versionadded:: 1.0
int 3
100 of 223 features
neighbourhood_group_Bronx
neighbourhood_group_Brooklyn
neighbourhood_group_Manhattan
neighbourhood_group_Queens
neighbourhood_group_Staten Island
neighbourhood_Allerton
neighbourhood_Arden Heights
neighbourhood_Arrochar
neighbourhood_Arverne
neighbourhood_Astoria
neighbourhood_Bath Beach
neighbourhood_Battery Park City
neighbourhood_Bay Ridge
neighbourhood_Bay Terrace
neighbourhood_Bay Terrace, Staten Island
neighbourhood_Baychester
neighbourhood_Bayside
neighbourhood_Bayswater
neighbourhood_Bedford-Stuyvesant
neighbourhood_Belle Harbor
neighbourhood_Bellerose
neighbourhood_Belmont
neighbourhood_Bensonhurst
neighbourhood_Bergen Beach
neighbourhood_Boerum Hill
neighbourhood_Borough Park
neighbourhood_Breezy Point
neighbourhood_Briarwood
neighbourhood_Brighton Beach
neighbourhood_Bronxdale
neighbourhood_Brooklyn Heights
neighbourhood_Brownsville
neighbourhood_Bull's Head
neighbourhood_Bushwick
neighbourhood_Cambria Heights
neighbourhood_Canarsie
neighbourhood_Carroll Gardens
neighbourhood_Castle Hill
neighbourhood_Castleton Corners
neighbourhood_Chelsea
neighbourhood_Chinatown
neighbourhood_City Island
neighbourhood_Civic Center
neighbourhood_Claremont Village
neighbourhood_Clason Point
neighbourhood_Clifton
neighbourhood_Clinton Hill
neighbourhood_Co-op City
neighbourhood_Cobble Hill
neighbourhood_College Point
neighbourhood_Columbia St
neighbourhood_Concord
neighbourhood_Concourse
neighbourhood_Concourse Village
neighbourhood_Coney Island
neighbourhood_Corona
neighbourhood_Crown Heights
neighbourhood_Cypress Hills
neighbourhood_DUMBO
neighbourhood_Ditmars Steinway
neighbourhood_Dongan Hills
neighbourhood_Douglaston
neighbourhood_Downtown Brooklyn
neighbourhood_Dyker Heights
neighbourhood_East Elmhurst
neighbourhood_East Flatbush
neighbourhood_East Harlem
neighbourhood_East Morrisania
neighbourhood_East New York
neighbourhood_East Village
neighbourhood_Eastchester
neighbourhood_Edenwald
neighbourhood_Edgemere
neighbourhood_Elmhurst
neighbourhood_Eltingville
neighbourhood_Emerson Hill
neighbourhood_Far Rockaway
neighbourhood_Fieldston
neighbourhood_Financial District
neighbourhood_Flatbush
neighbourhood_Flatiron District
neighbourhood_Flatlands
neighbourhood_Flushing
neighbourhood_Fordham
neighbourhood_Forest Hills
neighbourhood_Fort Greene
neighbourhood_Fort Hamilton
neighbourhood_Fresh Meadows
neighbourhood_Glendale
neighbourhood_Gowanus
neighbourhood_Gramercy
neighbourhood_Graniteville
neighbourhood_Grant City
neighbourhood_Gravesend
neighbourhood_Great Kills
neighbourhood_Greenpoint
neighbourhood_Greenwich Village
neighbourhood_Grymes Hill
neighbourhood_Harlem
neighbourhood_Hell's Kitchen
name
Parameters
stop_words stop_words: {'english'}, list, default=None

If 'english', a built-in stop word list for English is used.
There are several known issues with 'english' and you should
consider an alternative (see :ref:`stop_words`).

If a list, that list is assumed to contain stop words, all of which
will be removed from the resulting tokens.
Only applies if ``analyzer == 'word'``.

If None, no stop words will be used. In this case, setting `max_df`
to a higher value, such as in the range (0.7, 1.0), can automatically detect
and filter stop words based on intra corpus document frequency of terms.
'english'
max_features max_features: int, default=None

If not None, build a vocabulary that only consider the top
`max_features` ordered by term frequency across the corpus.
Otherwise, all features are used.

This parameter is ignored if vocabulary is not None.
100
input input: {'filename', 'file', 'content'}, default='content'

- If `'filename'`, the sequence passed as an argument to fit is
expected to be a list of filenames that need reading to fetch
the raw content to analyze.

- If `'file'`, the sequence items must have a 'read' method (file-like
object) that is called to fetch the bytes in memory.

- If `'content'`, the input is expected to be a sequence of items that
can be of type string or byte.
'content'
encoding encoding: str, default='utf-8'

If bytes or files are given to analyze, this encoding is used to
decode.
'utf-8'
decode_error decode_error: {'strict', 'ignore', 'replace'}, default='strict'

Instruction on what to do if a byte sequence is given to analyze that
contains characters not of the given `encoding`. By default, it is
'strict', meaning that a UnicodeDecodeError will be raised. Other
values are 'ignore' and 'replace'.
'strict'
strip_accents strip_accents: {'ascii', 'unicode'} or callable, default=None

Remove accents and perform other character normalization
during the preprocessing step.
'ascii' is a fast method that only works on characters that have
a direct ASCII mapping.
'unicode' is a slightly slower method that works on any characters.
None (default) means no character normalization is performed.

Both 'ascii' and 'unicode' use NFKD normalization from
:func:`unicodedata.normalize`.
None
lowercase lowercase: bool, default=True

Convert all characters to lowercase before tokenizing.
True
preprocessor preprocessor: callable, default=None

Override the preprocessing (strip_accents and lowercase) stage while
preserving the tokenizing and n-grams generation steps.
Only applies if ``analyzer`` is not callable.
None
tokenizer tokenizer: callable, default=None

Override the string tokenization step while preserving the
preprocessing and n-grams generation steps.
Only applies if ``analyzer == 'word'``.
None
token_pattern token_pattern: str or None, default=r"(?u)\\b\\w\\w+\\b"

Regular expression denoting what constitutes a "token", only used
if ``analyzer == 'word'``. The default regexp select tokens of 2
or more alphanumeric characters (punctuation is completely ignored
and always treated as a token separator).

If there is a capturing group in token_pattern then the
captured group content, not the entire match, becomes the token.
At most one capturing group is permitted.
'(?u)\\b\\w\\w+\\b'
ngram_range ngram_range: tuple (min_n, max_n), default=(1, 1)

The lower and upper boundary of the range of n-values for different
word n-grams or char n-grams to be extracted. All values of n such
such that min_n <= n <= max_n will be used. For example an
``ngram_range`` of ``(1, 1)`` means only unigrams, ``(1, 2)`` means
unigrams and bigrams, and ``(2, 2)`` means only bigrams.
Only applies if ``analyzer`` is not callable.
(1, ...)
analyzer analyzer: {'word', 'char', 'char_wb'} or callable, default='word'

Whether the feature should be made of word n-gram or character
n-grams.
Option 'char_wb' creates character n-grams only from text inside
word boundaries; n-grams at the edges of words are padded with space.

If a callable is passed it is used to extract the sequence of features
out of the raw, unprocessed input.

.. versionchanged:: 0.21

Since v0.21, if ``input`` is ``filename`` or ``file``, the data is
first read from the file and then passed to the given callable
analyzer.
'word'
max_df max_df: float in range [0.0, 1.0] or int, default=1.0

When building the vocabulary ignore terms that have a document
frequency strictly higher than the given threshold (corpus-specific
stop words).
If float, the parameter represents a proportion of documents, integer
absolute counts.
This parameter is ignored if vocabulary is not None.
1.0
min_df min_df: float in range [0.0, 1.0] or int, default=1

When building the vocabulary ignore terms that have a document
frequency strictly lower than the given threshold. This value is also
called cut-off in the literature.
If float, the parameter represents a proportion of documents, integer
absolute counts.
This parameter is ignored if vocabulary is not None.
1
vocabulary vocabulary: Mapping or iterable, default=None

Either a Mapping (e.g., a dict) where keys are terms and values are
indices in the feature matrix, or an iterable over terms. If not
given, a vocabulary is determined from the input documents. Indices
in the mapping should not be repeated and should not have any gap
between 0 and the largest index.
None
binary binary: bool, default=False

If True, all non zero counts are set to 1. This is useful for discrete
probabilistic models that model binary events rather than integer
counts.
False
dtype dtype: dtype, default=np.int64

Type of the matrix returned by fit_transform() or transform().
<class 'numpy.int64'>
Fitted attributes
Name Type Value
fixed_vocabulary_ fixed_vocabulary_: bool

True if a fixed vocabulary of term to indices mapping
is provided by the user.
bool False
vocabulary_ vocabulary_: dict

A mapping of terms to feature indices.
dict {'1br': np.int64(0), '2br': np.int64(1), 'amazing': np.int64(2), 'ap...nt': np.int64(3), ...}
100 features
1br
2br
amazing
apartment
apt
artist
astoria
away
backyard
balcony
bath
bathroom
bdrm
beautiful
bed
bedroom
best
big
bk
br
bright
brooklyn
brownstone
bushwick
central
charming
chelsea
city
clean
close
comfortable
comfy
cozy
duplex
east
entire
floor
garden
gorgeous
great
greenpoint
harlem
heart
heights
hill
historic
home
house
huge
jfk
kitchen
large
location
loft
lovely
lower
luxury
manhattan
midtown
min
mins
minutes
modern
near
new
nice
ny
nyc
oasis
park
perfect
place
prime
private
prospect
queens
quiet
renovated
room
slope
soho
space
spacious
square
studio
stuy
subway
suite
sunny
times
townhouse
train
upper
uws
view
views
village
west
williamsburg
york
100 of 330 features
pipeline__latitude
pipeline__longitude
pipeline__price
pipeline__minimum_nights
pipeline__calculated_host_listings_count
pipeline__availability_365
pipeline__minimum_cost
onehotencoder__neighbourhood_group_Bronx
onehotencoder__neighbourhood_group_Brooklyn
onehotencoder__neighbourhood_group_Manhattan
onehotencoder__neighbourhood_group_Queens
onehotencoder__neighbourhood_group_Staten Island
onehotencoder__neighbourhood_Allerton
onehotencoder__neighbourhood_Arden Heights
onehotencoder__neighbourhood_Arrochar
onehotencoder__neighbourhood_Arverne
onehotencoder__neighbourhood_Astoria
onehotencoder__neighbourhood_Bath Beach
onehotencoder__neighbourhood_Battery Park City
onehotencoder__neighbourhood_Bay Ridge
onehotencoder__neighbourhood_Bay Terrace
onehotencoder__neighbourhood_Bay Terrace, Staten Island
onehotencoder__neighbourhood_Baychester
onehotencoder__neighbourhood_Bayside
onehotencoder__neighbourhood_Bayswater
onehotencoder__neighbourhood_Bedford-Stuyvesant
onehotencoder__neighbourhood_Belle Harbor
onehotencoder__neighbourhood_Bellerose
onehotencoder__neighbourhood_Belmont
onehotencoder__neighbourhood_Bensonhurst
onehotencoder__neighbourhood_Bergen Beach
onehotencoder__neighbourhood_Boerum Hill
onehotencoder__neighbourhood_Borough Park
onehotencoder__neighbourhood_Breezy Point
onehotencoder__neighbourhood_Briarwood
onehotencoder__neighbourhood_Brighton Beach
onehotencoder__neighbourhood_Bronxdale
onehotencoder__neighbourhood_Brooklyn Heights
onehotencoder__neighbourhood_Brownsville
onehotencoder__neighbourhood_Bull's Head
onehotencoder__neighbourhood_Bushwick
onehotencoder__neighbourhood_Cambria Heights
onehotencoder__neighbourhood_Canarsie
onehotencoder__neighbourhood_Carroll Gardens
onehotencoder__neighbourhood_Castle Hill
onehotencoder__neighbourhood_Castleton Corners
onehotencoder__neighbourhood_Chelsea
onehotencoder__neighbourhood_Chinatown
onehotencoder__neighbourhood_City Island
onehotencoder__neighbourhood_Civic Center
onehotencoder__neighbourhood_Claremont Village
onehotencoder__neighbourhood_Clason Point
onehotencoder__neighbourhood_Clifton
onehotencoder__neighbourhood_Clinton Hill
onehotencoder__neighbourhood_Co-op City
onehotencoder__neighbourhood_Cobble Hill
onehotencoder__neighbourhood_College Point
onehotencoder__neighbourhood_Columbia St
onehotencoder__neighbourhood_Concord
onehotencoder__neighbourhood_Concourse
onehotencoder__neighbourhood_Concourse Village
onehotencoder__neighbourhood_Coney Island
onehotencoder__neighbourhood_Corona
onehotencoder__neighbourhood_Crown Heights
onehotencoder__neighbourhood_Cypress Hills
onehotencoder__neighbourhood_DUMBO
onehotencoder__neighbourhood_Ditmars Steinway
onehotencoder__neighbourhood_Dongan Hills
onehotencoder__neighbourhood_Douglaston
onehotencoder__neighbourhood_Downtown Brooklyn
onehotencoder__neighbourhood_Dyker Heights
onehotencoder__neighbourhood_East Elmhurst
onehotencoder__neighbourhood_East Flatbush
onehotencoder__neighbourhood_East Harlem
onehotencoder__neighbourhood_East Morrisania
onehotencoder__neighbourhood_East New York
onehotencoder__neighbourhood_East Village
onehotencoder__neighbourhood_Eastchester
onehotencoder__neighbourhood_Edenwald
onehotencoder__neighbourhood_Edgemere
onehotencoder__neighbourhood_Elmhurst
onehotencoder__neighbourhood_Eltingville
onehotencoder__neighbourhood_Emerson Hill
onehotencoder__neighbourhood_Far Rockaway
onehotencoder__neighbourhood_Fieldston
onehotencoder__neighbourhood_Financial District
onehotencoder__neighbourhood_Flatbush
onehotencoder__neighbourhood_Flatiron District
onehotencoder__neighbourhood_Flatlands
onehotencoder__neighbourhood_Flushing
onehotencoder__neighbourhood_Fordham
onehotencoder__neighbourhood_Forest Hills
onehotencoder__neighbourhood_Fort Greene
onehotencoder__neighbourhood_Fort Hamilton
onehotencoder__neighbourhood_Fresh Meadows
onehotencoder__neighbourhood_Glendale
onehotencoder__neighbourhood_Gowanus
onehotencoder__neighbourhood_Gramercy
onehotencoder__neighbourhood_Graniteville
onehotencoder__neighbourhood_Grant City
Parameters
n_estimators n_estimators: int, default=100

The number of trees in the forest.

.. versionchanged:: 0.22
The default value of ``n_estimators`` changed from 10 to 100
in 0.22.
10
max_depth max_depth: int, default=None

The maximum depth of the tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
20
min_samples_leaf min_samples_leaf: int or float, default=1

The minimum number of samples required to be at a leaf node.
A split point at any depth will only be considered if it leaves at
least ``min_samples_leaf`` training samples in each of the left and
right branches. This may have the effect of smoothing the model,
especially in regression.

- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a fraction and
`ceil(min_samples_leaf * n_samples)` are the minimum
number of samples for each node.

.. versionchanged:: 0.18
Added float values for fractions.
10
random_state random_state: int, RandomState instance or None, default=None

Controls both the randomness of the bootstrapping of the samples used
when building trees (if ``bootstrap=True``) and the sampling of the
features to consider when looking for the best split at each node
(if ``max_features < n_features``).
See :term:`Glossary <random_state>` for details.
123
criterion criterion: {"squared_error", "absolute_error", "poisson"}, default="squared_error"

The function to measure the quality of a split. Supported criteria
are "squared_error" for the mean squared error, which is equal to
variance reduction as feature selection criterion and minimizes the L2
loss using the mean of each terminal node, "absolute_error" for the mean
absolute error, which minimizes the L1 loss using the median of each terminal
node, and "poisson" which uses reduction in Poisson deviance to find splits,
also using the mean of each terminal node.

.. versionadded:: 0.18
Mean Absolute Error (MAE) criterion.

.. versionadded:: 1.0
Poisson criterion.

.. versionchanged:: 1.9
Criterion `"friedman_mse"` was deprecated.
'squared_error'
min_samples_split min_samples_split: int or float, default=2

The minimum number of samples required to split an internal node:

- If int, then consider `min_samples_split` as the minimum number.
- If float, then `min_samples_split` is a fraction and
`ceil(min_samples_split * n_samples)` are the minimum
number of samples for each split.

.. versionchanged:: 0.18
Added float values for fractions.
2
min_weight_fraction_leaf min_weight_fraction_leaf: float, default=0.0

The minimum weighted fraction of the sum total of weights (of all
the input samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided.
0.0
max_features max_features: {"sqrt", "log2", None}, int or float, default=1.0

The number of features to consider when looking for the best split:

- If int, then consider `max_features` features at each split.
- If float, then `max_features` is a fraction and
`max(1, int(max_features * n_features_in_))` features are considered at each
split.
- If "sqrt", then `max_features=sqrt(n_features)`.
- If "log2", then `max_features=log2(n_features)`.
- If None or 1.0, then `max_features=n_features`.

.. note::
The default of 1.0 is equivalent to bagged trees and more
randomness can be achieved by setting smaller values, e.g. 0.3.

.. versionchanged:: 1.1
The default of `max_features` changed from `"auto"` to 1.0.

Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than ``max_features`` features.
1.0
max_leaf_nodes max_leaf_nodes: int, default=None

Grow trees with ``max_leaf_nodes`` in best-first fashion.
Best nodes are defined as relative reduction in impurity.
If None then unlimited number of leaf nodes.
None
min_impurity_decrease min_impurity_decrease: float, default=0.0

A node will be split if this split induces a decrease of the impurity
greater than or equal to this value.

The weighted impurity decrease equation is the following::

N_t / N * (impurity - N_t_R / N_t * right_impurity
- N_t_L / N_t * left_impurity)

where ``N`` is the total number of samples, ``N_t`` is the number of
samples at the current node, ``N_t_L`` is the number of samples in the
left child, and ``N_t_R`` is the number of samples in the right child.

``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
if ``sample_weight`` is passed.

.. versionadded:: 0.19
0.0
bootstrap bootstrap: bool, default=True

Whether bootstrap samples are used when building trees. If False, the
whole dataset is used to build each tree.
True
oob_score oob_score: bool or callable, default=False

Whether to use out-of-bag samples to estimate the generalization score.
By default, :func:`~sklearn.metrics.r2_score` is used.
Provide a callable with signature `metric(y_true, y_pred)` to use a
custom metric. Only available if `bootstrap=True`.

For an illustration of out-of-bag (OOB) error estimation, see the example
:ref:`sphx_glr_auto_examples_ensemble_plot_ensemble_oob.py`.
False
n_jobs n_jobs: int, default=None

The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`,
:meth:`decision_path` and :meth:`apply` are all parallelized over the
trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`
context. ``-1`` means using all processors. See :term:`Glossary
<n_jobs>` for more details.
None
verbose verbose: int, default=0

Controls the verbosity when fitting and predicting.
0
warm_start warm_start: bool, default=False

When set to ``True``, reuse the solution of the previous call to fit
and add more estimators to the ensemble, otherwise, just fit a whole
new forest. See :term:`Glossary <warm_start>` and
:ref:`tree_ensemble_warm_start` for details.
False
ccp_alpha ccp_alpha: non-negative float, default=0.0

Complexity parameter used for Minimal Cost-Complexity Pruning. The
subtree with the largest cost complexity that is smaller than
``ccp_alpha`` will be chosen. By default, no pruning is performed. See
:ref:`minimal_cost_complexity_pruning` for details. See
:ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py`
for an example of such pruning.

.. versionadded:: 0.22
0.0
max_samples max_samples: int or float, default=None

If bootstrap is True, the number of samples to draw from X
to train each base estimator.

- If None (default), then draw `X.shape[0]` samples irrespective of
`sample_weight`.
- If int, then draw `max_samples` samples.
- If float, then draw `max_samples * X.shape[0]` unweighted samples
or `max_samples * sample_weight.sum()` weighted samples.

.. versionadded:: 0.22

.. versionchanged:: 1.9
Float `max_samples` is relative to `sample_weight.sum()` instead of
`X.shape[0]` for weighted samples.
None
monotonic_cst monotonic_cst: array-like of int of shape (n_features,), default=None

Indicates the monotonicity constraint to enforce on each feature.
- 1: monotonically increasing
- 0: no constraint
- -1: monotonically decreasing

If monotonic_cst is None, no constraints are applied.

Monotonicity constraints are not supported for:
- multioutput regressions (i.e. when `n_outputs_ > 1`).

Read more in the :ref:`User Guide <monotonic_cst_gbdt>`.

.. versionadded:: 1.4
None
Fitted attributes
Name Type Value
estimator_ estimator_: :class:`~sklearn.tree.DecisionTreeRegressor`

The child estimator template used to create the collection of fitted
sub-estimators.

.. versionadded:: 1.2
`base_estimator_` was renamed to `estimator_`.
DecisionTreeRegressor DecisionTreeRegressor()
estimators_ estimators_: list of DecisionTreeRegressor

The collection of fitted sub-estimators.
list [DecisionTreeR...ate=843828734), DecisionTreeR...ate=914636141), DecisionTreeR...te=1228959102), DecisionTreeR...te=1840268610), ...]
estimators_samples_ estimators_samples_: list of arrays

The subset of drawn samples (i.e., the in-bag samples) for each base
estimator. Each subset is defined by an array of the indices selected.

.. versionadded:: 1.4
list [array([11780,..., dtype=int32), array([23256,..., dtype=int32), array([10935,..., dtype=int32), array([ 326,..., dtype=int32), ...]
feature_importances_ feature_importances_: ndarray of shape (n_features,)

The impurity-based feature importances.
The higher, the more important the feature.
The importance of a feature is computed as the (normalized)
total reduction of the criterion brought by that feature. It is also
known as the Gini importance.

Warning: impurity-based feature importances can be misleading for
high cardinality features (many unique values). See
:func:`sklearn.inspection.permutation_importance` as an alternative.
ndarray[float64](330,) [0.06,0.08,0.03,...,0. ,0. ,0. ]
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`.

.. versionadded:: 0.24
int 330
n_outputs_ n_outputs_: int

The number of outputs when ``fit`` is performed.
int 1
In [37]:
print("Selected settings:", rf_search.best_params_)
print(f"Selected mean CV MAE: {-rf_search.best_score_:.4f}")
Selected settings: {'randomforestregressor__max_depth': 20, 'randomforestregressor__min_samples_leaf': 10}
Selected mean CV MAE: 0.8660
In [38]:
search_results = pd.DataFrame(rf_search.cv_results_)
result_columns = [
    "param_randomforestregressor__max_depth", "param_randomforestregressor__min_samples_leaf",
    "mean_train_score", "mean_test_score", "std_test_score", "mean_fit_time", "rank_test_score",
]
search_results.sort_values("rank_test_score")[result_columns]
Out[38]:
param_randomforestregressor__max_depth param_randomforestregressor__min_samples_leaf mean_train_score mean_test_score std_test_score mean_fit_time rank_test_score
12 20 10 -0.736121 -0.865977 0.012441 2.041439 1
22 55 10 -0.716642 -0.866274 0.012071 2.024639 2
17 35 10 -0.716809 -0.866293 0.012013 1.997795 3
10 20 1 -0.591365 -0.866612 0.008405 3.274843 4
11 20 5 -0.670779 -0.866843 0.011311 2.198358 5
16 35 5 -0.612189 -0.868419 0.011786 2.744306 6
21 55 5 -0.610773 -0.868508 0.011673 2.961700 7
18 35 20 -0.785562 -0.868556 0.009977 1.502864 8
23 55 20 -0.785559 -0.868560 0.009976 1.470005 9
13 20 20 -0.788860 -0.868840 0.010466 1.491280 10
14 20 25 -0.804379 -0.869840 0.009211 1.308265 11
19 35 25 -0.802930 -0.869851 0.009196 1.343711 12
24 55 25 -0.802930 -0.869851 0.009196 1.314801 12
15 35 1 -0.378676 -0.873391 0.011369 6.469520 14
20 55 1 -0.342703 -0.876574 0.010188 7.923329 15
9 10 25 -0.853085 -0.881853 0.010382 0.885256 16
8 10 20 -0.849585 -0.882064 0.010531 0.920371 17
6 10 5 -0.832302 -0.882310 0.011344 0.978857 18
7 10 10 -0.841541 -0.883235 0.012299 1.045724 19
5 10 1 -0.829029 -0.883981 0.011636 1.005517 20
2 5 10 -0.910163 -0.915862 0.011030 0.447812 21
3 5 20 -0.910856 -0.915991 0.010496 0.446558 22
1 5 5 -0.909953 -0.916239 0.010896 0.455292 23
4 5 25 -0.911709 -0.916327 0.010498 0.458346 24
0 5 1 -0.911450 -0.919178 0.011091 0.442463 25
In [39]:
score_grid = search_results.pivot(
    index="param_randomforestregressor__max_depth",
    columns="param_randomforestregressor__min_samples_leaf",
    values="mean_test_score",
).sort_index().sort_index(axis=1)

score_grid = -score_grid
fig, ax = plt.subplots(figsize=(8, 5))
heatmap = ax.imshow(score_grid.to_numpy(), cmap="viridis", aspect="auto", origin="lower")
ax.set_xticks(range(len(score_grid.columns)), labels=score_grid.columns)
ax.set_yticks(range(len(score_grid.index)), labels=score_grid.index)
ax.set_xlabel("min_samples_leaf")
ax.set_ylabel("max_depth")
for row in range(len(score_grid.index)):
    for col in range(len(score_grid.columns)):
        ax.text(col, row, f"{score_grid.iloc[row, col]:.4f}",
                ha="center", va="center", color="white",
                bbox=dict(facecolor="black", alpha=0.4, edgecolor="none"))
fig.colorbar(heatmap, ax=ax, label="Mean CV MAE")
fig.tight_layout();
No description has been provided for this image

11. Feature importance¶

Through the results, the most important features are availability_365 and minium_nights. The latitude and longitude information are important as well, indicating that the model also use the location information. The custom feature minimun_cost have some effect but not indicates that it has been used to improve the model performance.

In [43]:
# Code referenced from book
forest_pipe = rf_search.best_estimator_
forest_names = (
    forest_pipe.named_steps["columntransformer"].get_feature_names_out()
)
forest_names
Out[43]:
array(['pipeline__latitude', 'pipeline__longitude', 'pipeline__price',
       'pipeline__minimum_nights',
       'pipeline__calculated_host_listings_count',
       'pipeline__availability_365', 'pipeline__minimum_cost',
       'onehotencoder__neighbourhood_group_Bronx',
       'onehotencoder__neighbourhood_group_Brooklyn',
       'onehotencoder__neighbourhood_group_Manhattan',
       'onehotencoder__neighbourhood_group_Queens',
       'onehotencoder__neighbourhood_group_Staten Island',
       'onehotencoder__neighbourhood_Allerton',
       'onehotencoder__neighbourhood_Arden Heights',
       'onehotencoder__neighbourhood_Arrochar',
       'onehotencoder__neighbourhood_Arverne',
       'onehotencoder__neighbourhood_Astoria',
       'onehotencoder__neighbourhood_Bath Beach',
       'onehotencoder__neighbourhood_Battery Park City',
       'onehotencoder__neighbourhood_Bay Ridge',
       'onehotencoder__neighbourhood_Bay Terrace',
       'onehotencoder__neighbourhood_Bay Terrace, Staten Island',
       'onehotencoder__neighbourhood_Baychester',
       'onehotencoder__neighbourhood_Bayside',
       'onehotencoder__neighbourhood_Bayswater',
       'onehotencoder__neighbourhood_Bedford-Stuyvesant',
       'onehotencoder__neighbourhood_Belle Harbor',
       'onehotencoder__neighbourhood_Bellerose',
       'onehotencoder__neighbourhood_Belmont',
       'onehotencoder__neighbourhood_Bensonhurst',
       'onehotencoder__neighbourhood_Bergen Beach',
       'onehotencoder__neighbourhood_Boerum Hill',
       'onehotencoder__neighbourhood_Borough Park',
       'onehotencoder__neighbourhood_Breezy Point',
       'onehotencoder__neighbourhood_Briarwood',
       'onehotencoder__neighbourhood_Brighton Beach',
       'onehotencoder__neighbourhood_Bronxdale',
       'onehotencoder__neighbourhood_Brooklyn Heights',
       'onehotencoder__neighbourhood_Brownsville',
       "onehotencoder__neighbourhood_Bull's Head",
       'onehotencoder__neighbourhood_Bushwick',
       'onehotencoder__neighbourhood_Cambria Heights',
       'onehotencoder__neighbourhood_Canarsie',
       'onehotencoder__neighbourhood_Carroll Gardens',
       'onehotencoder__neighbourhood_Castle Hill',
       'onehotencoder__neighbourhood_Castleton Corners',
       'onehotencoder__neighbourhood_Chelsea',
       'onehotencoder__neighbourhood_Chinatown',
       'onehotencoder__neighbourhood_City Island',
       'onehotencoder__neighbourhood_Civic Center',
       'onehotencoder__neighbourhood_Claremont Village',
       'onehotencoder__neighbourhood_Clason Point',
       'onehotencoder__neighbourhood_Clifton',
       'onehotencoder__neighbourhood_Clinton Hill',
       'onehotencoder__neighbourhood_Co-op City',
       'onehotencoder__neighbourhood_Cobble Hill',
       'onehotencoder__neighbourhood_College Point',
       'onehotencoder__neighbourhood_Columbia St',
       'onehotencoder__neighbourhood_Concord',
       'onehotencoder__neighbourhood_Concourse',
       'onehotencoder__neighbourhood_Concourse Village',
       'onehotencoder__neighbourhood_Coney Island',
       'onehotencoder__neighbourhood_Corona',
       'onehotencoder__neighbourhood_Crown Heights',
       'onehotencoder__neighbourhood_Cypress Hills',
       'onehotencoder__neighbourhood_DUMBO',
       'onehotencoder__neighbourhood_Ditmars Steinway',
       'onehotencoder__neighbourhood_Dongan Hills',
       'onehotencoder__neighbourhood_Douglaston',
       'onehotencoder__neighbourhood_Downtown Brooklyn',
       'onehotencoder__neighbourhood_Dyker Heights',
       'onehotencoder__neighbourhood_East Elmhurst',
       'onehotencoder__neighbourhood_East Flatbush',
       'onehotencoder__neighbourhood_East Harlem',
       'onehotencoder__neighbourhood_East Morrisania',
       'onehotencoder__neighbourhood_East New York',
       'onehotencoder__neighbourhood_East Village',
       'onehotencoder__neighbourhood_Eastchester',
       'onehotencoder__neighbourhood_Edenwald',
       'onehotencoder__neighbourhood_Edgemere',
       'onehotencoder__neighbourhood_Elmhurst',
       'onehotencoder__neighbourhood_Eltingville',
       'onehotencoder__neighbourhood_Emerson Hill',
       'onehotencoder__neighbourhood_Far Rockaway',
       'onehotencoder__neighbourhood_Fieldston',
       'onehotencoder__neighbourhood_Financial District',
       'onehotencoder__neighbourhood_Flatbush',
       'onehotencoder__neighbourhood_Flatiron District',
       'onehotencoder__neighbourhood_Flatlands',
       'onehotencoder__neighbourhood_Flushing',
       'onehotencoder__neighbourhood_Fordham',
       'onehotencoder__neighbourhood_Forest Hills',
       'onehotencoder__neighbourhood_Fort Greene',
       'onehotencoder__neighbourhood_Fort Hamilton',
       'onehotencoder__neighbourhood_Fresh Meadows',
       'onehotencoder__neighbourhood_Glendale',
       'onehotencoder__neighbourhood_Gowanus',
       'onehotencoder__neighbourhood_Gramercy',
       'onehotencoder__neighbourhood_Graniteville',
       'onehotencoder__neighbourhood_Grant City',
       'onehotencoder__neighbourhood_Gravesend',
       'onehotencoder__neighbourhood_Great Kills',
       'onehotencoder__neighbourhood_Greenpoint',
       'onehotencoder__neighbourhood_Greenwich Village',
       'onehotencoder__neighbourhood_Grymes Hill',
       'onehotencoder__neighbourhood_Harlem',
       "onehotencoder__neighbourhood_Hell's Kitchen",
       'onehotencoder__neighbourhood_Highbridge',
       'onehotencoder__neighbourhood_Hollis',
       'onehotencoder__neighbourhood_Holliswood',
       'onehotencoder__neighbourhood_Howard Beach',
       'onehotencoder__neighbourhood_Howland Hook',
       'onehotencoder__neighbourhood_Huguenot',
       'onehotencoder__neighbourhood_Hunts Point',
       'onehotencoder__neighbourhood_Inwood',
       'onehotencoder__neighbourhood_Jackson Heights',
       'onehotencoder__neighbourhood_Jamaica',
       'onehotencoder__neighbourhood_Jamaica Estates',
       'onehotencoder__neighbourhood_Jamaica Hills',
       'onehotencoder__neighbourhood_Kensington',
       'onehotencoder__neighbourhood_Kew Gardens',
       'onehotencoder__neighbourhood_Kew Gardens Hills',
       'onehotencoder__neighbourhood_Kingsbridge',
       'onehotencoder__neighbourhood_Kips Bay',
       'onehotencoder__neighbourhood_Laurelton',
       'onehotencoder__neighbourhood_Lighthouse Hill',
       'onehotencoder__neighbourhood_Little Italy',
       'onehotencoder__neighbourhood_Little Neck',
       'onehotencoder__neighbourhood_Long Island City',
       'onehotencoder__neighbourhood_Longwood',
       'onehotencoder__neighbourhood_Lower East Side',
       'onehotencoder__neighbourhood_Manhattan Beach',
       'onehotencoder__neighbourhood_Marble Hill',
       'onehotencoder__neighbourhood_Mariners Harbor',
       'onehotencoder__neighbourhood_Maspeth',
       'onehotencoder__neighbourhood_Melrose',
       'onehotencoder__neighbourhood_Middle Village',
       'onehotencoder__neighbourhood_Midland Beach',
       'onehotencoder__neighbourhood_Midtown',
       'onehotencoder__neighbourhood_Midwood',
       'onehotencoder__neighbourhood_Mill Basin',
       'onehotencoder__neighbourhood_Morningside Heights',
       'onehotencoder__neighbourhood_Morris Heights',
       'onehotencoder__neighbourhood_Morris Park',
       'onehotencoder__neighbourhood_Morrisania',
       'onehotencoder__neighbourhood_Mott Haven',
       'onehotencoder__neighbourhood_Mount Eden',
       'onehotencoder__neighbourhood_Mount Hope',
       'onehotencoder__neighbourhood_Murray Hill',
       'onehotencoder__neighbourhood_Navy Yard',
       'onehotencoder__neighbourhood_Neponsit',
       'onehotencoder__neighbourhood_New Brighton',
       'onehotencoder__neighbourhood_New Dorp Beach',
       'onehotencoder__neighbourhood_New Springville',
       'onehotencoder__neighbourhood_NoHo',
       'onehotencoder__neighbourhood_Nolita',
       'onehotencoder__neighbourhood_North Riverdale',
       'onehotencoder__neighbourhood_Norwood',
       'onehotencoder__neighbourhood_Oakwood',
       'onehotencoder__neighbourhood_Olinville',
       'onehotencoder__neighbourhood_Ozone Park',
       'onehotencoder__neighbourhood_Park Slope',
       'onehotencoder__neighbourhood_Parkchester',
       'onehotencoder__neighbourhood_Pelham Bay',
       'onehotencoder__neighbourhood_Pelham Gardens',
       'onehotencoder__neighbourhood_Port Morris',
       'onehotencoder__neighbourhood_Port Richmond',
       'onehotencoder__neighbourhood_Prospect Heights',
       'onehotencoder__neighbourhood_Prospect-Lefferts Gardens',
       'onehotencoder__neighbourhood_Queens Village',
       'onehotencoder__neighbourhood_Randall Manor',
       'onehotencoder__neighbourhood_Red Hook',
       'onehotencoder__neighbourhood_Rego Park',
       'onehotencoder__neighbourhood_Richmond Hill',
       'onehotencoder__neighbourhood_Richmondtown',
       'onehotencoder__neighbourhood_Ridgewood',
       'onehotencoder__neighbourhood_Riverdale',
       'onehotencoder__neighbourhood_Rockaway Beach',
       'onehotencoder__neighbourhood_Roosevelt Island',
       'onehotencoder__neighbourhood_Rosebank',
       'onehotencoder__neighbourhood_Rosedale',
       'onehotencoder__neighbourhood_Rossville',
       'onehotencoder__neighbourhood_Schuylerville',
       'onehotencoder__neighbourhood_Sea Gate',
       'onehotencoder__neighbourhood_Sheepshead Bay',
       'onehotencoder__neighbourhood_Shore Acres',
       'onehotencoder__neighbourhood_Silver Lake',
       'onehotencoder__neighbourhood_SoHo',
       'onehotencoder__neighbourhood_Soundview',
       'onehotencoder__neighbourhood_South Beach',
       'onehotencoder__neighbourhood_South Ozone Park',
       'onehotencoder__neighbourhood_South Slope',
       'onehotencoder__neighbourhood_Springfield Gardens',
       'onehotencoder__neighbourhood_Spuyten Duyvil',
       'onehotencoder__neighbourhood_St. Albans',
       'onehotencoder__neighbourhood_St. George',
       'onehotencoder__neighbourhood_Stapleton',
       'onehotencoder__neighbourhood_Stuyvesant Town',
       'onehotencoder__neighbourhood_Sunnyside',
       'onehotencoder__neighbourhood_Sunset Park',
       'onehotencoder__neighbourhood_Theater District',
       'onehotencoder__neighbourhood_Throgs Neck',
       'onehotencoder__neighbourhood_Tompkinsville',
       'onehotencoder__neighbourhood_Tottenville',
       'onehotencoder__neighbourhood_Tremont',
       'onehotencoder__neighbourhood_Tribeca',
       'onehotencoder__neighbourhood_Two Bridges',
       'onehotencoder__neighbourhood_Unionport',
       'onehotencoder__neighbourhood_University Heights',
       'onehotencoder__neighbourhood_Upper East Side',
       'onehotencoder__neighbourhood_Upper West Side',
       'onehotencoder__neighbourhood_Van Nest',
       'onehotencoder__neighbourhood_Vinegar Hill',
       'onehotencoder__neighbourhood_Wakefield',
       'onehotencoder__neighbourhood_Washington Heights',
       'onehotencoder__neighbourhood_West Brighton',
       'onehotencoder__neighbourhood_West Farms',
       'onehotencoder__neighbourhood_West Village',
       'onehotencoder__neighbourhood_Westchester Square',
       'onehotencoder__neighbourhood_Westerleigh',
       'onehotencoder__neighbourhood_Whitestone',
       'onehotencoder__neighbourhood_Williamsbridge',
       'onehotencoder__neighbourhood_Williamsburg',
       'onehotencoder__neighbourhood_Windsor Terrace',
       'onehotencoder__neighbourhood_Woodhaven',
       'onehotencoder__neighbourhood_Woodlawn',
       'onehotencoder__neighbourhood_Woodside',
       'onehotencoder__room_type_Entire home/apt',
       'onehotencoder__room_type_Private room',
       'onehotencoder__room_type_Shared room', 'countvectorizer__1br',
       'countvectorizer__2br', 'countvectorizer__amazing',
       'countvectorizer__apartment', 'countvectorizer__apt',
       'countvectorizer__artist', 'countvectorizer__astoria',
       'countvectorizer__away', 'countvectorizer__backyard',
       'countvectorizer__balcony', 'countvectorizer__bath',
       'countvectorizer__bathroom', 'countvectorizer__bdrm',
       'countvectorizer__beautiful', 'countvectorizer__bed',
       'countvectorizer__bedroom', 'countvectorizer__best',
       'countvectorizer__big', 'countvectorizer__bk',
       'countvectorizer__br', 'countvectorizer__bright',
       'countvectorizer__brooklyn', 'countvectorizer__brownstone',
       'countvectorizer__bushwick', 'countvectorizer__central',
       'countvectorizer__charming', 'countvectorizer__chelsea',
       'countvectorizer__city', 'countvectorizer__clean',
       'countvectorizer__close', 'countvectorizer__comfortable',
       'countvectorizer__comfy', 'countvectorizer__cozy',
       'countvectorizer__duplex', 'countvectorizer__east',
       'countvectorizer__entire', 'countvectorizer__floor',
       'countvectorizer__garden', 'countvectorizer__gorgeous',
       'countvectorizer__great', 'countvectorizer__greenpoint',
       'countvectorizer__harlem', 'countvectorizer__heart',
       'countvectorizer__heights', 'countvectorizer__hill',
       'countvectorizer__historic', 'countvectorizer__home',
       'countvectorizer__house', 'countvectorizer__huge',
       'countvectorizer__jfk', 'countvectorizer__kitchen',
       'countvectorizer__large', 'countvectorizer__location',
       'countvectorizer__loft', 'countvectorizer__lovely',
       'countvectorizer__lower', 'countvectorizer__luxury',
       'countvectorizer__manhattan', 'countvectorizer__midtown',
       'countvectorizer__min', 'countvectorizer__mins',
       'countvectorizer__minutes', 'countvectorizer__modern',
       'countvectorizer__near', 'countvectorizer__new',
       'countvectorizer__nice', 'countvectorizer__ny',
       'countvectorizer__nyc', 'countvectorizer__oasis',
       'countvectorizer__park', 'countvectorizer__perfect',
       'countvectorizer__place', 'countvectorizer__prime',
       'countvectorizer__private', 'countvectorizer__prospect',
       'countvectorizer__queens', 'countvectorizer__quiet',
       'countvectorizer__renovated', 'countvectorizer__room',
       'countvectorizer__slope', 'countvectorizer__soho',
       'countvectorizer__space', 'countvectorizer__spacious',
       'countvectorizer__square', 'countvectorizer__studio',
       'countvectorizer__stuy', 'countvectorizer__subway',
       'countvectorizer__suite', 'countvectorizer__sunny',
       'countvectorizer__times', 'countvectorizer__townhouse',
       'countvectorizer__train', 'countvectorizer__upper',
       'countvectorizer__uws', 'countvectorizer__view',
       'countvectorizer__views', 'countvectorizer__village',
       'countvectorizer__west', 'countvectorizer__williamsburg',
       'countvectorizer__york'], dtype=object)
In [44]:
impurity_importance = pd.Series(
    forest_pipe.named_steps["randomforestregressor"].feature_importances_,
    index=forest_names,
).sort_values()
In [45]:
impurity_importance.tail(12).plot.barh()
plt.xlabel("Impurity-based importance (share of total)")
plt.title("Random forest: transformed features")
plt.tight_layout()
plt.show()
No description has been provided for this image

12. Test evaluation and SHAP explanations¶

The test MAE of Random forest model is 0.8656 which close to selected CV mean MAE 0.8660. This support the model has similar generalization on the current data. I compared multiple models, so it may affected by optimization bias.

I randomly select 100 records as SHAP reference data. Base value about 1.3355 reviews per month.

  • Record 2964: predict 2.919912, actual 1.93, absolute error 0.989912, avaliability_365 contributes 0.82 and minimun_night contributes 0.62
  • Record 14184: predict 0.331417, actual 0.17, absolute error 0.161417, avaliability_365 contributes −0.53 and minimun_night contributes −0.25
In [54]:
# Code referenced from book and AI was used to help explain concept and syntax
from sklearn.metrics import mean_absolute_error

best_model = rf_search.best_estimator_
test_predictions = best_model.predict(X_test)
print(f"CV MAE: {-rf_search.best_score_:.4f}")
print(f"Test MAE: {mean_absolute_error(y_test, test_predictions):.4f}")
CV MAE: 0.8660
Test MAE: 0.8656
In [55]:
preprocessor = best_model.named_steps["columntransformer"]
forest = best_model.named_steps["randomforestregressor"]
In [56]:
import shap

rf_pipe = rf_search.best_estimator_
rf_preprocessor = rf_pipe.named_steps["columntransformer"]
rf_model = rf_pipe.named_steps["randomforestregressor"]
rf_names = rf_preprocessor.get_feature_names_out()

def encode_for_rf(frame):
    encoded = rf_preprocessor.transform(frame).toarray()
    return pd.DataFrame(encoded, columns=rf_names, index=frame.index)

background = encode_for_rf(
    X_train.sample(n=100, random_state=123)
)

X_explain_raw = X_test.iloc[:2]
X_explain = encode_for_rf(X_explain_raw)

explainer = shap.TreeExplainer(
    rf_model,
    data=background,
    feature_perturbation="interventional",
    model_output="raw",
)
shap_values = explainer(X_explain)
In [57]:
display(pd.DataFrame({
    "actual": y_test.iloc[:2],
    "predicted": test_predictions[:2],
}))
actual predicted
2964 1.93 2.919912
14184 0.17 0.331417
In [58]:
shap.plots.waterfall(shap_values[0], max_display=10)
shap.plots.waterfall(shap_values[1], max_display=10)
No description has been provided for this image
No description has been provided for this image

13. Results summary¶

Model Comment Train MAE Mean CV MAE Test MAE
Dummy baseline median 1.1237 1.1238 —
Ridge alpha=10 1.1048 1.1169 —
kNN k=5 0.8770 1.0879 —
Decision tree max_depth=10 0.8288 0.9067 —
Random forest Before 0.8290 0.8840 —
Random forest After 0.7361 0.8660 0.8656

The test MAE is 0.8656 for the random forest on the test set. It represent the mean absolue error is 0.8656 reviews per month. The test score is close to the CV score, supporting that this model has a similar performance generalization on this data set.

RFECV reduces the number of features but strongly increses the fitting time, while CV MAE only decreased from 0.8840 to 0.8831. Could increase the number of trees for the random forest in thre future.

Final test MAE: 0.8656