Repository navigation
Expand file tree
/
Copy pathclasses.py
More file actions
617 lines (528 loc) · 22.9 KB
/
Copy pathclasses.py
File metadata and controls
617 lines (528 loc) · 22.9 KB
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
import numbers
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils import check_array, check_random_state
from sklearn.utils.validation import check_is_fitted
##########################
### Encoders ###
##########################
class Encoder(TransformerMixin, BaseEstimator):
'''Shared plumbing: frame coercion, input validation, fitted-state check.
Statistics are learned in `fit` and stored in trailing-underscore attributes,
so `check_is_fitted`, `clone`, `get_feature_names_out` and `set_output` all behave.
'''
def check_fit(self):
check_is_fitted(self)
@staticmethod
def pd(X):
if isinstance(X, pd.DataFrame):
return X
# arrays: let sklearn enforce 2-D, finite-or-NaN, non-sparse, non-complex
kw = {"ensure_all_finite": "allow-nan"} if _NEW_VALIDATE else {"force_all_finite": "allow-nan"}
arr = check_array(X, dtype=None, ensure_min_samples=1, **kw)
if arr.dtype == object:
for v in arr.ravel():
if not isinstance(v, (str, bytes, numbers.Number, type(None))) and v is not pd.NA:
raise TypeError("argument must be a string or a number")
return pd.DataFrame(arr)
def _remember_input(self, X):
self.n_features_in_ = X.shape[1]
if all(isinstance(c, str) for c in X.columns):
self.feature_names_in_ = np.asarray(X.columns, dtype=object)
elif hasattr(self, "feature_names_in_"):
del self.feature_names_in_
def _check_input(self, X):
X = self.pd(X)
if X.shape[1] != self.n_features_in_:
raise ValueError(f"X has {X.shape[1]} features, but {type(self).__name__} "
f"is expecting {self.n_features_in_} features as input")
if hasattr(self, "feature_names_in_") and list(X.columns) != list(self.feature_names_in_):
if all(isinstance(c, str) for c in X.columns):
raise ValueError("The feature names should match those that were passed during fit.")
X = X.set_axis(self.feature_names_in_, axis=1)
elif not hasattr(self, "feature_names_in_"):
X = X.set_axis(range(X.shape[1]), axis=1)
return X
# tags: NaN is the input we exist for
def _more_tags(self):
return {"allow_nan": True, "preserves_dtype": []}
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.input_tags.allow_nan = True
tags.transformer_tags.preserves_dtype = []
return tags
try: # sklearn >= 1.6 renamed force_all_finite
import inspect as _inspect
_NEW_VALIDATE = "ensure_all_finite" in _inspect.signature(check_array).parameters
except Exception: # pragma: no cover
_NEW_VALIDATE = False
def _is_numeric(s: pd.Series) -> bool:
return pd.api.types.is_numeric_dtype(s) and not pd.api.types.is_bool_dtype(s)
class FeatureTrans:
''' Collection of data-transformation features '''
def __init__(self,data:pd.Series,n:int=5,n_step:int=5,n_max:int=50,empty:bool=False):
'''Initiating object with data series'''
if empty:
return
if str(data.dtype) == 'category':
self.data = pd.Series(data.cat.codes, name=data.name, index = data.index )
else:
self.data = data
dataunique = self.data.nunique()
if dataunique < n_max:
n_max = dataunique + 1
n_step = 1
n = 2
datatype = str(self.data.dtype)
dataint = datatype in ['int', 'int32', 'int64']
datafloat = datatype in ['float', 'float64']
datanum = dataint or datafloat
math_func = ["cbrt", "sqrt", "log1p", "log2", "ln", "log10"] + [f"pow{i}" for i in range(2,n)] # TODO: separate variable n
dict_math = {f"{func}":lambda X, func=func: __class__.math(X,func) for func in math_func}
dict_math = {"dull":__class__.dull, **dict_math}
dict_top = {f"top{i}":lambda X, i=i: __class__.top(X,i) for i in range(n,n_max,n_step)}
dict_ncut = {f"cut{i}":lambda X, i=i: __class__.cut(X,i) for i in range(n,n_max,n_step)}
dict_qcut = {f"qcut{i}":lambda X, i=i: __class__.qcut(X,i) for i in range(n,n_max,n_step)}
dict_cut = {**dict_ncut, **dict_qcut}
dict_cat = {
"count":__class__.count,
"freq":__class__.freq,
}
# Saving methods
self.method = {
**dict_cat,
**dict_top,
}
if datanum:
self.method = {
**self.method,
**dict_cut,
**dict_math
}
if dataunique == 2:
self.method = {
"bilabel":__class__.bilabel,
**self.method,
}
self.methods = list(self.method.keys())
def __iter__(self):
self.current_index = 0
return self
def __next__(self):
i = self.current_index
if i < len(self.methods):
method_name = self.methods[i]
method = self.method[method_name]
x = method(self.data)
self.current_index += 1
return x
raise StopIteration
@staticmethod
def dull(data):
return data
@staticmethod
def bilabel(data:pd.Series):
replaces = {'Yes':1, 'No':0}
unique = data.unique()
nonstandart = pd.Series([value not in replaces.keys() for value in unique]).sum()
if nonstandart > 0 and len(unique) == 2:
l1, l2 = unique
replaces = {l1:0,l2:1}
return pd.Series(data.map({v:replaces.get(v,v) for v in unique}),
name=data.name + "_bilabel")
@staticmethod
def fuzzy_mean(data:pd.Series,astype=float,random_state=None,stats:dict=None) -> pd.Series:
'''Fill NaN with draws from N(mean, std) clipped to [min, max].
`stats` = {"mean","std","min","max"} learned elsewhere (fit time); default - from `data`.'''
data = data.copy()
if stats is None:
stats = data.agg(['mean','std','min','max']).to_dict()
rng = check_random_state(random_state)
d_nan = data.isna()
if d_nan.any():
std = 0.0 if pd.isna(stats["std"]) else stats["std"]
draws = rng.normal(stats["mean"], std, d_nan.sum()).clip(stats["min"], stats["max"])
data[d_nan] = draws.astype(astype)
return data
@staticmethod
def robust(data:pd.Series,method:str) -> pd.Series:
'''Filling nan values with mean/median'''
data = data.copy()
value = data.agg(method)
if isinstance(value, pd.Series): # 'mode' gives a Series, 'mean'/'median' a scalar
value = value.iloc[0]
return data.fillna(value)
@staticmethod
def fill(data:pd.Series,filler:str) -> pd.Series:
'''Filling nan values with some str'''
data = data.copy()
data[data.isna()] = filler
return data
@staticmethod
def count(data):
''' Freq count '''
return pd.Series(data.map(data.value_counts().to_dict()),name=data.name+"_count")
@staticmethod
def freq(data):
''' Freq share'''
vcounts = data.value_counts()
maxvc = vcounts.max()
nunique = data.nunique()
n = len(data)
if maxvc < nunique:
t = "u"
result = data.map((vcounts / nunique).to_dict())
elif maxvc / n > 0.2:
t = "n"
result = data.map((vcounts / n).to_dict())
else:
t = "o"
result = data.map((vcounts / maxvc).to_dict())
return pd.Series(result,name=data.name+f"_freq{t}")
@staticmethod
def top(data,n):
''' Top rating - most frequent becomes 1, less becomes 2, 3 .. n'''
return pd.Series(data.map({
v:i+1 if i < n else n
for i,v in enumerate(data.value_counts().index)}),
name=data.name+f"_top{n}")
@staticmethod
def math(data:pd.Series,name:str):
# check = domain; eps keeps the signed fallback finite at 0
math_func = {
"cbrt": {"func":np.cbrt, "check": lambda X: True, "eps": 0.0},
"sqrt": {"func":np.sqrt, "check": lambda X: (X >= 0).all(), "eps": 0.0},
"log1p":{"func":np.log1p, "check": lambda X: (X > -1).all(), "eps": 0.0},
"log2": {"func":np.log2, "check": lambda X: (X > 0).all(), "eps": 1e-24},
"ln": {"func":np.log, "check": lambda X: (X > 0).all(), "eps": 1e-24},
"log10":{"func":np.log10, "check": lambda X: (X > 0).all(), "eps": 1e-24}
}
if name.startswith("pow"):
pow = int(name[3:])
return pd.Series( np.power(data,pow), name=data.name + f"_{name}", index = data.index )
else:
terms = math_func[name]
check, func = terms["check"], terms["func"]
values = data.astype(float)
if check(values.dropna()):
out = func(values)
else:
# out of domain: odd (signed) extension, sign(x) * f(|x|) - monotone and finite
out = np.sign(values) * func(np.abs(values) + terms["eps"])
return pd.Series( out, name=data.name + f"_{name}", index = data.index )
@staticmethod
def qcut(data,n):
return pd.Series( pd.qcut(data,n,labels=False,duplicates="drop"),name=data.name+f"_qcut{n}")
@staticmethod
def cut(data,n):
return pd.Series( pd.cut(data,n,labels=False,duplicates="drop"),name=data.name+f"_cut{n}")
class NanFixer(Encoder):
'''
Fill the gaps, one strategy per column, chosen and *measured* at `fit` time:
| column | condition | fill |
| numeric | NA share <= `lim` | `method` ("mean"/"median") of the fit data |
| numeric | NA share > `lim` | draws from N(mean, std) of the fit data, clipped |
| object | one value > 25 % (fit) | that mode |
| object | otherwise | the `filler` string |
Other dtypes pass through. Parameters are grid-searchable.
'''
def __init__(self,lim:float=0.225,method:str="mean",filler:str="U",random_state=None):
self.lim = lim
self.method = method
self.filler = filler
self.random_state = random_state
def fit(self, X, y=None):
X = self.pd(X)
self._remember_input(X)
plan = {}
for col in X.columns:
data = X[col]
if _is_numeric(data):
datanan = data.isna().mean()
if datanan > self.lim:
stats = data.agg(['mean','std','min','max']).to_dict()
plan[col] = ("fuzzy", {"stats": stats,
"astype": float if pd.api.types.is_float_dtype(data) else int})
else:
value = data.agg(self.method)
plan[col] = ("value", value)
elif data.dtype == object or isinstance(data.dtype, pd.CategoricalDtype) \
or pd.api.types.is_string_dtype(data):
counts = data.value_counts(dropna=True)
if len(counts) and counts.iloc[0] / len(data) > 0.25:
plan[col] = ("value", counts.index[0])
else:
plan[col] = ("value", self.filler)
# anything else: no entry -> pass through
self.plan_ = plan
return self
def transform(self, X):
self.check_fit()
was_frame = isinstance(X, pd.DataFrame)
X = self._check_input(X)
result = X.copy()
rng = check_random_state(self.random_state)
for col, (kind, param) in self.plan_.items():
data = X[col]
if kind == "fuzzy":
result[col] = FeatureTrans.fuzzy_mean(data, astype=param["astype"],
random_state=rng, stats=param["stats"])
else:
if isinstance(data.dtype, pd.CategoricalDtype) and param not in data.cat.categories:
data = data.astype(object)
result[col] = data.fillna(param)
return result if was_frame else result.to_numpy() # you get what you gave
def get_feature_names_out(self, input_features=None):
self.check_fit()
if hasattr(self, "feature_names_in_"):
return np.asarray(self.feature_names_in_, dtype=object)
return np.asarray([f"x{i}" for i in range(self.n_features_in_)], dtype=object)
class Digitalize(Encoder):
'''
Mixed frame -> numeric frame. The plan *and its statistics* come from `fit`:
| column | condition | result |
| numeric | < 3 unique | as is |
| any | < `alim` unique | one-hot over the categories seen at fit (unseen -> all zeros) |
| numeric | mode "cut" / "qcut" | `ncut` bins with edges from the fit data |
| numeric | mode "raw" | as is |
| non-numeric | >= `alim` unique | frequency rank from the fit data: top -> 1, tail and unseen -> `ncut` |
`final` is kept for backwards compatibility and does nothing.
'''
def __init__(self,final:bool=True,alim:int=10,mode:str="raw",ncut:int=5):
self.alim = alim
self.ncut = ncut
self.mode = mode
self.final = final
def fit(self, X, y=None):
X = self.pd(X)
self._remember_input(X)
plan = []
for col in X.columns:
data = X[col]
numeric = _is_numeric(data)
nunique = data.nunique()
if nunique < self.alim:
if nunique < 3 and numeric:
plan.append((col, "raw", None))
else:
cats = pd.Series(data.dropna().unique())
try:
cats = cats.sort_values()
except TypeError:
pass
plan.append((col, "onehot", list(cats)))
elif numeric:
if self.mode == "cut":
lo, hi = data.min(), data.max()
edges = np.linspace(lo, hi, self.ncut + 1)
plan.append((col, "bins", edges))
elif self.mode == "qcut":
edges = np.unique(data.quantile(np.linspace(0, 1, self.ncut + 1)).to_numpy())
plan.append((col, "bins", edges))
else:
plan.append((col, "raw", None))
else:
ranks = {v: min(i + 1, self.ncut) for i, v in enumerate(data.value_counts().index)}
plan.append((col, "rank", ranks))
self.plan_ = plan
self.feature_names_out_ = np.asarray(
[name for col, kind, param in plan for name in self._names(col, kind, param)], dtype=object)
return self
def _names(self, col, kind, param):
if kind == "onehot":
return [f"{col}_{v}" for v in param]
if kind == "bins":
return [f"{col}_{self.mode}{self.ncut}"]
if kind == "rank":
return [f"{col}_top{self.ncut}"]
return [str(col)]
def transform(self, X):
self.check_fit()
was_frame = isinstance(X, pd.DataFrame)
X = self._check_input(X)
parts = []
for col, kind, param in self.plan_:
data = X[col]
names = self._names(col, kind, param)
if kind == "raw":
parts.append(data.rename(names[0]))
elif kind == "onehot":
for v, name in zip(param, names):
parts.append((data == v).astype("uint8").rename(name))
elif kind == "bins":
edges = param
values = data.astype(float).clip(edges[0], edges[-1])
binned = pd.cut(values, edges, labels=False, include_lowest=True, duplicates="drop")
parts.append(binned.rename(names[0]))
else: # rank
parts.append(data.map(param).fillna(self.ncut).astype(int).rename(names[0]))
out = pd.concat(parts, axis=1) if parts else pd.DataFrame(index=X.index)
return out if was_frame else out.to_numpy() # you get what you gave
def get_feature_names_out(self, input_features=None):
self.check_fit()
return self.feature_names_out_
##########################
### Estimators ###
##########################
class SlowPolyLinearReg(FeatureTrans):
'''
This is just hand-made regression class
to see how it can be done from scratch (using numpy and pandas)
'''
# nonlinear functions to generate additional synthetic features
genmap = {
"cbrt": {"func":np.cbrt},
"sqrt": {"func":np.sqrt, "check": lambda X: (X >= 0).all()},
"log2": {"func":np.log2, "check": lambda X: (X > 0).all()},
"ln": {"func":np.log, "check": lambda X: (X > 0).all()},
"log10":{"func":np.log10, "check": lambda X: (X > 0).all()}
}
@staticmethod
def gener():
return list(SlowPolyLinearReg.genmap.keys())
@staticmethod
def norm():
return list(SlowPolyLinearReg.normap.keys())
# functions for saving or retrieving parameters and applying normalization
def save_load(self, value, name):
try:
stored = getattr(self,name)
except AttributeError:
stored = None
if type(stored) != type(None):
return stored
else:
setattr(self,name,value)
return value
# min-max rescaling
def minmax(self,X):
X_min = SlowPolyLinearReg.save_load(self,X.min(),"norm_min")
X_max = SlowPolyLinearReg.save_load(self,X.max(),"norm_max")
return (X-X_min)/(X_max-X_min)
# max normalization
def n_max(self,X):
X_max = SlowPolyLinearReg.save_load(self,X.max(),"norm_max")
return X/X_max
# Z-score normalization
def n_std(self,X):
X_mean = SlowPolyLinearReg.save_load(self,X.mean(),"norm_mean")
X_std = SlowPolyLinearReg.save_load(self,X.std(),"norm_std")
return (X-X_mean)/X_std
# mean normalization
def n_mean(self,X):
X_mean = SlowPolyLinearReg.save_load(self,X.mean(),"norm_mean")
X_min = SlowPolyLinearReg.save_load(self,X.min(),"norm_min")
X_max = SlowPolyLinearReg.save_load(self,X.max(),"norm_max")
return (X-X_mean)/(X_max-X_min)
# access to normalization functions from one dictionary
normap = {
None: lambda _, X: X,
"minmax": minmax,
"std": n_std,
"max": n_max,
"mean": n_mean
}
# object creation
def __init__(self,gener:list=[0,1],norm:str=None,alpha:float=None):
'''
Planning check and data generation for columns (synthetic features addon),
than data normalization
'''
self.checks = {}
self.generators = {}
self.normalize = __class__.normap.get(norm,lambda _, X: print(f"Can't find {norm} normalization") or X)
if alpha:
self.regular = True
self.alpha = alpha
print(f"Will apply L2 regularization with coef {alpha:.3f}")
else:
self.regular = False
for key in gener:
if isinstance(key,str):
param = __class__.genmap.get(key,{})
if "func" in param:
self.generators[key] = param["func"]
else:
raise ValueError(f"Can't find {key} function")
if "check" in param:
self.checks[key] = param["check"]
elif isinstance(key,int):
self.generators[key] = lambda X, key=key: np.power(X,key)
def __gen_cols(self,X):
'''
Generating column(s)
'''
def namecol(data,name):
data.columns = pd.MultiIndex.from_product([data.columns,[name]],names=['feature', 'function'])
ndim = X.ndim
rows, cols = X.shape
result = pd.DataFrame()
if X.size == 0:
return result
if ndim > 2:
raise ValueError("Two-dimensional array max!")
for key, generator in self.generators.items():
# const hack
if key == 0:
addon = pd.DataFrame(np.ones((rows,1)),index=X.index)
namecol(addon,0)
result = pd.concat([addon,result],axis=1)
else:
addon = X.apply(generator)
namecol(addon,key)
result = pd.concat([result,addon],axis=1)
return result
def complete(self, X):
'''
Apply checks, column generation and normalization
'''
X = pd.DataFrame(X)
if X.isna().any().any():
raise ValueError("NA values have no weight to learn - fill them first")
for key, check in self.checks.items():
if not X.apply(check).all():
raise ValueError(f"Try different column generators, other than {key}")
X_wide = self.__gen_cols(X)
if X_wide.empty:
return X_wide
# the constant column is the intercept, not a feature - it stays out of normalization
variable = X_wide.columns.get_level_values("function") != 0
X_wide = pd.concat([X_wide.loc[:,~variable],
self.normalize(self,X_wide.loc[:,variable])],axis=1)
return X_wide
def fit(self, X, y):
'''
Finding the most suitable weights for feature(s)
'''
for stat in ("norm_min","norm_max","norm_mean","norm_std"):
setattr(self,stat,None) # a refit is a fresh fit, not a continuation
X_wide = self.complete(X)
XTX = X_wide.T @ X_wide
XTY = X_wide.T @ y
if self.regular:
XTX = XTX + self.alpha * np.eye(XTX.shape[0])
if np.linalg.det(XTX) == 0:
print("Columns or rows are dependent!")
# TODO: try removing some of the data to get rid of this effect
elif np.linalg.cond(XTX) > 1e4:
print("Ill-conditioned matrix!")
try:
# closed-form solution
self.w = np.linalg.solve(XTX,XTY)
except np.linalg.LinAlgError:
print("Singular matrix - falling back to the least-norm solution")
self.w = np.linalg.lstsq(XTX,XTY,rcond=None)[0]
return self
def predict(self, X):
'''
Applying previously fitted weights to new data
'''
X_wide = self.complete(X)
return X_wide.dot(self.w)
def score(self, X, y):
'''
R2-score of prediction
'''
y_pred = self.predict(X)
return 1 - ((y - y_pred)**2).sum() / ((y - np.mean(y))**2).sum()