bitskitten 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bitskitten/__init__.py +29 -0
- bitskitten/classes.py +573 -0
- bitskitten/input.py +24 -0
- bitskitten/output.py +220 -0
- bitskitten-0.2.0.dist-info/METADATA +193 -0
- bitskitten-0.2.0.dist-info/RECORD +9 -0
- bitskitten-0.2.0.dist-info/WHEEL +5 -0
- bitskitten-0.2.0.dist-info/licenses/LICENSE +201 -0
- bitskitten-0.2.0.dist-info/top_level.txt +1 -0
bitskitten/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
'''bitskitten - small helpers for EDA, plotting and feature encoding.
|
|
2
|
+
|
|
3
|
+
from bitskitten import imperfection, NanFixer, Digitalize
|
|
4
|
+
|
|
5
|
+
Submodules stay importable on their own (`from bitskitten import output`),
|
|
6
|
+
which is also how the zipped drop-in build is used: `from classes import NanFixer`.
|
|
7
|
+
'''
|
|
8
|
+
|
|
9
|
+
__version__ = "0.2.0"
|
|
10
|
+
|
|
11
|
+
from .classes import Digitalize, Encoder, FeatureTrans, NanFixer, SlowPolyLinearReg
|
|
12
|
+
from .input import number
|
|
13
|
+
from .output import (
|
|
14
|
+
imperfection,
|
|
15
|
+
img_framaker,
|
|
16
|
+
img_squeeze,
|
|
17
|
+
informer,
|
|
18
|
+
informer_print,
|
|
19
|
+
multicolumn,
|
|
20
|
+
plot_conf_map,
|
|
21
|
+
plot_some_scatters,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"Digitalize", "Encoder", "FeatureTrans", "NanFixer", "SlowPolyLinearReg",
|
|
26
|
+
"number",
|
|
27
|
+
"imperfection", "informer", "informer_print", "multicolumn",
|
|
28
|
+
"plot_conf_map", "plot_some_scatters", "img_squeeze", "img_framaker",
|
|
29
|
+
]
|
bitskitten/classes.py
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from sklearn.base import BaseEstimator, TransformerMixin
|
|
4
|
+
from sklearn.exceptions import NotFittedError
|
|
5
|
+
|
|
6
|
+
##########################
|
|
7
|
+
### Encoders ###
|
|
8
|
+
##########################
|
|
9
|
+
|
|
10
|
+
class Encoder(BaseEstimator, TransformerMixin):
|
|
11
|
+
def check_fit(self):
|
|
12
|
+
if not self.fitted:
|
|
13
|
+
raise NotFittedError(f"This {type(self).__name__} instance is not fitted yet.\
|
|
14
|
+
Call 'fit' with appropriate arguments before using this estimator.")
|
|
15
|
+
@staticmethod
|
|
16
|
+
def pd(X):
|
|
17
|
+
if not isinstance(X,pd.DataFrame):
|
|
18
|
+
return pd.DataFrame(X)
|
|
19
|
+
else:
|
|
20
|
+
return X
|
|
21
|
+
|
|
22
|
+
class FeatureTrans:
|
|
23
|
+
''' Collection of data-transformation features '''
|
|
24
|
+
|
|
25
|
+
def __init__(self,data:pd.Series,n:int=5,n_step:int=5,n_max:int=50,empty:bool=False):
|
|
26
|
+
'''Initiating object with data series'''
|
|
27
|
+
if empty:
|
|
28
|
+
return
|
|
29
|
+
|
|
30
|
+
if str(data.dtype) == 'category':
|
|
31
|
+
self.data = pd.Series(data.cat.codes, name=data.name, index = data.index )
|
|
32
|
+
else:
|
|
33
|
+
self.data = data
|
|
34
|
+
|
|
35
|
+
dataunique = self.data.nunique()
|
|
36
|
+
|
|
37
|
+
if dataunique < n_max:
|
|
38
|
+
n_max = dataunique + 1
|
|
39
|
+
n_step = 1
|
|
40
|
+
n = 2
|
|
41
|
+
|
|
42
|
+
datatype = str(self.data.dtype)
|
|
43
|
+
|
|
44
|
+
dataint = datatype in ['int', 'int32', 'int64']
|
|
45
|
+
datafloat = datatype in ['float', 'float64']
|
|
46
|
+
datanum = dataint or datafloat
|
|
47
|
+
|
|
48
|
+
math_func = ["cbrt", "sqrt", "log1p", "log2", "ln", "log10"] + [f"pow{i}" for i in range(2,n)] # TODO: separate variable n
|
|
49
|
+
dict_math = {f"{func}":lambda X, func=func: __class__.math(X,func) for func in math_func}
|
|
50
|
+
dict_math = {"dull":__class__.dull, **dict_math}
|
|
51
|
+
|
|
52
|
+
dict_top = {f"top{i}":lambda X, i=i: __class__.top(X,i) for i in range(n,n_max,n_step)}
|
|
53
|
+
|
|
54
|
+
dict_ncut = {f"cut{i}":lambda X, i=i: __class__.cut(X,i) for i in range(n,n_max,n_step)}
|
|
55
|
+
dict_qcut = {f"qcut{i}":lambda X, i=i: __class__.qcut(X,i) for i in range(n,n_max,n_step)}
|
|
56
|
+
dict_cut = {**dict_ncut, **dict_qcut}
|
|
57
|
+
|
|
58
|
+
dict_cat = {
|
|
59
|
+
"count":__class__.count,
|
|
60
|
+
"freq":__class__.freq,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
# Saving methods
|
|
64
|
+
self.method = {
|
|
65
|
+
**dict_cat,
|
|
66
|
+
**dict_top,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if datanum:
|
|
70
|
+
self.method = {
|
|
71
|
+
**self.method,
|
|
72
|
+
**dict_cut,
|
|
73
|
+
**dict_math
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if dataunique == 2:
|
|
77
|
+
self.method = {
|
|
78
|
+
"bilabel":__class__.bilabel,
|
|
79
|
+
**self.method,
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
self.methods = list(self.method.keys())
|
|
83
|
+
|
|
84
|
+
def __iter__(self):
|
|
85
|
+
self.current_index = 0
|
|
86
|
+
return self
|
|
87
|
+
|
|
88
|
+
def __next__(self):
|
|
89
|
+
i = self.current_index
|
|
90
|
+
|
|
91
|
+
if i < len(self.methods):
|
|
92
|
+
method_name = self.methods[i]
|
|
93
|
+
method = self.method[method_name]
|
|
94
|
+
x = method(self.data)
|
|
95
|
+
self.current_index += 1
|
|
96
|
+
return x
|
|
97
|
+
raise StopIteration
|
|
98
|
+
|
|
99
|
+
@staticmethod
|
|
100
|
+
def dull(data):
|
|
101
|
+
return data
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def bilabel(data:pd.Series):
|
|
105
|
+
replaces = {'Yes':1, 'No':0}
|
|
106
|
+
unique = data.unique()
|
|
107
|
+
nonstandart = pd.Series([value not in replaces.keys() for value in unique]).sum()
|
|
108
|
+
if nonstandart > 0 and len(unique) == 2:
|
|
109
|
+
l1, l2 = unique
|
|
110
|
+
replaces = {l1:0,l2:1}
|
|
111
|
+
return pd.Series(data.map({v:replaces.get(v,v) for v in unique}),
|
|
112
|
+
name=data.name + "_bilabel")
|
|
113
|
+
|
|
114
|
+
@staticmethod
|
|
115
|
+
def fuzzy_mean(data:pd.Series,astype=float) -> pd.Series:
|
|
116
|
+
'''Filling nan values with fuzzy mean values of corresponding columns
|
|
117
|
+
() '''
|
|
118
|
+
data = data.copy()
|
|
119
|
+
d_mean, d_std, d_min, d_max = data.agg(['mean','std','min','max'])
|
|
120
|
+
d_nan = data.isna()
|
|
121
|
+
data[d_nan] = np.random.normal(
|
|
122
|
+
d_mean,
|
|
123
|
+
d_std,
|
|
124
|
+
d_nan.sum()
|
|
125
|
+
).clip(d_min, d_max)\
|
|
126
|
+
.astype(astype)
|
|
127
|
+
return data
|
|
128
|
+
|
|
129
|
+
@staticmethod
|
|
130
|
+
def robust(data:pd.Series,method:str) -> pd.Series:
|
|
131
|
+
'''Filling nan values with mean/median'''
|
|
132
|
+
data = data.copy()
|
|
133
|
+
value = data.agg(method)
|
|
134
|
+
if isinstance(value, pd.Series): # 'mode' gives a Series, 'mean'/'median' a scalar
|
|
135
|
+
value = value.iloc[0]
|
|
136
|
+
return data.fillna(value)
|
|
137
|
+
|
|
138
|
+
@staticmethod
|
|
139
|
+
def fill(data:pd.Series,filler:str) -> pd.Series:
|
|
140
|
+
'''Filling nan values with some str'''
|
|
141
|
+
data = data.copy()
|
|
142
|
+
data[data.isna()] = filler
|
|
143
|
+
return data
|
|
144
|
+
|
|
145
|
+
@staticmethod
|
|
146
|
+
def count(data):
|
|
147
|
+
''' Freq count '''
|
|
148
|
+
return pd.Series(data.map(data.value_counts().to_dict()),name=data.name+"_count")
|
|
149
|
+
|
|
150
|
+
@staticmethod
|
|
151
|
+
def freq(data):
|
|
152
|
+
''' Freq share'''
|
|
153
|
+
vcounts = data.value_counts()
|
|
154
|
+
maxvc = vcounts.max()
|
|
155
|
+
nunique = data.nunique()
|
|
156
|
+
n = len(data)
|
|
157
|
+
if maxvc < nunique:
|
|
158
|
+
t = "u"
|
|
159
|
+
result = data.map((vcounts / nunique).to_dict())
|
|
160
|
+
elif maxvc / n > 0.2:
|
|
161
|
+
t = "n"
|
|
162
|
+
result = data.map((vcounts / n).to_dict())
|
|
163
|
+
else:
|
|
164
|
+
t = "o"
|
|
165
|
+
result = data.map((vcounts / maxvc).to_dict())
|
|
166
|
+
return pd.Series(result,name=data.name+f"_freq{t}")
|
|
167
|
+
|
|
168
|
+
@staticmethod
|
|
169
|
+
def top(data,n):
|
|
170
|
+
''' Top rating - most frequent becomes 1, less becomes 2, 3 .. n'''
|
|
171
|
+
return pd.Series(data.map({
|
|
172
|
+
v:i+1 if i < n else n
|
|
173
|
+
for i,v in enumerate(data.value_counts().index)}),
|
|
174
|
+
name=data.name+f"_top{n}")
|
|
175
|
+
|
|
176
|
+
@staticmethod
|
|
177
|
+
def math(data:pd.Series,name:str):
|
|
178
|
+
math_func = {
|
|
179
|
+
"cbrt": {"func":np.cbrt, "check": lambda X: True},
|
|
180
|
+
"sqrt": {"func":np.sqrt, "check": lambda X: (X >= 0).all()},
|
|
181
|
+
"log1p":{"func":np.log1p, "check": lambda X: (X > 0).all()},
|
|
182
|
+
"log2": {"func":np.log2, "check": lambda X: (X > 0).all()},
|
|
183
|
+
"ln": {"func":np.log, "check": lambda X: (X > 0).all()},
|
|
184
|
+
"log10":{"func":np.log10, "check": lambda X: (X > 0).all()}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if name.startswith("pow"):
|
|
188
|
+
pow = int(name[3:])
|
|
189
|
+
return pd.Series( np.power(data,pow), name=data.name + f"_{name}", index = data.index )
|
|
190
|
+
else:
|
|
191
|
+
terms = math_func[name]
|
|
192
|
+
check, func = terms["check"], terms["func"]
|
|
193
|
+
|
|
194
|
+
if check(data):
|
|
195
|
+
return pd.Series( func(data), name=data.name + f"_{name}", index = data.index )
|
|
196
|
+
else:
|
|
197
|
+
return pd.Series( func(data.apply(abs)+1e-24), name=data.name + f"_{name}", index = data.index ) # TODO: remove hack
|
|
198
|
+
|
|
199
|
+
@staticmethod
|
|
200
|
+
def qcut(data,n):
|
|
201
|
+
return pd.Series( pd.qcut(data,n,labels=False,duplicates="drop"),name=data.name+f"_qcut{n}")
|
|
202
|
+
|
|
203
|
+
@staticmethod
|
|
204
|
+
def cut(data,n):
|
|
205
|
+
return pd.Series( pd.cut(data,n,labels=False,duplicates="drop"),name=data.name+f"_cut{n}")
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class NanFixer(Encoder,FeatureTrans):
|
|
209
|
+
'''
|
|
210
|
+
There is different (yet primitive) strategies for filling NAN values
|
|
211
|
+
this class giving a possibility to grid search through them
|
|
212
|
+
'''
|
|
213
|
+
def __init__(self,lim:float=0.225,method:str="mean",filler:str="U"):
|
|
214
|
+
'''Initiating object: copying parameters to self'''
|
|
215
|
+
self.lim = lim
|
|
216
|
+
self.plan = {}
|
|
217
|
+
self.method = method
|
|
218
|
+
self.filler = filler
|
|
219
|
+
self.fitted = False
|
|
220
|
+
# logging.debug("Initialized %s object with parameters:\
|
|
221
|
+
# \tmax share of NA in column to apply robust methods: %s,\
|
|
222
|
+
# \taggregation mode for robust method: %s,\
|
|
223
|
+
# \tfiller for NA values in other cases: %s",
|
|
224
|
+
# __class__.__name__,lim,method,filler)
|
|
225
|
+
|
|
226
|
+
def fit(self, X:pd.DataFrame,y=None):
|
|
227
|
+
'''
|
|
228
|
+
Making a plan for filling NA values depending on parameters
|
|
229
|
+
and dtypes of data
|
|
230
|
+
'''
|
|
231
|
+
X = self.pd(X)
|
|
232
|
+
|
|
233
|
+
for col in X.columns:
|
|
234
|
+
data = X[col]
|
|
235
|
+
datanan = data.isna().sum()/len(data)
|
|
236
|
+
datatype = data.dtype
|
|
237
|
+
datanum = datatype in [np.dtype(t) for t in (int, float, 'int64')]
|
|
238
|
+
datafloat = datatype == np.dtype(float)
|
|
239
|
+
if datanum:
|
|
240
|
+
if datanan > self.lim:
|
|
241
|
+
self.plan[col] = {
|
|
242
|
+
"func":__class__.fuzzy_mean,
|
|
243
|
+
"param":{"astype":float if datafloat else int}
|
|
244
|
+
}
|
|
245
|
+
else:
|
|
246
|
+
self.plan[col] = {
|
|
247
|
+
"func":__class__.robust,
|
|
248
|
+
"param":{"method":self.method}
|
|
249
|
+
}
|
|
250
|
+
elif datatype == np.dtype(object):
|
|
251
|
+
datamodefreq = data.value_counts()[data.mode()]/len(data)
|
|
252
|
+
if datamodefreq.iloc[0] > 0.25: # TODO: in parameters?
|
|
253
|
+
self.plan[col] = {
|
|
254
|
+
"func":__class__.robust,
|
|
255
|
+
"param":{"method":"mode"}
|
|
256
|
+
}
|
|
257
|
+
else:
|
|
258
|
+
self.plan[col] = {
|
|
259
|
+
"func":__class__.fill,
|
|
260
|
+
"param":{"filler":self.filler}
|
|
261
|
+
}
|
|
262
|
+
self.fitted = True
|
|
263
|
+
# TODO: drop rows in X then y is NA
|
|
264
|
+
return self
|
|
265
|
+
|
|
266
|
+
def transform(self, X:pd.DataFrame):
|
|
267
|
+
'''Following previously setted plan'''
|
|
268
|
+
self.check_fit()
|
|
269
|
+
|
|
270
|
+
X = self.pd(X)
|
|
271
|
+
|
|
272
|
+
result = pd.DataFrame().reindex_like(X)
|
|
273
|
+
for col in X:
|
|
274
|
+
if col not in self.plan: # dtype we have no strategy for - pass through
|
|
275
|
+
result[col] = X[col]
|
|
276
|
+
continue
|
|
277
|
+
func, param = self.plan[col]["func"], self.plan[col]["param"]
|
|
278
|
+
result[col] = func(X[col],**param)
|
|
279
|
+
|
|
280
|
+
return result
|
|
281
|
+
|
|
282
|
+
class Digitalize(Encoder,FeatureTrans):
|
|
283
|
+
'''
|
|
284
|
+
There is a bunch of methods that can be used to transform data:
|
|
285
|
+
vectorization, hashing, transform by frequency, in bins, by quantiles groups, etc...
|
|
286
|
+
Here we will implement some of them in one class
|
|
287
|
+
with some logic of automatic application
|
|
288
|
+
'''
|
|
289
|
+
def __init__(self,final:bool=True,alim:int=10,mode:str="raw",ncut:int=5):
|
|
290
|
+
'''Initiating object: copying parameters to self'''
|
|
291
|
+
self.alim = alim
|
|
292
|
+
self.ncut = ncut
|
|
293
|
+
self.mode = mode
|
|
294
|
+
self.final = final
|
|
295
|
+
self.fitted = False
|
|
296
|
+
# logging.debug("Initialized %s object with parameters:\
|
|
297
|
+
# \tfinal transform (result must be not whole dataset, but 'X, y'): %s,\
|
|
298
|
+
# \tmax additional features for one-hot transformation: %s,\
|
|
299
|
+
# \ttransformation mode for numeric features: %s,\
|
|
300
|
+
# \tn of top freq features to keep: %s",
|
|
301
|
+
# __class__.__name__,final,alim,mode,ncut)
|
|
302
|
+
|
|
303
|
+
def fit(self, X:pd.DataFrame,y=None):
|
|
304
|
+
'''
|
|
305
|
+
Making a plan for transforming values
|
|
306
|
+
depending on parameters and dtypes of data
|
|
307
|
+
'''
|
|
308
|
+
X = self.pd(X)
|
|
309
|
+
|
|
310
|
+
self.features = []
|
|
311
|
+
|
|
312
|
+
for col in X.columns:
|
|
313
|
+
data = X[col]
|
|
314
|
+
datatype = data.dtype
|
|
315
|
+
datanum = datatype in [np.dtype(t) for t in (int, float, 'int64')]
|
|
316
|
+
dataunique = data.nunique()
|
|
317
|
+
if dataunique < self.alim:
|
|
318
|
+
if dataunique < 3 and datanum:
|
|
319
|
+
# logging.debug("Column %s (numeric) would be passed as is (raw)",col)
|
|
320
|
+
self.features.append({
|
|
321
|
+
'name':col,
|
|
322
|
+
'func':__class__.dull,
|
|
323
|
+
'param': {}
|
|
324
|
+
})
|
|
325
|
+
else:
|
|
326
|
+
# logging.debug("Column %s with %i columns would be one-hot encoded",col,dataunique)
|
|
327
|
+
self.features.append({
|
|
328
|
+
'name':col,
|
|
329
|
+
'func':pd.get_dummies,
|
|
330
|
+
'param': {"prefix":col[:5]} #TODO: move it to variables
|
|
331
|
+
})
|
|
332
|
+
elif datanum:
|
|
333
|
+
if self.mode == "cut":
|
|
334
|
+
# logging.debug("Column %s (numeric) would be binned in %i equal-spaced bins",col,self.ncut)
|
|
335
|
+
self.features.append({
|
|
336
|
+
'name':col,
|
|
337
|
+
'func':pd.cut,
|
|
338
|
+
'param': {"bins":self.ncut,"labels":False}
|
|
339
|
+
})
|
|
340
|
+
elif self.mode == "qcut":
|
|
341
|
+
# logging.debug("Column %s (numeric) would be binned in %i equal-sized bins",col,self.ncut)
|
|
342
|
+
self.features.append({
|
|
343
|
+
'name':col,
|
|
344
|
+
'func':pd.qcut,
|
|
345
|
+
'param': {"q":self.ncut,"labels":False,"duplicates":"drop"}
|
|
346
|
+
})
|
|
347
|
+
else: # self.mode == "raw":
|
|
348
|
+
# logging.debug("Column %s (numeric) would be passed as is (raw)",col)
|
|
349
|
+
self.features.append({
|
|
350
|
+
'name':col,
|
|
351
|
+
'func':lambda data:data,
|
|
352
|
+
'param': {}
|
|
353
|
+
})
|
|
354
|
+
else:
|
|
355
|
+
# logging.debug("Column %s (non-numeric) would be freq.coded with %i top variants",col,self.ncut)
|
|
356
|
+
self.features.append({
|
|
357
|
+
'name':col,
|
|
358
|
+
'func':__class__.top,
|
|
359
|
+
'param': {"n":self.ncut}
|
|
360
|
+
})
|
|
361
|
+
self.fitted = True
|
|
362
|
+
return self
|
|
363
|
+
|
|
364
|
+
def transform(self, X:pd.DataFrame):
|
|
365
|
+
'''Following previously setted plan'''
|
|
366
|
+
self.check_fit()
|
|
367
|
+
|
|
368
|
+
X = self.pd(X)
|
|
369
|
+
|
|
370
|
+
data_series = []
|
|
371
|
+
# logging.debug("Transforming features by the plan")
|
|
372
|
+
for feature in self.features:
|
|
373
|
+
name, func, param = feature['name'], feature['func'], feature['param']
|
|
374
|
+
# logging.debug("Column %s: Function %s applied with params %s",name,func,param)
|
|
375
|
+
data_series.append(
|
|
376
|
+
func(X[name],**param)
|
|
377
|
+
)
|
|
378
|
+
df_result = pd.concat(data_series,axis=1)
|
|
379
|
+
|
|
380
|
+
return df_result
|
|
381
|
+
|
|
382
|
+
##########################
|
|
383
|
+
### Estimators ###
|
|
384
|
+
##########################
|
|
385
|
+
|
|
386
|
+
class SlowPolyLinearReg(FeatureTrans):
|
|
387
|
+
'''
|
|
388
|
+
This is just hand-made regression class
|
|
389
|
+
to see how it can be done from scratch (using numpy and pandas)
|
|
390
|
+
'''
|
|
391
|
+
# nonlinear functions to generate additional synthetic features
|
|
392
|
+
genmap = {
|
|
393
|
+
"cbrt": {"func":np.cbrt},
|
|
394
|
+
"sqrt": {"func":np.sqrt, "check": lambda X: (X >= 0).all()},
|
|
395
|
+
"log2": {"func":np.log2, "check": lambda X: (X > 0).all()},
|
|
396
|
+
"ln": {"func":np.log, "check": lambda X: (X > 0).all()},
|
|
397
|
+
"log10":{"func":np.log10, "check": lambda X: (X > 0).all()}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
@staticmethod
|
|
401
|
+
def gener():
|
|
402
|
+
return list(SlowPolyLinearReg.genmap.keys())
|
|
403
|
+
|
|
404
|
+
@staticmethod
|
|
405
|
+
def norm():
|
|
406
|
+
return list(SlowPolyLinearReg.normap.keys())
|
|
407
|
+
|
|
408
|
+
# functions for saving or retrieving parameters and applying normalization
|
|
409
|
+
def save_load(self, value, name):
|
|
410
|
+
try:
|
|
411
|
+
stored = getattr(self,name)
|
|
412
|
+
except AttributeError:
|
|
413
|
+
stored = None
|
|
414
|
+
if type(stored) != type(None):
|
|
415
|
+
return stored
|
|
416
|
+
else:
|
|
417
|
+
setattr(self,name,value)
|
|
418
|
+
return value
|
|
419
|
+
|
|
420
|
+
# min-max rescaling
|
|
421
|
+
def minmax(self,X):
|
|
422
|
+
X_min = SlowPolyLinearReg.save_load(self,X.min(),"norm_min")
|
|
423
|
+
X_max = SlowPolyLinearReg.save_load(self,X.max(),"norm_max")
|
|
424
|
+
return (X-X_min)/(X_max-X_min)
|
|
425
|
+
|
|
426
|
+
# max normalization
|
|
427
|
+
def n_max(self,X):
|
|
428
|
+
X_max = SlowPolyLinearReg.save_load(self,X.max(),"norm_max")
|
|
429
|
+
return X/X_max
|
|
430
|
+
|
|
431
|
+
# Z-score normalization
|
|
432
|
+
def n_std(self,X):
|
|
433
|
+
X_mean = SlowPolyLinearReg.save_load(self,X.mean(),"norm_mean")
|
|
434
|
+
X_std = SlowPolyLinearReg.save_load(self,X.std(),"norm_std")
|
|
435
|
+
return (X-X_mean)/X_std
|
|
436
|
+
|
|
437
|
+
# mean normalization
|
|
438
|
+
def n_mean(self,X):
|
|
439
|
+
X_mean = SlowPolyLinearReg.save_load(self,X.mean(),"norm_mean")
|
|
440
|
+
X_min = SlowPolyLinearReg.save_load(self,X.min(),"norm_min")
|
|
441
|
+
X_max = SlowPolyLinearReg.save_load(self,X.max(),"norm_max")
|
|
442
|
+
return (X-X_mean)/(X_max-X_min)
|
|
443
|
+
|
|
444
|
+
# access to normalization functions from one dictionary
|
|
445
|
+
normap = {
|
|
446
|
+
None: lambda _, X: X,
|
|
447
|
+
"minmax": minmax,
|
|
448
|
+
"std": n_std,
|
|
449
|
+
"max": n_max,
|
|
450
|
+
"mean": n_mean
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
# object creation
|
|
454
|
+
def __init__(self,gener:list=[0,1],norm:str=None,alpha:float=None):
|
|
455
|
+
'''
|
|
456
|
+
Planning check and data generation for columns (synthetic features addon),
|
|
457
|
+
than data normalization
|
|
458
|
+
'''
|
|
459
|
+
|
|
460
|
+
self.checks = {}
|
|
461
|
+
self.generators = {}
|
|
462
|
+
self.normalize = __class__.normap.get(norm,lambda _, X: print(f"Can't find {norm} normalization") or X)
|
|
463
|
+
|
|
464
|
+
if alpha:
|
|
465
|
+
self.regular = True
|
|
466
|
+
self.alpha = alpha
|
|
467
|
+
print(f"Will apply L2 regularization with coef {alpha:.3f}")
|
|
468
|
+
else:
|
|
469
|
+
self.regular = False
|
|
470
|
+
|
|
471
|
+
for key in gener:
|
|
472
|
+
if isinstance(key,str):
|
|
473
|
+
param = __class__.genmap.get(key,{})
|
|
474
|
+
if "func" in param:
|
|
475
|
+
self.generators[key] = param["func"]
|
|
476
|
+
else:
|
|
477
|
+
raise ValueError(f"Can't find {key} function")
|
|
478
|
+
if "check" in param:
|
|
479
|
+
self.checks[key] = param["check"]
|
|
480
|
+
elif isinstance(key,int):
|
|
481
|
+
self.generators[key] = lambda X, key=key: np.power(X,key)
|
|
482
|
+
|
|
483
|
+
def __gen_cols(self,X):
|
|
484
|
+
'''
|
|
485
|
+
Generating column(s)
|
|
486
|
+
'''
|
|
487
|
+
def namecol(data,name):
|
|
488
|
+
data.columns = pd.MultiIndex.from_product([data.columns,[name]],names=['feature', 'function'])
|
|
489
|
+
|
|
490
|
+
ndim = X.ndim
|
|
491
|
+
rows, cols = X.shape
|
|
492
|
+
result = pd.DataFrame()
|
|
493
|
+
|
|
494
|
+
if X.size == 0:
|
|
495
|
+
return result
|
|
496
|
+
if ndim > 2:
|
|
497
|
+
raise ValueError("Two-dimensional array max!")
|
|
498
|
+
|
|
499
|
+
for key, generator in self.generators.items():
|
|
500
|
+
# const hack
|
|
501
|
+
if key == 0:
|
|
502
|
+
addon = pd.DataFrame(np.ones((rows,1)),index=X.index)
|
|
503
|
+
namecol(addon,0)
|
|
504
|
+
result = pd.concat([addon,result],axis=1)
|
|
505
|
+
else:
|
|
506
|
+
addon = X.apply(generator)
|
|
507
|
+
namecol(addon,key)
|
|
508
|
+
result = pd.concat([result,addon],axis=1)
|
|
509
|
+
|
|
510
|
+
return result
|
|
511
|
+
|
|
512
|
+
def complete(self, X):
|
|
513
|
+
'''
|
|
514
|
+
Apply checks, column generation and normalization
|
|
515
|
+
'''
|
|
516
|
+
X = pd.DataFrame(X)
|
|
517
|
+
if X.isna().any().any():
|
|
518
|
+
raise ValueError("NA values have no weight to learn - fill them first")
|
|
519
|
+
for key, check in self.checks.items():
|
|
520
|
+
if not X.apply(check).all():
|
|
521
|
+
raise ValueError(f"Try different column generators, other than {key}")
|
|
522
|
+
X_wide = self.__gen_cols(X)
|
|
523
|
+
if X_wide.empty:
|
|
524
|
+
return X_wide
|
|
525
|
+
# the constant column is the intercept, not a feature - it stays out of normalization
|
|
526
|
+
variable = X_wide.columns.get_level_values("function") != 0
|
|
527
|
+
X_wide = pd.concat([X_wide.loc[:,~variable],
|
|
528
|
+
self.normalize(self,X_wide.loc[:,variable])],axis=1)
|
|
529
|
+
return X_wide
|
|
530
|
+
|
|
531
|
+
def fit(self, X, y):
|
|
532
|
+
'''
|
|
533
|
+
Finding the most suitable weights for feature(s)
|
|
534
|
+
'''
|
|
535
|
+
for stat in ("norm_min","norm_max","norm_mean","norm_std"):
|
|
536
|
+
setattr(self,stat,None) # a refit is a fresh fit, not a continuation
|
|
537
|
+
|
|
538
|
+
X_wide = self.complete(X)
|
|
539
|
+
|
|
540
|
+
XTX = X_wide.T @ X_wide
|
|
541
|
+
XTY = X_wide.T @ y
|
|
542
|
+
|
|
543
|
+
if self.regular:
|
|
544
|
+
XTX = XTX + self.alpha * np.eye(XTX.shape[0])
|
|
545
|
+
|
|
546
|
+
if np.linalg.det(XTX) == 0:
|
|
547
|
+
print("Columns or rows are dependent!")
|
|
548
|
+
# TODO: try removing some of the data to get rid of this effect
|
|
549
|
+
elif np.linalg.cond(XTX) > 1e4:
|
|
550
|
+
print("Ill-conditioned matrix!")
|
|
551
|
+
try:
|
|
552
|
+
# closed-form solution
|
|
553
|
+
self.w = np.linalg.solve(XTX,XTY)
|
|
554
|
+
except np.linalg.LinAlgError:
|
|
555
|
+
print("Singular matrix - falling back to the least-norm solution")
|
|
556
|
+
self.w = np.linalg.lstsq(XTX,XTY,rcond=None)[0]
|
|
557
|
+
|
|
558
|
+
return self
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def predict(self, X):
|
|
562
|
+
'''
|
|
563
|
+
Applying previously fitted weights to new data
|
|
564
|
+
'''
|
|
565
|
+
X_wide = self.complete(X)
|
|
566
|
+
return X_wide.dot(self.w)
|
|
567
|
+
|
|
568
|
+
def score(self, X, y):
|
|
569
|
+
'''
|
|
570
|
+
R2-score of prediction
|
|
571
|
+
'''
|
|
572
|
+
y_pred = self.predict(X)
|
|
573
|
+
return 1 - ((y - y_pred)**2).sum() / ((y - np.mean(y))**2).sum()
|
bitskitten/input.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import operator
|
|
2
|
+
from typing import Callable
|
|
3
|
+
from numbers import Number
|
|
4
|
+
|
|
5
|
+
def dull(_a=None,_b=None):return True
|
|
6
|
+
oper = {
|
|
7
|
+
"==": operator.eq,
|
|
8
|
+
"!=": operator.ne,
|
|
9
|
+
"<": operator.lt,
|
|
10
|
+
">": operator.gt,
|
|
11
|
+
"<=": operator.le,
|
|
12
|
+
">=": operator.ge,
|
|
13
|
+
"": dull
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
def number(msg:str="Enter number: ", t:Callable=int, op:str=">=", limit:int=0) -> Number:
|
|
17
|
+
if t == str:
|
|
18
|
+
limit = ""
|
|
19
|
+
func = oper[op]
|
|
20
|
+
x = t(input(msg))
|
|
21
|
+
while not func(x, limit):
|
|
22
|
+
print(f"Condition {x} {op} {limit} not met, try again")
|
|
23
|
+
x = t(input(msg))
|
|
24
|
+
return x
|
bitskitten/output.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import matplotlib.pyplot as plt
|
|
4
|
+
import seaborn as sns
|
|
5
|
+
import statistics as s
|
|
6
|
+
import itertools as it
|
|
7
|
+
from math import factorial
|
|
8
|
+
|
|
9
|
+
# # # # # # # # # # # # # # # #
|
|
10
|
+
# # # # Printing functions # # # #
|
|
11
|
+
# # # # # # # # # # # # # # # #
|
|
12
|
+
|
|
13
|
+
def informer(df:pd.DataFrame,target:str) -> dict:
|
|
14
|
+
'''
|
|
15
|
+
Function for initial dataset analysis -
|
|
16
|
+
returning dict with number of observations, features & classes,
|
|
17
|
+
'''
|
|
18
|
+
df_train = df[~df[target].isna()]
|
|
19
|
+
classes = df_train[target].value_counts()
|
|
20
|
+
tr_n, tr_f = df_train.shape
|
|
21
|
+
te_n, _ = df[df[target].isna()].shape
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
"classes": classes,
|
|
25
|
+
"n_cls": len(classes),
|
|
26
|
+
"features": tr_f,
|
|
27
|
+
"train_obs": tr_n,
|
|
28
|
+
"test_obs": te_n,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
def informer_print(info:dict) -> None:
|
|
32
|
+
txt_classes = ", ".join([f"{cls}: {n/(info['train_obs']):.1%}"
|
|
33
|
+
for cls, n in info["classes"].items()])
|
|
34
|
+
print(f'''\n\tFeatures:\t{info['features']}
|
|
35
|
+
\tObservations:\t{info['train_obs']}/{info['test_obs']}
|
|
36
|
+
\ttrain dataset:\t{info['train_obs']/(info['train_obs']+info['test_obs']):.1%}
|
|
37
|
+
\tclasses:\t{txt_classes}''')
|
|
38
|
+
|
|
39
|
+
def imperfection(df:pd.DataFrame,numeric:bool=False,no_nan:bool=False) -> pd.DataFrame:
|
|
40
|
+
'''
|
|
41
|
+
Quick evaluation of missing values, types and variety of values in table columns
|
|
42
|
+
'''
|
|
43
|
+
def form_series(series:pd.Series,name:str) -> pd.Series:
|
|
44
|
+
series.name = name
|
|
45
|
+
return series
|
|
46
|
+
|
|
47
|
+
missing_df = form_series(df.isnull().sum() / len(df),"NA Share")
|
|
48
|
+
unique_df = form_series(df.apply(pd.unique),"Values")
|
|
49
|
+
nunique_df = form_series(unique_df.apply(len),"Num. of unique")
|
|
50
|
+
type_df = form_series(df.dtypes,"Type")
|
|
51
|
+
|
|
52
|
+
full_df = pd.DataFrame([missing_df,nunique_df,type_df,unique_df]).T
|
|
53
|
+
if not numeric:
|
|
54
|
+
full_df = full_df.where(
|
|
55
|
+
(full_df['Type'] != np.dtype('int64'))\
|
|
56
|
+
& (full_df['Type'] != np.dtype('float64')))\
|
|
57
|
+
.dropna()
|
|
58
|
+
if no_nan:
|
|
59
|
+
full_df = full_df.where(full_df['NA Share'] > 0).dropna()
|
|
60
|
+
return full_df.sort_values(by=['NA Share','Num. of unique'], ascending=False)
|
|
61
|
+
|
|
62
|
+
def multicolumn(series,cols:int=5) -> pd.DataFrame:
|
|
63
|
+
'''
|
|
64
|
+
Work with pd.Series and slice of pd.DataFrame:
|
|
65
|
+
Function for viewing long data series,
|
|
66
|
+
useful with df.sample().T
|
|
67
|
+
'''
|
|
68
|
+
try:
|
|
69
|
+
title = (series.columns.name, series.columns[0])
|
|
70
|
+
except AttributeError:
|
|
71
|
+
title = (series.dtype, series.name)
|
|
72
|
+
n = len(series)
|
|
73
|
+
rows= int(n//cols)
|
|
74
|
+
if rows*cols < n:
|
|
75
|
+
rows += 1
|
|
76
|
+
col_sep = pd.Series(["│"] * rows, name="│")
|
|
77
|
+
portions = []
|
|
78
|
+
for i in range(cols):
|
|
79
|
+
portion = series.iloc[rows*i:rows*(i+1)]
|
|
80
|
+
if len(portion.index) == 0:
|
|
81
|
+
break
|
|
82
|
+
portion = portion.reset_index()
|
|
83
|
+
portion.columns = [f"col_{i+1}",f"val_{i+1}"]
|
|
84
|
+
portions.append(portion)
|
|
85
|
+
portions.append(col_sep)
|
|
86
|
+
table = pd.concat(portions,axis=1)
|
|
87
|
+
return table.where(table.notna(),"").style.set_caption("{}: {}".format(*title))
|
|
88
|
+
|
|
89
|
+
# # # # # # # # # # # # # # # #
|
|
90
|
+
# # # # Plotting functions # # # #
|
|
91
|
+
# # # # # # # # # # # # # # # #
|
|
92
|
+
|
|
93
|
+
# For a visual assessment of the quality of the model, we will use the confusion matrix
|
|
94
|
+
yvg = list([(abs(np.cos(x-1)),abs(np.sin(x+1)),abs(np.sin(x*x))) for x in np.arange(-2,0,0.1)])
|
|
95
|
+
pal_yvg = sns.color_palette(yvg)
|
|
96
|
+
comb = lambda n, k: factorial(n) / (factorial(k) * factorial(n-k)) # n! / (k! * (n – k)!)
|
|
97
|
+
comb_2 = lambda n: comb(n,2)
|
|
98
|
+
|
|
99
|
+
def plot_some_scatters(X,y,name:str=None,s:float=5):
|
|
100
|
+
n, m = X.shape
|
|
101
|
+
ax_combs = tuple(it.combinations(range(m),r=2))
|
|
102
|
+
k = comb_2(m)
|
|
103
|
+
c = 1
|
|
104
|
+
for i in range(2,6):
|
|
105
|
+
if k % i == 0:
|
|
106
|
+
c = i
|
|
107
|
+
r = int(k / c)
|
|
108
|
+
|
|
109
|
+
fig, axs = plt.subplots(r,c,figsize=(s*c,s*r))
|
|
110
|
+
fig.suptitle(name)
|
|
111
|
+
for i, ax in enumerate(np.ravel(axs)):
|
|
112
|
+
x_idx, y_idx = ax_combs[i]
|
|
113
|
+
ax.scatter(X[:,x_idx],X[:,y_idx],c=y)
|
|
114
|
+
ax.set(xlabel=f"axis {x_idx}", ylabel=f"axis {y_idx}")
|
|
115
|
+
plt.show()
|
|
116
|
+
|
|
117
|
+
def plot_conf_map(
|
|
118
|
+
conf:np.ndarray,
|
|
119
|
+
title:str=None,
|
|
120
|
+
compact:bool=False,
|
|
121
|
+
figsize:tuple=(6.4, 4.8),
|
|
122
|
+
blind:bool=False) -> None:
|
|
123
|
+
'''
|
|
124
|
+
displaying the confusion matrix graphically with additional coefficients
|
|
125
|
+
'''
|
|
126
|
+
q = len(conf)
|
|
127
|
+
conf_m = np.reshape(np.array(conf),(q,q))
|
|
128
|
+
conf_share = conf_m/np.sum(conf)
|
|
129
|
+
|
|
130
|
+
true_ans = np.diag(conf_m)
|
|
131
|
+
p_list = true_ans / (np.sum(conf_m, axis=0) + 2.2250738585072014e-308 ) # divide by zero hack
|
|
132
|
+
r_list = true_ans / (np.sum(conf_m, axis=1) + 2.2250738585072014e-308 ) # divide by zero hack
|
|
133
|
+
|
|
134
|
+
# generalization of F1 metrix since we don't know in advance which class is the main one
|
|
135
|
+
|
|
136
|
+
hm = s.harmonic_mean(np.r_[p_list,r_list] + 2.2250738585072014e-308)
|
|
137
|
+
|
|
138
|
+
if not blind:
|
|
139
|
+
coef_m = np.hstack((
|
|
140
|
+
np.vstack( (conf_share,p_list) ),
|
|
141
|
+
np.append(r_list,hm).reshape(-1,1) ))
|
|
142
|
+
|
|
143
|
+
if compact:
|
|
144
|
+
labels = np.asarray([f"{share:.0%}" for share in coef_m.ravel()]).reshape(q+1,q+1)
|
|
145
|
+
else:
|
|
146
|
+
labels = np.asarray([f"{share:.1%}" for share in coef_m.ravel()]).reshape(q+1,q+1)
|
|
147
|
+
labels[-1][-1] = f"H:{hm:.0%}"
|
|
148
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
149
|
+
sns.heatmap(coef_m, annot=labels, fmt='', cmap=pal_yvg, vmin=0, vmax=1)
|
|
150
|
+
|
|
151
|
+
xlabels = [item.get_text() for item in ax.get_xticklabels()]
|
|
152
|
+
ylabels = [item.get_text() for item in ax.get_yticklabels()]
|
|
153
|
+
xlabels[-1] = 'Rate'
|
|
154
|
+
ylabels[-1] = 'Prediction\nvalue'
|
|
155
|
+
|
|
156
|
+
ax.set_xticklabels(xlabels)
|
|
157
|
+
ax.set_yticklabels(ylabels)
|
|
158
|
+
|
|
159
|
+
if title is not None:
|
|
160
|
+
plt.title(title)
|
|
161
|
+
|
|
162
|
+
plt.show()
|
|
163
|
+
|
|
164
|
+
return hm, p_list.ravel(), r_list.ravel()
|
|
165
|
+
|
|
166
|
+
# Images transforms
|
|
167
|
+
|
|
168
|
+
# This fuctions break our picture
|
|
169
|
+
def img_breakdown(img_arr):
|
|
170
|
+
return np.vstack((img_arr[:,:,0],img_arr[:,:,1],img_arr[:,:,2],img_arr[:,:,3]))
|
|
171
|
+
|
|
172
|
+
def img_breakright(img_arr):
|
|
173
|
+
return np.hstack((img_arr[:,:,0],img_arr[:,:,1],img_arr[:,:,2],img_arr[:,:,3]))
|
|
174
|
+
|
|
175
|
+
# and these collect them back
|
|
176
|
+
def img_set_up(ldown_arr):
|
|
177
|
+
q = ldown_arr.shape[0] // 4
|
|
178
|
+
return np.dstack((ldown_arr[q*0:q*1,:],ldown_arr[q*1:q*2,:],ldown_arr[q*2:q*3,:],ldown_arr[q*3:q*4,:]))
|
|
179
|
+
|
|
180
|
+
def img_set_left(ldown_arr):
|
|
181
|
+
q = ldown_arr.shape[1] // 4
|
|
182
|
+
return np.dstack((ldown_arr[:,q*0:q*1],ldown_arr[:,q*1:q*2],ldown_arr[:,q*2:q*3],ldown_arr[:,q*3:q*4]))
|
|
183
|
+
|
|
184
|
+
def img_squeeze(img_arr,trans_class,n_components,conv_pair):
|
|
185
|
+
'''
|
|
186
|
+
Main process - we break data, transform it,
|
|
187
|
+
then inverse_transform and build in original form
|
|
188
|
+
'''
|
|
189
|
+
conv_break, conv_set = conv_pair
|
|
190
|
+
data = conv_break(img_arr)
|
|
191
|
+
transform = trans_class(n_components=n_components)
|
|
192
|
+
data_trunc = transform.fit_transform(data)
|
|
193
|
+
data_re = transform.inverse_transform(data_trunc)
|
|
194
|
+
data_recol = conv_set(data_re)
|
|
195
|
+
return np.clip(data_recol, 0, 1)
|
|
196
|
+
|
|
197
|
+
def img_no_ticks(axs):
|
|
198
|
+
'''
|
|
199
|
+
Options to display pictures
|
|
200
|
+
'''
|
|
201
|
+
plt.tight_layout(pad=0.0, w_pad=0.0, h_pad=0.0)
|
|
202
|
+
for ax in axs:
|
|
203
|
+
ax.set_xticks([], [])
|
|
204
|
+
ax.set_yticks([], [])
|
|
205
|
+
|
|
206
|
+
# of course we want to see the result
|
|
207
|
+
def img_framaker(img,n,trans_class):
|
|
208
|
+
'''
|
|
209
|
+
Output function
|
|
210
|
+
'''
|
|
211
|
+
converting_pairs = ((img_breakdown, img_set_up), (img_breakright, img_set_left))
|
|
212
|
+
|
|
213
|
+
fig, ax = plt.subplots(figsize=(10,5))
|
|
214
|
+
# mixed image to reduce the number of artifacts
|
|
215
|
+
new_img = img_squeeze(img,trans_class,n,converting_pairs[0])/2+img_squeeze(img,trans_class,n,converting_pairs[1])/2
|
|
216
|
+
ax.imshow(new_img)
|
|
217
|
+
ax.text(30,50,str(n))
|
|
218
|
+
img_no_ticks([ax])
|
|
219
|
+
|
|
220
|
+
return fig
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bitskitten
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: EDA reports, plots and sklearn-compatible encoders
|
|
5
|
+
Author: Caerno
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Caerno/bitskit
|
|
8
|
+
Keywords: eda,pandas,sklearn,kaggle
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: numpy>=1.21
|
|
13
|
+
Requires-Dist: pandas>=1.3
|
|
14
|
+
Requires-Dist: scikit-learn>=1.0
|
|
15
|
+
Requires-Dist: matplotlib>=3.4
|
|
16
|
+
Requires-Dist: seaborn>=0.11
|
|
17
|
+
Requires-Dist: jinja2>=3
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# bitskitten
|
|
23
|
+
|
|
24
|
+
A small toolbox of things I kept re-typing in every EDA notebook:
|
|
25
|
+
quick dataset reports, a few plots, and sklearn-compatible encoders that can be
|
|
26
|
+
dropped straight into a `Pipeline` / `GridSearchCV`.
|
|
27
|
+
|
|
28
|
+
Nothing here is a framework. Each helper is one function or one class you can read in a minute.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install bitskitten
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The latest commit: `pip install git+https://github.com/Caerno/bitskit.git`.
|
|
37
|
+
On Kaggle / Colab the same lines work in a cell (`!pip install ...`).
|
|
38
|
+
For a kernel with no internet, add
|
|
39
|
+
[the archive GitHub builds for every commit](https://github.com/Caerno/bitskit/archive/refs/heads/main.zip)
|
|
40
|
+
as a dataset and install it from disk:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install --no-deps /kaggle/input/<your-dataset>/bitskit-main.zip
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Requires Python ≥ 3.9, numpy, pandas, scikit-learn, matplotlib, seaborn.
|
|
47
|
+
|
|
48
|
+
## Quick start
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import pandas as pd
|
|
52
|
+
from bitskitten import informer, informer_print, imperfection, NanFixer, Digitalize
|
|
53
|
+
|
|
54
|
+
df = pd.concat([train, test]) # test rows have no target -> NaN
|
|
55
|
+
|
|
56
|
+
informer_print(informer(df, "Survived"))
|
|
57
|
+
# Features: 12
|
|
58
|
+
# Observations: 891/418
|
|
59
|
+
# train dataset: 68.0%
|
|
60
|
+
# classes: 0: 61.6%, 1: 38.4%
|
|
61
|
+
|
|
62
|
+
imperfection(df) # what is missing and how varied it is
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`imperfection` returns a frame sorted by NA share — share of missing values, number of
|
|
66
|
+
unique values, dtype and the values themselves. By default it shows non-numeric columns
|
|
67
|
+
only; `numeric=True` adds the rest, `no_nan=True` keeps only columns that actually have gaps.
|
|
68
|
+
|
|
69
|
+
## Encoders
|
|
70
|
+
|
|
71
|
+
Both are `BaseEstimator` + `TransformerMixin`, so `fit`/`transform`/`fit_transform`,
|
|
72
|
+
`get_params`, `clone` and grid search over their parameters all work.
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from sklearn.pipeline import Pipeline
|
|
76
|
+
from sklearn.model_selection import GridSearchCV
|
|
77
|
+
from sklearn.ensemble import RandomForestClassifier
|
|
78
|
+
|
|
79
|
+
pipe = Pipeline([
|
|
80
|
+
("nan", NanFixer()), # fill the gaps
|
|
81
|
+
("dig", Digitalize()), # make everything numeric
|
|
82
|
+
("clf", RandomForestClassifier()),
|
|
83
|
+
])
|
|
84
|
+
|
|
85
|
+
grid = GridSearchCV(pipe, {
|
|
86
|
+
"nan__lim": [0.1, 0.225, 0.5],
|
|
87
|
+
"nan__method": ["mean", "median"],
|
|
88
|
+
"dig__mode": ["raw", "cut", "qcut"],
|
|
89
|
+
"dig__ncut": [5, 10],
|
|
90
|
+
})
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
**`NanFixer(lim=0.225, method="mean", filler="U")`** — picks a filling strategy per column
|
|
94
|
+
at `fit` time and applies it at `transform` time:
|
|
95
|
+
|
|
96
|
+
| column | condition | strategy |
|
|
97
|
+
|---|---|---|
|
|
98
|
+
| numeric | NA share ≤ `lim` | `method` (`mean`/`median`) |
|
|
99
|
+
| numeric | NA share > `lim` | random draw from the column's own normal distribution, clipped to its range |
|
|
100
|
+
| object | one value dominates (>25%) | mode |
|
|
101
|
+
| object | otherwise | the `filler` string |
|
|
102
|
+
|
|
103
|
+
Columns of any other dtype pass through untouched.
|
|
104
|
+
|
|
105
|
+
**`Digitalize(alim=10, mode="raw", ncut=5)`** — turns a mixed frame into a numeric one:
|
|
106
|
+
|
|
107
|
+
| column | condition | result |
|
|
108
|
+
|---|---|---|
|
|
109
|
+
| numeric | < 3 unique values | as is |
|
|
110
|
+
| any | < `alim` unique values | one-hot (`pd.get_dummies`) |
|
|
111
|
+
| numeric | `mode="cut"` / `"qcut"` | binned into `ncut` equal-spaced / equal-sized bins |
|
|
112
|
+
| numeric | `mode="raw"` | as is |
|
|
113
|
+
| non-numeric | ≥ `alim` unique values | top-`ncut` frequency rating (most frequent → 1, the tail → `ncut`) |
|
|
114
|
+
|
|
115
|
+
**`FeatureTrans(series)`** is the shared kit both encoders are built from, and it is
|
|
116
|
+
iterable: it yields every transformation that makes sense for that column's dtype —
|
|
117
|
+
handy when you want to throw candidate features at a selector.
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
candidates = pd.concat(list(FeatureTrans(df["Fare"])), axis=1)
|
|
121
|
+
# Fare_count, Fare_freqn, Fare_top5..., Fare_cut5..., Fare_qcut5..., Fare_sqrt, Fare_log2, Fare_pow2 ...
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Its pieces are static methods you can also call directly: `count`, `freq`, `top`,
|
|
125
|
+
`cut`, `qcut`, `math`, `bilabel`, `fuzzy_mean`, `robust`, `fill`.
|
|
126
|
+
|
|
127
|
+
## Plots
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from bitskitten import plot_conf_map, plot_some_scatters
|
|
131
|
+
|
|
132
|
+
hm, precision, recall = plot_conf_map(confusion_matrix(y_true, y_pred), title="RF")
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
`plot_conf_map` draws the confusion matrix as shares, with a precision row, a recall
|
|
136
|
+
column and — in the corner — the harmonic mean of all of them. That last number is the
|
|
137
|
+
point of it: a class-agnostic generalization of F1 for when no class is "the positive one".
|
|
138
|
+
Returns `(harmonic_mean, precision, recall)`; `blind=True` computes without drawing,
|
|
139
|
+
which is what you want inside a scoring loop.
|
|
140
|
+
|
|
141
|
+
`plot_some_scatters(X, y)` — pairwise scatter plots of every column combination, coloured by `y`.
|
|
142
|
+
|
|
143
|
+
`multicolumn(series, cols=5)` folds a long series into several columns so a wide
|
|
144
|
+
`df.sample().T` fits on one screen.
|
|
145
|
+
|
|
146
|
+
## Image compression demo
|
|
147
|
+
|
|
148
|
+
`img_squeeze` reduces the dimensionality of an RGBA image by unrolling channels into a
|
|
149
|
+
flat 2D matrix, running any sklearn decomposition on it and rebuilding the picture:
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
from sklearn.decomposition import PCA
|
|
153
|
+
from bitskitten import img_framaker
|
|
154
|
+
|
|
155
|
+
img_framaker(img, 20, PCA) # image restored from 20 components
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Estimator from scratch
|
|
159
|
+
|
|
160
|
+
`SlowPolyLinearReg(gener=[0, 1], norm=None, alpha=None)` — linear regression written on
|
|
161
|
+
numpy/pandas, with polynomial and non-linear feature generation (`0` = intercept,
|
|
162
|
+
integers = powers, `"sqrt"`/`"cbrt"`/`"log2"`/`"ln"`/`"log10"`), optional normalization
|
|
163
|
+
(`"minmax"`, `"std"`, `"max"`, `"mean"`) and L2 regularization. Closed-form solution,
|
|
164
|
+
so it warns you about singular and ill-conditioned matrices instead of hiding them
|
|
165
|
+
(and falls back to the least-norm solution rather than giving up).
|
|
166
|
+
It exists to show the mechanics, not to compete with `sklearn.linear_model`.
|
|
167
|
+
|
|
168
|
+
The default `gener=[0, 1]` is the plain intercept + x. Drop the `0` only if you
|
|
169
|
+
really want the line forced through the origin.
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
model = SlowPolyLinearReg(gener=[0, 1, 2], norm="std", alpha=0.01)
|
|
173
|
+
model.fit(X, y)
|
|
174
|
+
model.score(X, y) # R²
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## Input
|
|
178
|
+
|
|
179
|
+
`number("How many? ", t=int, op=">=", limit=0)` — keeps asking until the answer parses
|
|
180
|
+
and satisfies the condition.
|
|
181
|
+
|
|
182
|
+
## Development
|
|
183
|
+
|
|
184
|
+
```bash
|
|
185
|
+
pip install -e .[test]
|
|
186
|
+
pytest
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
The drop-in zip in `download/` is a plain stdlib call, no notebook needed:
|
|
190
|
+
|
|
191
|
+
```bash
|
|
192
|
+
python -m zipfile -c download/bitskitten.zip __init__.py classes.py input.py output.py
|
|
193
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
bitskitten/__init__.py,sha256=q7nKI2ME_DuSc9a8u_elOSHrblEgdd_mHjY4pbPHU44,848
|
|
2
|
+
bitskitten/classes.py,sha256=rzr6YzkEwA4LfCYaEhyUcQ-04KAbRPXUXJiLlMuvz-M,20350
|
|
3
|
+
bitskitten/input.py,sha256=ElZ2euANjKupfLVopq73HQMUz0QctZ0EffJVnSiwVA4,571
|
|
4
|
+
bitskitten/output.py,sha256=xbZMIOqvNozoHsFgoeXXTK6PD9AJHY73au5SkaPMYxU,7613
|
|
5
|
+
bitskitten-0.2.0.dist-info/licenses/LICENSE,sha256=UOZ1F5fFDe3XXvG4oNnkL1-Ecun7zpHzRxjp-XsMeAo,11324
|
|
6
|
+
bitskitten-0.2.0.dist-info/METADATA,sha256=cYJybCo1E54km3eMT4N22yilMEKmV9lBpP5PMyA9Eos,6757
|
|
7
|
+
bitskitten-0.2.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
8
|
+
bitskitten-0.2.0.dist-info/top_level.txt,sha256=PaBVR1V3fix8z4zN1zw29Vl1a0fHr2ymi8Fh9WhOC0w,11
|
|
9
|
+
bitskitten-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
bitskitten
|