-
Notifications
You must be signed in to change notification settings - Fork 0
/
boab.py
407 lines (326 loc) · 12.4 KB
/
boab.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# -*- coding: utf-8 -*-
"""
load_data
check file extension if csv or xlsx or dat
fix column names (remove capitals, spaces, dots, symbols)
Fix data types to_numeric to_datetime
for each column check number of missing
if more than 20% missing then remove
if missing records < 20% try impute
impute - KNN, random for labels or mean impute
Binning of contiuous vars
For categoricals make dummy variables
Always drop dummy [-1] for each group of variables
scale and normalise numeric variables
Balance data using smote
train test split
lassoCV, RidgeCV, Neural Net
Perf report
Save models
"""
import os
import pandas as pd
import re
import numpy as np
import datetimeseek
class Boab(object):
"""
Class Desc
"""
def __init__(self, *args, **kwargs):
self.df = pd.DataFrame([])
self.time_cols = []
self.date_cols = []
self.models = []
self.X_train = None
self.X_test = None
self.y_train = None
self.y_test = None
return super().__init__(*args, **kwargs)
def __str__(self):
return str(self.df.head())
def __repr__(self):
return str(self.df.head())
def head(self):
print(self.df.head())
@property
def columns(self):
return self.df.columns
def fix_col_names(self):
"""
fix column names (remove capitals, spaces, dots, symbols)
"""
col_names = []
for n in self.df.columns:
coln = n.lower()
coln = re.sub("([-_.\(\) ])", '_', coln)
coln = re.sub("([+: ])", '', coln)
col_names.append(coln)
self.df.columns = col_names
def load_data(self, filename, sep=','):
"""
load_data
check file extension if csv or xlsx or dat
"""
ext = os.path.splitext(filename)[-1].replace('.','')
if ext in ['csv', 'tsv', 'dat', 'data', 'txt', '']:
# Check csv file to find separator
import csv
with open(filename, newline='') as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(1024))
separator = dialect.delimiter
print("\n[INFO] File separator: '{}'".format(separator))
self.df = pd.read_csv(filename, sep=separator)
# return self.df
elif ext == 'xlsx' or ext == 'xls':
self.df = pd.read_excel(filename)
# return self.df
self.fix_col_names()
def __which_time_col(self, cols):
# Look for date columns
time_cols = []
for i, c in enumerate(cols):
match_obj = re.match("time", c, flags=re.IGNORECASE)
if match_obj:
time_cols.append(match_obj.group())
return time_cols
def __which_date_col(self,cols):
# Look for date columns
date_cols = []
for col in cols:
if datetimeseek.isdatecol(self.df.col):
date_cols.append(col)
return date_cols
def fix_types(self, french_decs=None):
"""
Fix data types to_numeric, to_datetime
Look at top 100 rows of each col and decide on a
data type, if number rows < 100 then use all rows
"""
def fix_time_cols(self):
# Fix TIme Columns
try:
# fix time cols
for c in self.time_cols:
self.df[c] = pd.to_datetime(self.df[c], format='%H:%M:%S')
except:
pass
# Fix TIme Columns
try:
# fix time cols
for c in self.time_cols:
self.df[c] = pd.to_datetime(self.df[c], format='%H.%M.%S')
except:
pass
def fix_date_cols(self):
# fix date cols
# for cols in date_cols do pd.to_datetime()
for c in self.date_cols:
try:
self.df[c] = pd.to_datetime(self.df[c])
except:
self.df[c] = pd.to_datetime(self.df[c], format='%d/%m/%y %H.%M.%S')
############################
# FIX FRENCH DECIMALS
############################
if french_decs:
self.french_dec_english(french_decs)
############################
# FIX DATE AND TIME COLUMNS
############################
# Look for date columns
self.date_cols = self.__which_date_col(self.df.columns)
# fix date cols
# for cols in date_cols do pd.to_datetime()
# for c in self.date_cols:
# self.df[c] = pd.to_datetime(self.df[c])
# fix date cols
fix_date_cols(self)
# Look for time columns
self.time_cols = self.__which_time_col(self.df.columns)
# Remove Date Cols from Time Cols
self.time_cols = list(set(self.time_cols) - set(self.date_cols))
# Fix time columns
fix_time_cols(self)
# Infer Objects
self.df.infer_objects()
# Do any columns contan 'nan'?
# if so then fix
for c in self.df.columns:
# For string columns
if self.df[c].dtype == object:
print('Column:', c)
mask = self.df[c] == 'nan'
print('Number nans:', mask.shape[0])
if mask.shape[0] > 0:
# Replace the nans
self.df.loc[mask, c] = np.NaN
try:
# Convert to numeric
self.df[c] = pd.to_numeric(self.df[c])
except:
pass
return self
def fix_missing(self):
"""
For each col count the number of missing
divided by the number of rows.
Check if over 20% missing
"""
n_rows = self.df.shape[0]
perc_missing = []
for c in self.df.columns:
n_missing = self.df[c].isna().sum()
perc_missing.append(n_missing/n_rows)
drop_cols = []
for i, p in enumerate(perc_missing):
if p > 0.2:
drop_cols.append(self.df.columns[i])
# Drop the columns
self.df.drop(drop_cols, axis=1, inplace=True)
# If there are <20% missing then impute the column
for c in self.df.columns:
# Numeric Columns
if(self.df[c].dtype == np.float64 or self.df[c].dtype == np.int64):
print('Column:', c, 'Numeric')
# for each numeric col do mean imputation
self.df.loc[self.df[c].isnull(), c] = self.df[c].mean()
return self
def french_dec_english(self, colnames):
"""
Convert 2,6 to 2.6
"""
for c in colnames:
self.df[c] = self.df[c].apply(lambda x: str(x).replace(',','.'))
return self
def is_time_componet(self, colname):
# There is no time component
if self.df[colname].dt.hour.sum() == 0 and self.df[colname].dt.minute.sum() == 0 and self.df[colname].dt.second.sum() == 0 and self.df[colname].dt.microsecond.sum() == 0:
return False
# There IS a time component
else:
return True
def make_discrete_datetime_cols(self, verbose=False):
# Look for date columns
self.date_cols = self.__which_date_col(self.df.columns)
# Look for time columns
self.time_cols = self.__which_time_col(self.df.columns)
if verbose:
print('Date columns:', self.date_cols, 'Time columns', self.time_cols )
for d in self.date_cols:
# append col name as prefix
self.df['_'.join([d, 'day'])] = self.df[d].dt.day
self.df['_'.join([d, 'month'])] = self.df[d].dt.month
self.df['_'.join([d, 'year'])] = self.df[d].dt.year
# If there is a time component then extract hour
if self.is_time_componet(d):
self.df['_'.join([d, 'hour'])] = self.df[d].dt.hour
def build_regression(self, feature_list, target, model_list=['ridge']):
"""
Takes features and target
Does train test split
Reports on preformance
Returns: model
"""
# Fix missing values
print('\n[INFO] Imputing missing values')
self.fix_missing()
print('\nMissing Values:')
print(self.df.isna().sum())
seed = 4784
from sklearn.model_selection import train_test_split
X = self.df[feature_list]
y = self.df[target]
self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X, y, random_state=seed)
for m in model_list:
if m == 'ridge':
from sklearn.linear_model import RidgeCV
# Choosing a CV number
if self.df.shape[0] > 100:
cv = 3
elif self.df.shape[0] > 500:
cv = 5
else:
cv = 1
model = RidgeCV(alphas=(0.1, 1.0, 10.0), cv=cv)
model.fit(self.X_train, self.y_train)
print('\nRidge Regression R-squared:', model.score(self.X_test, self.y_test))
# Add the model to the output list
self.models.append(model)
def build_ts_regression(self, feature_list, target, dt_index, model_list=['ridge']):
"""
Takes features and target
Does train test split
Reports on preformance
Returns: model
"""
# Fix missing values
print('\n[INFO] Imputing missing values')
self.fix_missing()
print('\nMissing Values:')
print(bo.df.isna().sum())
test_size = 0.3
self.df.sort_values(dt_index, ascending=True, inplace=True)
nrows = self.df.shape[0]
train_idx = int(nrows*(1-test_size))
test_idx = nrows - train_idx
X = self.df[feature_list]
y = self.df[target]
self.X_train = X.iloc[0:train_idx]
self.X_test = X.iloc[0:test_idx]
self.y_train = y.iloc[0:train_idx]
self.y_test = y.iloc[0:test_idx]
print('Xtrain size:', self.X_train.shape[0], 'Xtest size:', self.X_test.shape[0])
for m in model_list:
if m == 'ridge':
from sklearn.linear_model import RidgeCV
# Choosing a CV number
if self.df.shape[0] > 100:
cv = 3
elif self.df.shape[0] > 500:
cv = 5
else:
cv = 1
model = RidgeCV(alphas=(0.1, 1.0, 10.0), cv=cv)
model.fit(self.X_train, self.y_train)
print('\nRidge Regression R-squared:', model.score(self.X_test, self.y_test)
# Add the model to the output list
self.models.append(model)
############################################################
### End Class
############################################################
############################################################
### Example API
############################################################
# bo = Boab()
# bo.load_data('boab-data-science/boab/AirQualityUCI.csv', sep=';')
# bo.fix_types(french_decs=['co_gt_', 'c6h6_gt_', 't', 'rh', 'ah'])
# bo.fix_missing()
# # bo.french_dec_english(['co_gt_', 'c6h6_gt_', 't', 'rh', 'ah'])
# bo.make_discrete_datetime_cols()
# bo.df.head()
# # Build normal regression
# feature_list = ['pt08_s1_co_', 'nmhc_gt_', 'c6h6_gt_',
# 'pt08_s2_nmhc_', 'nox_gt_', 'pt08_s3_nox_', 'no2_gt_', 'pt08_s4_no2_',
# 'pt08_s5_o3_', 't', 'rh', 'ah', 'date_day', 'date_month', 'date_year']
# target = 'co_gt_'
# bo.build_regression(feature_list=feature_list, target=target)
# # Build Timeseries regression
# feature_list = ['pt08_s1_co_', 'nmhc_gt_', 'c6h6_gt_',
# 'pt08_s2_nmhc_', 'nox_gt_', 'pt08_s3_nox_', 'no2_gt_', 'pt08_s4_no2_',
# 'pt08_s5_o3_', 't', 'rh', 'ah', 'date_day', 'date_month', 'date_year']
# target = 'co_gt_'
# bo.build_ts_regression(feature_list=feature_list, target=target, dt_index='date')
############################################################
## CAR DATA
############################################################
bo = Boab()
bo.load_data('car_data.csv')
bo.fix_types()
bo.fix_missing()
bo.make_discrete_datetime_cols()
print(bo.df.head())
# Build normal regression
feature_list = ['cyclinders', 'displacement', 'hp', 'weight', 'acceleration', 'year', 'origin']
target = 'mpg'
bo.build_regression(feature_list=feature_list, target=target)