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.
Imports¶
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
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¶
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_grouponly has 5 unique values.most listings are in Manhattan and Brooklyn.
There are 6990 records have missing value in the target column.
reviews_per_monthis right skewed.distribution of reviews of different neighbourhood are different.
MAE (mean absolute error): unit is reviews per month.
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
train_df.describe()
| 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 |
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
train_df.isna().sum()
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
print(train_df['neighbourhood_group'].unique().shape[0])
5
train_df["reviews_per_month"].plot.hist(bins=50)
plt.xlabel("Reviews per month")
plt.show()
train_df["neighbourhood_group"].value_counts().plot.bar(rot=0)
plt.ylabel("Number of listings")
plt.show()
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()
4. Feature engineering¶
New feature: minimum_cost: price times minimum_nights, refecting the minimum cost for each listing.
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
| 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_reviewfeature 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 |
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"])
numeric_feats = ["latitude", "longitude", "price", "minimum_nights", "calculated_host_listings_count", "availability_365", "minimum_cost"]
categorical_feats = ["neighbourhood_group", "neighbourhood", "room_type"]
train_df["name"] = train_df["name"].fillna("")
test_df["name"] = test_df["name"].fillna("")
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"),
)
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¶
from sklearn.dummy import DummyRegressor
baseline_pipe = make_pipeline(ct, DummyRegressor(strategy="median"))
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)
pd.DataFrame({
"train_MAE": -baseline_results["train_score"],
"validation_MAE": -baseline_results["test_score"],
}).agg(["mean", "std"])
| 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.
from sklearn.linear_model import Ridge
alphas = [0.01, 0.1, 1, 10, 100, 1000]
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(),
})
linear_summary = pd.DataFrame(linear_results).set_index("alpha")
linear_summary
| 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.
# 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)
| 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 |
# 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)
| 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 |
# 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)
| 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.
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)
| 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 |
# 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.
# Code referenced from book
param_grid = {
"randomforestregressor__max_depth": [5, 10, 20, 35, 55],
"randomforestregressor__min_samples_leaf": [1, 5, 10, 20, 25],
}
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)
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
Fitted attributes
Parameters
Fitted attributes
['latitude', 'longitude', 'price', 'minimum_nights', 'calculated_host_listings_count', 'availability_365', 'minimum_cost']
Parameters
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
Fitted attributes
7 features
| x0 |
| x1 |
| x2 |
| x3 |
| x4 |
| x5 |
| x6 |
['neighbourhood_group', 'neighbourhood', 'room_type']
Parameters
Fitted attributes
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
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
Fitted attributes
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
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]
| 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 |
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();
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.
# Code referenced from book
forest_pipe = rf_search.best_estimator_
forest_names = (
forest_pipe.named_steps["columntransformer"].get_feature_names_out()
)
forest_names
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)
impurity_importance = pd.Series(
forest_pipe.named_steps["randomforestregressor"].feature_importances_,
index=forest_names,
).sort_values()
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()
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_365contributes 0.82 andminimun_nightcontributes 0.62 - Record 14184: predict 0.331417, actual 0.17, absolute error 0.161417,
avaliability_365contributes −0.53 andminimun_nightcontributes −0.25
# 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
preprocessor = best_model.named_steps["columntransformer"]
forest = best_model.named_steps["randomforestregressor"]
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)
display(pd.DataFrame({
"actual": y_test.iloc[:2],
"predicted": test_predictions[:2],
}))
| actual | predicted | |
|---|---|---|
| 2964 | 1.93 | 2.919912 |
| 14184 | 0.17 | 0.331417 |
shap.plots.waterfall(shap_values[0], max_display=10)
shap.plots.waterfall(shap_values[1], max_display=10)
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