skl_utils¶
SciKit-Learn utilities for preprocessing pipelines and weighted KNN.
This module provides transformer factories (e.g. :class:Quantizer),
:func:parse_transform for spec-based transformer construction, and
:class:TransformPipeline for composing transformers. It also provides
:class:WeighedKNNClassifier implementing sample-weighted KNN
classification/probability estimation, plus fit/predict helpers handling
single- vs multi-output target shapes.
Quantizer
¶
Uniform quantization transformer scaling data into symmetric integer bins.
Normalizes data by mean and std_k*std, rounds to integer bins, and clips to the range [-nbins, nbins].
Example
import numpy as np
q = skl_utils.Quantizer(nbins=2)
X = np.array([[1.0], [2.0], [3.0], [100.0]])
q.fit(X)
q.transform(X) # Integer values in [-2, 2].
Source code in py_misc_utils/skl_utils.py
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 | |
fit(X, *args)
¶
Compute column means and stds from X.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Input data array. |
required | |
*args
|
Ignored; present for sklearn transformer compatibility. |
()
|
Returns:
| Type | Description |
|---|---|
|
The fitted Quantizer instance. |
Source code in py_misc_utils/skl_utils.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
transform(X)
¶
Quantize X into integer bins in [-nbins, nbins].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Input data array. |
required |
Returns:
| Type | Description |
|---|---|
|
The quantized array. |
Source code in py_misc_utils/skl_utils.py
68 69 70 71 72 73 74 75 76 77 78 79 | |
fit_transform(X, *args)
¶
Fit the Quantizer on X and return the transformed data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Input data array. |
required | |
*args
|
Ignored; present for sklearn transformer compatibility. |
()
|
Returns:
| Type | Description |
|---|---|
|
The quantized array. |
Source code in py_misc_utils/skl_utils.py
81 82 83 84 85 86 87 88 89 90 91 | |
TransformPipeline
¶
A sequence of transformers applied in order to input data.
Supports adding transformers, partial_fit/full-fit, and transform. Transformers can be given as instances or spec strings: strings passed to the constructor are parsed via parse_transform(), while add() keeps them as-is.
Example
tp = skl_utils.TransformPipeline(['QTZ', 'PCA:{n_components: 1}'])
import numpy as np
tp.fit_transform(np.random.rand(8, 4))
Source code in py_misc_utils/skl_utils.py
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 | |
transformers
property
¶
Return the list of transformers in the pipeline.
Returns:
| Type | Description |
|---|---|
|
A tuple of transformer instances. |
supports_partial_fit
property
¶
Whether all transformers support partial_fit.
Returns:
| Type | Description |
|---|---|
|
True if every transformer has a partial_fit method. |
supports_fit
property
¶
Whether the pipeline supports full fit.
Returns:
| Type | Description |
|---|---|
|
True if the pipeline has at most one transformer (fit is not |
|
|
distributed correctly across multiple transformers). |
add(transformer)
¶
Append a transformer to the pipeline.
Unlike the constructor, spec strings are kept as-is instead of being parsed via parse_transform().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transformer
|
The transformer instance or spec string to add. |
required |
Source code in py_misc_utils/skl_utils.py
200 201 202 203 204 205 206 207 208 209 | |
transform(x)
¶
Apply all transformers in order to x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Input data array. |
required |
Returns:
| Type | Description |
|---|---|
|
The transformed data. |
Source code in py_misc_utils/skl_utils.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 | |
fit_transform(x)
¶
Fit and transform x through all transformers in order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Input data array. |
required |
Returns:
| Type | Description |
|---|---|
|
The transformed data. |
Source code in py_misc_utils/skl_utils.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
fit(x)
¶
Fit all transformers on x (only valid for single-transformer pipelines).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Input data array. |
required |
Returns:
| Type | Description |
|---|---|
|
The pipeline itself. |
Source code in py_misc_utils/skl_utils.py
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | |
partial_fit_transform(x)
¶
Partial-fit all transformers on x and return the transformed data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Input data array. |
required |
Returns:
| Type | Description |
|---|---|
|
The transformed data. |
Source code in py_misc_utils/skl_utils.py
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | |
WeighedKNNClassifier
¶
KNN classifier supporting per-sample weights in the neighborhood vote.
When no sample weights are provided the operations are simply delegated to sklearn.neighbors.KNeighborsClassifier; otherwise the weighted mode of the neighbor labels drives the predictions: each neighbor votes with a weight of sample_weight * neighbor-distance-weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Keyword arguments forwarded to KNeighborsClassifier. |
{}
|
Example
import numpy as np
knn = skl_utils.WeighedKNNClassifier(n_neighbors=3)
X = np.array([[0.0], [1.0], [2.0], [3.0]])
y = np.array([0, 1, 1, 2])
weights = np.array([1.0, 0.01, 0.01, 1.0])
knn.fit(X, y, sample_weight=weights)
knn.predict(np.array([[1.6]]))
Source code in py_misc_utils/skl_utils.py
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 | |
fit(X, y, sample_weight=None)
¶
Fit the classifier, recording the per-sample weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Input features. |
required | |
y
|
Target values. |
required | |
sample_weight
|
Optional per-sample weights used to weight the neighbors during prediction. |
None
|
Returns:
| Type | Description |
|---|---|
|
The fitted classifier. |
Source code in py_misc_utils/skl_utils.py
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 | |
predict(X)
¶
Predict the class labels of the samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Input features. |
required |
Returns:
| Type | Description |
|---|---|
|
The predicted labels, weighted by the sample weights when they |
|
|
were provided at fit time. |
Source code in py_misc_utils/skl_utils.py
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 | |
predict_proba(X)
¶
Predict the class probabilities of the samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Input features. |
required |
Returns:
| Type | Description |
|---|---|
|
The class probabilities accumulated from the weighted neighbor |
|
|
votes when sample weights were provided at fit time, or the |
|
|
probabilities of the wrapped classifier otherwise. |
Source code in py_misc_utils/skl_utils.py
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 | |
parse_transform(trs_spec)
¶
Create a transformer instance from a spec string.
The spec format is 'NAME' or 'NAME:cfg', where cfg is a config string parsed via pyu.parse_config (a YAML dict such as '{nbins: 4}', or a path to a YAML file).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trs_spec
|
The transformer spec string (e.g. 'QTZ', 'PCA:{n_components: 2}'). |
required |
Returns:
| Type | Description |
|---|---|
|
A configured transformer instance. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
When the transformer name is unknown. |
Example
skl_utils.parse_transform('QTZ:{nbins: 4}') # Quantizer(nbins=4)
skl_utils.parse_transform('PCA') # sklearn.decomposition.PCA()
Source code in py_misc_utils/skl_utils.py
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 | |
fit(m, x, y, **kwargs)
¶
Fit a model, normalizing single-output 2D targets to 1D.
Some sklearn models (e.g. KNeighborsClassifier) require 1D (N,) targets for single-output problems rather than (N, 1) tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
m
|
The model to fit. |
required | |
x
|
Input features. |
required | |
y
|
Target values. |
required | |
**kwargs
|
Additional keyword arguments passed to m.fit. |
{}
|
Returns:
| Type | Description |
|---|---|
|
The fitted model. |
Example
import numpy as np
import sklearn.linear_model
model = sklearn.linear_model.LinearRegression()
x = np.array([[1.0], [2.0], [3.0]])
y = np.array([[1.0], [2.0], [3.0]])
skl_utils.fit(model, x, y) # (N, 1) y is handled.
Source code in py_misc_utils/skl_utils.py
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 | |
predict(m, x, **kwargs)
¶
Predict targets, normalizing single-output results to 2D.
Some sklearn models emit 1D (N,) vectors for single-output problems; this reshapes them to (N, 1) for consistency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
m
|
The fitted model. |
required | |
x
|
Input features. |
required | |
**kwargs
|
Additional keyword arguments passed to m.predict. |
{}
|
Returns:
| Type | Description |
|---|---|
|
The predicted targets, always with ndim >= 2. |
Example
import numpy as np
import sklearn.linear_model
model = sklearn.linear_model.LinearRegression()
x = np.array([[1.0], [2.0], [3.0]])
skl_utils.fit(model, x, np.array([[1.0], [2.0], [3.0]]))
skl_utils.predict(model, x).shape # (3, 1) for single-output models.
Source code in py_misc_utils/skl_utils.py
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 | |
predict_proba(m, x, classes=None)
¶
Predict class probabilities, optionally extracting specific classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
m
|
The fitted model. |
required | |
x
|
Input features. |
required | |
classes
|
Optional list of class indices to extract per output. If None, return the model's probabilities unchanged. |
None
|
Returns:
| Type | Description |
|---|---|
|
The probability array(s), filtered to requested classes if provided. |
Example
import numpy as np
import sklearn.neighbors
model = sklearn.neighbors.KNeighborsClassifier(n_neighbors=1)
x = np.array([[0.0], [1.0], [10.0], [11.0]])
skl_utils.fit(model, x, np.array([0, 0, 1, 1]))
skl_utils.predict_proba(model, np.array([[0.5]])) # All the class probabilities.
skl_utils.predict_proba(model, np.array([[0.5]]), classes=[1]) # Only class 1.
Source code in py_misc_utils/skl_utils.py
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 | |