-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathairbnb_regression.py
392 lines (279 loc) · 15.4 KB
/
airbnb_regression.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# pylint: disable=C0321,C0103,E1221,C0301,E1305,E1121,C0302,C0330
# -*- coding: utf-8 -*-
"""
python airbnb_regression.py preprocess
python airbnb_regression.py train
python airbnb_regression.py predict
"""
import warnings, copy, os, sys
warnings.filterwarnings('ignore')
###################################################################################
from source import util_feature
####################################################################################
###### Path ########################################################################
print( os.getcwd())
root = os.path.abspath(os.getcwd()).replace("\\", "/") + "/"
print(root)
dir_data = os.path.abspath( root + "/data/" ) + "/"
dir_data = dir_data.replace("\\", "/")
print(dir_data)
def global_pars_update(model_dict, data_name, config_name):
m = {}
model_name = model_dict['model_pars']['model_class']
m['path_config_model'] = root + f"/{config_file}"
m['config_name'] = config_name
m['path_data_train'] = f'data/input/{data_name}/train/'
m['path_data_test'] = f'data/input/{data_name}/test/'
m['path_model'] = f'data/output/{data_name}/{config_name}/'
m['path_output_pred'] = f'data/output/{data_name}/pred_{config_name}/'
m['n_sample'] = model_dict['data_pars'].get('n_sample', 5000)
model_dict[ 'global_pars'] = m
return model_dict
def os_get_function_name():
import sys
return sys._getframe(1).f_code.co_name
######################################################################################
config_file = "airbnb_regression.py"
config_default = 'airbnb_lightgbm'
#####################################################################################
####### y normalization #############################################################
def y_norm(y, inverse=True, mode='boxcox'):
## Normalize the input/output
if mode == 'boxcox':
width0 = 53.0 # 0,1 factor
k1 = 0.6145279599674994 # Optimal boxCox lambda for y
if inverse:
y2 = y * width0
y2 = ((y2 * k1) + 1) ** (1 / k1)
return y2
else:
y1 = (y ** k1 - 1) / k1
y1 = y1 / width0
return y1
if mode == 'norm':
m0, width0 = 0.0, 0.01 ## Min, Max
if inverse:
y1 = (y * width0 + m0)
return y1
else:
y2 = (y - m0) / width0
return y2
else:
return y
####################################################################################
##### Params########################################################################
cols_input_type_1 = {
"coly" : "price"
,"colid" : "id"
,"colcat" : [ "cancellation_policy", "host_response_rate", "host_response_time" ]
,"colnum" : [ "review_scores_communication", "review_scores_location", "review_scores_rating" ]
,"coltext" : [ "house_rules", "neighborhood_overview", "notes", "street" ]
,"coldate" : [ "calendar_last_scraped", "first_review", "host_since" ]
,"colcross" : [ "review_scores_communication", "review_scores_location", "cancellation_policy", "host_response_rate"]
}
cols_input_type_2 = {
"coly" : "price"
,"colid" : "id"
,"colcat" : ["host_id", "host_location", "host_response_time","host_response_rate","host_is_superhost","host_neighbourhood","host_verifications","host_has_profile_pic","host_identity_verified","street","neighbourhood","neighbourhood_cleansed", "neighbourhood_group_cleansed","city","zipcode", "smart_location","is_location_exact","property_type","room_type", "accommodates","bathrooms","bedrooms", "beds","bed_type","guests_included","calendar_updated", "license","instant_bookable","cancellation_policy","require_guest_profile_picture","require_guest_phone_verification","scrape_id"]
,"colnum" : ["host_listings_count","latitude", "longitude","square_feet","weekly_price","monthly_price", "security_deposit","cleaning_fee","extra_people", "minimum_nights","maximum_nights","availability_30","availability_60","availability_90","availability_365","number_of_reviews","review_scores_rating","review_scores_accuracy","review_scores_cleanliness","review_scores_checkin","review_scores_communication", "review_scores_location","review_scores_value","calculated_host_listings_count","reviews_per_month"]
,"coltext" : ["name","summary", "space","description", "neighborhood_overview","notes","transit", "access","interaction", "house_rules","host_name","host_about","amenities"]
, "coldate" : ["last_scraped","host_since","first_review","last_review"]
,"colcross" : ["name","host_is_superhost","is_location_exact","monthly_price","review_scores_value","review_scores_rating","reviews_per_month"]
}
####################################################################################
def airbnb_lightgbm(path_model_out="") :
"""
"""
data_name = "airbnb" ###in data/
model_name = 'LGBMRegressor'
def post_process_fun(y):
return y_norm(y, inverse=True, mode='norm')
def pre_process_fun(y):
return y_norm(y, inverse=False, mode='norm')
#############################################################################
model_dict = {'model_pars': {'model_class': model_name
,'model_path': path_model_out
,'model_pars': {'objective': 'huber',
} # lightgbm one
,'post_process_fun': post_process_fun
,'pre_process_pars': {'y_norm_fun' : copy.deepcopy(pre_process_fun) ,
### Pipeline for data processing ########################
'pipe_list': [
{'uri': 'source/preprocessors.py::pd_coly', 'pars': {}, 'cols_family': 'coly', 'cols_out': 'coly', 'type': 'coly' },
{'uri': 'source/preprocessors.py::pd_colnum_bin', 'pars': {}, 'cols_family': 'colnum', 'cols_out': 'colnum_bin', 'type': '' },
{'uri': 'source/preprocessors.py::pd_colnum_binto_onehot', 'pars': {}, 'cols_family': 'colnum_bin', 'cols_out': 'colnum_onehot', 'type': '' },
{'uri': 'source/preprocessors.py::pd_colcat_bin', 'pars': {}, 'cols_family': 'colcat', 'cols_out': 'colcat_bin', 'type': '' },
{'uri': 'source/preprocessors.py::pd_colcat_to_onehot', 'pars': {}, 'cols_family': 'colcat_bin', 'cols_out': 'colcat_onehot', 'type': '' },
{'uri': 'source/preprocessors.py::pd_coltext', 'pars': {}, 'cols_family': 'coltext', 'cols_out': 'coltext_svd', 'type': '' },
{'uri': 'source/preprocessors.py::pd_coldate', 'pars': {}, 'cols_family': 'coldate', 'cols_out': 'coldate', 'type': '' },
{'uri': 'source/preprocessors.py::pd_colcross', 'pars': {}, 'cols_family': 'colcross', 'cols_out': 'colcross_pair_onehot', 'type': 'cross'}
],
}
},
'compute_pars': { 'metric_list': ['root_mean_squared_error', 'mean_absolute_error', #### sklearm names
'explained_variance_score', 'r2_score', 'median_absolute_error']
},
'data_pars': {
'cols_input_type' : cols_input_type_1
#"colnum", "colnum_bin", "colnum_onehot", "colnum_binmap", #### Colnum columns
#"colcat", "colcat_bin", "colcat_onehot", "colcat_bin_map", #### colcat columns
#'colcross_single_onehot_select', "colcross_pair_onehot", 'colcross_pair', #### colcross columns
# 'coldate', #'coltext', 'coltext_svd'
,'cols_model_group': [ 'colnum'
,'colcat_bin'
,'coltext_svd'
]
,'filter_pars': { 'ymax' : 100000.0 ,'ymin' : 0.0 } ### Filter data
}}
##### Filling Global parameters ############################################################
model_dict = global_pars_update(model_dict, data_name, os_get_function_name() )
return model_dict
#####################################################################################
########## Profile data #############################################################
def data_profile(path_data_train="", path_model="", n_sample= 5000):
from source.run_feature_profile import run_profile
run_profile(path_data = path_data_train,
path_output = path_model + "/profile/",
n_sample = n_sample,
)
###################################################################################
########## Preprocess #############################################################
def preprocess(config=None, nsample=None):
model_class = config if config is not None else config_default
mdict = globals()[model_class]()
m = mdict['global_pars']
from source import run_preprocess, run_preprocess_old
run_preprocess.run_preprocess(config_name= model_class,
path_data = m['path_data_train'],
path_output = m['path_model'],
path_config_model = m['path_config_model'],
n_sample = nsample if nsample is not None else m['n_sample'],
mode = 'run_preprocess')
##################################################################################
########## Train #################################################################
def train(config=None, nsample=None):
model_class = config if config is not None else config_default
mdict = globals()[model_class]()
m = mdict['global_pars']
from source import run_train
run_train.run_train(config_name= model_class,
path_data = m['path_data_train'],
path_output = m['path_model'],
path_config_model = m['path_config_model'],
n_sample = nsample if nsample is not None else m['n_sample']
)
###################################################################################
######### Check data ##############################################################
def check():
pass
####################################################################################
####### Inference ##################################################################
def predict(config=None, nsample=None):
model_class = config if config is not None else config_default
mdict = globals()[model_class]()
m = mdict['global_pars']
print('ssss')
print(mdict)
from source import run_inference,run_inference
run_inference.run_predict(model_class,
path_model = m['path_model'],
path_data = m['path_data_test'],
path_output = m['path_output_pred'],
pars ={'cols_group':mdict['data_pars']['cols_input_type'],
'pipe_list':mdict['model_pars']['pre_process_pars']['pipe_list']},
n_sample = nsample if nsample is not None else m['n_sample']
)
def run_all():
data_profile()
preprocess()
train()
check()
predict()
###########################################################################################################
###########################################################################################################
"""
python airbnb_regression.py preprocess
python airbnb_regression.py train
python airbnb_regression.py check
python airbnb_regression.py predict
python airbnb_regression.py run_all
"""
if __name__ == "__main__":
import fire
fire.Fire()
"""
rm=["name", "summary", "space", "description", "neighborhood_overview", "notes", "transit", "access", "interaction", "house_rules", "host_name", "host_about", "amenities"]
colsX = list(set(colsX) - set(rm))
for col in rm:
col1=col+'_svd_0'
col2=col+'_svd_1'
colsX.append(col1)
colsX.append(col2)
rm1=["last_review", "host_since", "first_review", "last_scraped"]
colsX = list(set(colsX) - set(rm1))
for col in rm1:
col1=col+'_year'
col2=col+'_month'
col3=col+'_day'
colsX.append(col1)
colsX.append(col2)
colsX.append(col3)
dfX.fillna(0)
"""
def airbnb_elasticnetcv(path_model_out=""):
global model_name
model_name = 'ElasticNetCV'
def post_process_fun(y):
return y_norm(y, inverse=True, mode='boxcox')
def pre_process_fun(y):
return y_norm(y, inverse=False, mode='boxcox')
model_dict = {'model_pars': {'model_class': 'ElasticNetCV'
, 'model_path': path_model_out
, 'model_pars': {} # default ones
, 'post_process_fun': post_process_fun
, 'pre_process_pars': {'y_norm_fun' : pre_process_fun,
### Pipeline for data processing.
'pipe_list' : [ 'filter', 'label', 'dfnum_bin', 'dfnum_hot', 'dfcat_bin', 'dfcat_hot', 'dfcross_hot',
'dfdate', 'dftext'
]
}
},
'compute_pars': { 'metric_list': ['root_mean_squared_error', 'mean_absolute_error',
'explained_variance_score', 'r2_score', 'median_absolute_error']
},
'data_pars': {
'cols_input_type' : cols_input_type_1,
'cols_model_group': [ 'colnum_onehot', 'colcat_onehot', 'colcross_onehot' ]
,'cols_model': [] # cols['colcat_model'],
,'coly': [] # cols['coly']
,'filter_pars': { 'ymax' : 100000.0 ,'ymin' : 0.0 } ### Filter data
}}
return model_dict
def airbnb_bayesian_pyro(path_model_out="") :
global model_name
model_name = 'model_bayesian_pyro'
def post_process_fun(y):
return y_norm(y, inverse=True, mode='boxcox')
def pre_process_fun(y):
return y_norm(y, inverse=False, mode='boxcox')
model_dict = {'model_pars': {'model_class': 'model_bayesian_pyro'
, 'model_path': path_model_out
, 'model_pars': {'input_width': 112, } # default
, 'post_process_fun': post_process_fun
, 'pre_process_pars': {'y_norm_fun' : copy.deepcopy(pre_process_fun) ,
### Pipeline for data processing.
'pipe_list' : [ 'filter', 'label', 'dfnum_bin', 'dfnum_hot', 'dfcat_bin', 'dfcat_hot', 'dfcross_hot', ]
}
},
'compute_pars': {'compute_pars': {'n_iter': 1200, 'learning_rate': 0.01}
, 'metric_list': ['root_mean_squared_error', 'mean_absolute_error',
'explained_variance_score', 'r2_score', 'median_absolute_error']
, 'max_size': 1000000
, 'num_samples': 300
},
'data_pars': {
'cols_input_type' : cols_input_type_1
,'cols_model_group': [ 'colnum_onehot', 'colcat_onehot' ]
,'filter_pars': { 'ymax' : 100000.0 ,'ymin' : 0.0 } ### Filter data
}}
return model_dict