-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpreprocessing.py
More file actions
1424 lines (1250 loc) · 51.1 KB
/
preprocessing.py
File metadata and controls
1424 lines (1250 loc) · 51.1 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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Missing-aware preprocessing utilities with scikit-learn-like APIs."""
from __future__ import annotations
# ruff: noqa: D102, D107, DOC201, DOC501, TRY003, EM101, EM102, TC003
import warnings as _warnings_mod
from collections.abc import Sequence
from dataclasses import dataclass, field
from typing import Any, Literal, cast
import numpy as np
import scipy.sparse as sp
from ._sparsity import validate_mask_compatibility
__all__ = [
"AutoEncoder",
"DataReport",
"MissingAwareLogTransformer",
"MissingAwareMinMaxScaler",
"MissingAwareOneHotEncoder",
"MissingAwarePowerTransformer",
"MissingAwareSparseOneHotEncoder",
"MissingAwareStandardScaler",
"MissingAwareWinsorizer",
"check_data",
]
Mask = np.ndarray
ArrayLike = np.ndarray | sp.spmatrix
def _to_csr(x: ArrayLike, *, copy: bool = False) -> sp.csr_matrix:
return sp.csr_matrix(cast("Any", x), copy=copy)
def _to_csc(x: ArrayLike) -> sp.csc_matrix:
return sp.csc_matrix(cast("Any", x))
def _is_sparse(x: object) -> bool:
return sp.issparse(x)
def _ensure_mask(x: np.ndarray, mask: Mask | None) -> Mask:
"""Return a boolean mask where True marks observed entries."""
if mask is None:
if np.issubdtype(x.dtype, np.number):
return ~np.isnan(x.astype(float)) # type: ignore[no-any-return]
return ~np.not_equal(x, x) # type: ignore[no-any-return]
return np.asarray(mask, dtype=bool)
def _sparse_col_counts(mat: sp.csc_matrix) -> np.ndarray:
"""Return nonzero counts per column for a CSC matrix."""
return np.diff(mat.indptr)
def _sparse_safe_min(mat: sp.csc_matrix, counts: np.ndarray) -> np.ndarray:
mins = np.full(mat.shape[1], np.nan, dtype=float)
if mat.nnz:
for j in range(mat.shape[1]):
if counts[j] == 0:
continue
col = mat.getcol(j)
mins[j] = float(col.data.min()) if col.data.size else np.nan
return mins
def _sparse_safe_max(mat: sp.csc_matrix, counts: np.ndarray) -> np.ndarray:
maxs = np.full(mat.shape[1], np.nan, dtype=float)
if mat.nnz:
for j in range(mat.shape[1]):
if counts[j] == 0:
continue
col = mat.getcol(j)
maxs[j] = float(col.data.max()) if col.data.size else np.nan
return maxs
def _sparse_mean_var(mat: sp.csc_matrix) -> tuple[np.ndarray, np.ndarray]:
"""Compute mean/var per column ignoring missing (unstored) entries.
Returns:
Tuple of ``(means, variances)`` per column.
"""
counts = _sparse_col_counts(mat)
sums = np.array(mat.sum(axis=0)).ravel()
sumsq = np.array(mat.power(2).sum(axis=0)).ravel()
means = np.full(mat.shape[1], np.nan, dtype=float)
vars_ = np.full(mat.shape[1], np.nan, dtype=float)
nonzero = counts > 0
means[nonzero] = sums[nonzero] / counts[nonzero]
vars_[nonzero] = sumsq[nonzero] / counts[nonzero] - means[nonzero] ** 2
return means, vars_
def _safe_unique(values: np.ndarray) -> list[Any]:
"""Return ordered unique values preserving first occurrence."""
uniq: list[Any] = []
seen: set[Any] = set()
for v in values:
if v not in seen:
seen.add(v)
uniq.append(v)
return uniq
class MissingAwareOneHotEncoder:
"""One-hot encode categorical columns while respecting missing values."""
def __init__(
self,
*,
handle_unknown: Literal["ignore", "raise"] = "ignore",
mean_center: bool = False,
dtype: type = float,
) -> None:
self.handle_unknown = handle_unknown
self.mean_center = mean_center
self.dtype = dtype
self.categories_: list[list[Any]] = []
self.feature_names_out_: list[str] = []
self.column_means_: np.ndarray | None = None
self.n_features_in_: int | None = None
self._output_widths: list[int] = []
def fit(self, x: np.ndarray, mask: Mask | None = None) -> MissingAwareOneHotEncoder:
x_arr = np.asarray(x)
obs_mask = _ensure_mask(x_arr, mask)
n_features = x_arr.shape[1]
self.categories_ = []
self.feature_names_out_ = []
self._output_widths = []
means: list[float] = []
for j in range(n_features):
col_obs = obs_mask[:, j]
observed_vals = x_arr[col_obs, j]
cats = _safe_unique(observed_vals)
self.categories_.append(cats)
if len(cats) == 2:
# Mirror legacy OHspecial_transform: collapse binary to a single
# indicator column for the second category.
self.feature_names_out_.append(f"col{j}_{cats[1]}")
self._output_widths.append(1)
means.extend([0.0])
else:
for c in cats:
self.feature_names_out_.append(f"col{j}_{c}")
self._output_widths.append(len(cats))
means.extend([0.0] * len(cats))
self.column_means_ = np.array(means, dtype=self.dtype)
self.n_features_in_ = n_features
return self
def _transform_single(
self, x: np.ndarray, mask: Mask, j: int
) -> tuple[np.ndarray, list[str], np.ndarray]:
cats = self.categories_[j]
n_cats = len(cats)
if n_cats == 0:
empty: np.ndarray = np.zeros((x.shape[0], 0), dtype=self.dtype)
return empty, [], np.zeros(0, dtype=self.dtype)
col_mask = np.asarray(mask[:, j], dtype=bool)
col_vals = x[:, j]
if n_cats == 2:
return self._transform_binary(col_vals, col_mask, cats, j)
return self._transform_multicat(col_vals, col_mask, cats, j)
def _transform_binary(
self,
col_vals: np.ndarray,
col_mask: np.ndarray,
cats: list[Any],
j: int,
) -> tuple[np.ndarray, list[str], np.ndarray]:
out: np.ndarray = np.zeros((col_vals.shape[0], 1), dtype=self.dtype)
if not np.all(col_mask):
out[~col_mask, :] = np.nan
if np.any(col_mask):
cat0, cat1 = cats[0], cats[1]
obs_rows = np.nonzero(col_mask)[0]
observed_vals = col_vals[col_mask]
for row_idx, val in zip(obs_rows, observed_vals, strict=False):
if val == cat1:
out[row_idx, 0] = 1.0
elif val == cat0:
out[row_idx, 0] = 0.0
else:
if self.handle_unknown == "raise":
raise ValueError(
f"Unknown category {val!r} in binary column {j}"
)
out[row_idx, 0] = 0.0
means: np.ndarray = np.zeros(1, dtype=self.dtype)
if self.mean_center:
with np.errstate(invalid="ignore"):
means = np.nanmean(out, axis=0)
out -= means
out[~np.isfinite(out)] = np.nan
names = [f"col{j}_{cats[1]}"]
return out, names, means
def _transform_multicat(
self,
col_vals: np.ndarray,
col_mask: np.ndarray,
cats: list[Any],
j: int,
) -> tuple[np.ndarray, list[str], np.ndarray]:
n_cats = len(cats)
out: np.ndarray = np.zeros((col_vals.shape[0], n_cats), dtype=self.dtype)
if not np.all(col_mask):
out[~col_mask, :] = np.nan
if np.any(col_mask):
cat_to_idx = {cat: idx for idx, cat in enumerate(cats)}
observed_vals = col_vals[col_mask]
idxs = np.fromiter(
(cat_to_idx.get(val, -1) for val in observed_vals),
dtype=int,
count=observed_vals.size,
)
if self.handle_unknown == "raise" and np.any(idxs < 0):
bad_val = observed_vals[idxs < 0][0]
raise ValueError(f"Unknown category {bad_val!r} in column {j}")
valid = idxs >= 0
if np.any(valid):
obs_rows = np.nonzero(col_mask)[0]
out[obs_rows[valid], idxs[valid]] = 1.0
means: np.ndarray = np.zeros(n_cats, dtype=self.dtype)
if self.mean_center:
with np.errstate(invalid="ignore"):
means = np.nanmean(out, axis=0)
out -= means
out[~np.isfinite(out)] = np.nan
names = [f"col{j}_{c}" for c in cats]
return out, names, means
def transform(self, x: np.ndarray, mask: Mask | None = None) -> np.ndarray:
if self.n_features_in_ is None:
raise RuntimeError("Encoder not fitted")
x_arr = np.asarray(x)
obs_mask = _ensure_mask(x_arr, mask)
parts: list[np.ndarray] = []
means: list[float] = []
names: list[str] = []
for j in range(self.n_features_in_):
block, block_names, block_means = self._transform_single(x_arr, obs_mask, j)
parts.append(block)
names.extend(block_names)
means.extend(block_means.tolist())
self.feature_names_out_ = names
self.column_means_ = (
np.array(means, dtype=self.dtype) if self.mean_center else None
)
return (
np.concatenate(parts, axis=1)
if parts
else np.empty((x_arr.shape[0], 0), dtype=self.dtype)
)
def fit_transform(
self, x: np.ndarray, mask: Mask | None = None
) -> np.ndarray | sp.csr_matrix:
return self.fit(x, mask).transform(x, mask)
def inverse_transform(self, z: np.ndarray, mask: Mask | None = None) -> np.ndarray:
if self.n_features_in_ is None:
raise RuntimeError("Encoder not fitted")
z_arr: np.ndarray = np.asarray(z, dtype=self.dtype)
obs_mask = None
if mask is not None:
obs_mask = np.asarray(mask, dtype=bool)
out_cols: list[np.ndarray] = []
col_start = 0
mean_idx = 0
for j, cats in enumerate(self.categories_):
n_cats = len(cats)
width = self._output_widths[j] if j < len(self._output_widths) else n_cats
if n_cats == 0:
out_cols.append(np.full(z_arr.shape[0], np.nan))
continue
block = z_arr[:, col_start : col_start + width]
if self.mean_center and self.column_means_ is not None:
means = self.column_means_[mean_idx : mean_idx + width]
block += means
col_vals = np.full(z_arr.shape[0], np.nan, dtype=object)
if n_cats == 2 and width == 1:
self._decode_binary(block, col_vals, cats, obs_mask, j)
else:
self._decode_multicat(block, col_vals, cats, obs_mask, j)
out_cols.append(col_vals.astype(object))
col_start += width
mean_idx += width
return np.column_stack(out_cols)
@staticmethod
def _decode_binary(
block: np.ndarray,
col_vals: np.ndarray,
cats: list[Any],
obs_mask: np.ndarray | None,
j: int,
) -> None:
cat0, cat1 = cats[0], cats[1]
for i in range(block.shape[0]):
if obs_mask is not None and not obs_mask[i, j]:
col_vals[i] = np.nan
continue
val = block[i, 0]
if np.isnan(val):
col_vals[i] = np.nan
elif val >= 0.5:
col_vals[i] = cat1
else:
col_vals[i] = cat0
def _decode_multicat(
self,
block: np.ndarray,
col_vals: np.ndarray,
cats: list[Any],
obs_mask: np.ndarray | None,
j: int,
) -> None:
for i in range(block.shape[0]):
if obs_mask is not None and not obs_mask[i, j]:
col_vals[i] = np.nan
continue
row = block[i, :]
if np.all(np.isnan(row)):
col_vals[i] = np.nan
continue
idx = int(np.nanargmax(row))
if np.allclose(row, 0.0) and self.handle_unknown == "ignore":
col_vals[i] = np.nan
else:
col_vals[i] = cats[idx]
class _BaseScaler:
def __init__(self) -> None:
self.n_features_in_: int | None = None
def fit(self, x: ArrayLike, mask: Mask | None = None) -> _BaseScaler:
raise NotImplementedError
def transform(
self, x: ArrayLike, mask: Mask | None = None
) -> np.ndarray | sp.csr_matrix:
raise NotImplementedError
def inverse_transform(
self, z: ArrayLike, mask: Mask | None = None
) -> np.ndarray | sp.csr_matrix:
raise NotImplementedError
def fit_transform(
self, x: ArrayLike, mask: Mask | None = None
) -> np.ndarray | sp.csr_matrix:
return self.fit(x, mask).transform(x, mask)
class MissingAwareSparseOneHotEncoder:
"""Sparse one-hot encoder for categorical columns.
Assumptions:
- Input is sparse (CSR/CSC) with one column.
- Observed entries are stored; missing entries are absent.
- Categories must be numeric to round-trip through sparse matrices.
- ``mean_center`` adjusts stored values per category without
densifying.
"""
def __init__(
self,
*,
handle_unknown: Literal["ignore", "raise"] = "ignore",
mean_center: bool = False,
dtype: type = float,
) -> None:
self.handle_unknown = handle_unknown
self.mean_center = mean_center
self.dtype = dtype
self.categories_: list[float] = []
self.feature_names_out_: list[str] = []
self.column_means_: np.ndarray | None = None
self.n_features_in_: int | None = None
self._output_width: int = 0
def fit(
self, x: sp.spmatrix, mask: Mask | None = None
) -> MissingAwareSparseOneHotEncoder:
if mask is not None:
msg = "mask must be None for sparse one-hot encoder"
raise ValueError(msg)
x_csr = _to_csr(x)
if x_csr.shape[1] != 1:
msg = "sparse one-hot encoder expects a single column"
raise ValueError(msg)
if x_csr.data.size == 0:
self.categories_ = []
self.feature_names_out_ = []
self.column_means_ = np.array([], dtype=self.dtype)
self.n_features_in_ = 1
self._output_width = 0
return self
# Require numeric categories to round-trip through sparse matrices.
cats = np.unique(np.asarray(x_csr.data, dtype=float))
self.categories_ = [float(c) for c in cats.tolist()]
self.feature_names_out_ = [f"col0_{c}" for c in self.categories_]
self._output_width = len(self.categories_)
n_rows = x_csr.shape[0]
counts = np.zeros(len(self.categories_), dtype=float)
cat_to_idx = {cat: idx for idx, cat in enumerate(self.categories_)}
for val in x_csr.data:
counts[cat_to_idx[float(val)]] += 1.0
means_arr: np.ndarray = (counts / float(max(n_rows, 1))).astype(
self.dtype, copy=False
)
self.column_means_ = means_arr
self.n_features_in_ = 1
return self
def transform(self, x: sp.spmatrix, mask: Mask | None = None) -> sp.csr_matrix:
if self.n_features_in_ is None:
raise RuntimeError("Encoder not fitted")
if mask is not None:
msg = "mask must be None for sparse one-hot encoder"
raise ValueError(msg)
x_csr = _to_csr(x)
if x_csr.shape[1] != 1:
msg = "sparse one-hot encoder expects a single column"
raise ValueError(msg)
n_rows = x_csr.shape[0]
n_cats = len(self.categories_)
if n_cats == 0:
return sp.csr_matrix((n_rows, 0), dtype=self.dtype)
return self._transform_multicat_sparse(x_csr, n_rows)
def inverse_transform(
self, z: sp.spmatrix, mask: Mask | None = None
) -> sp.csr_matrix:
if self.n_features_in_ is None:
raise RuntimeError("Encoder not fitted")
if mask is not None:
msg = "mask must be None for sparse one-hot encoder"
raise ValueError(msg)
z_csr = _to_csr(z)
n_rows, n_cols = z_csr.shape
expected_width = len(self.categories_)
if n_cols != expected_width:
msg = "Input width must match fitted categories"
raise ValueError(msg)
return self._inverse_multicat_sparse(z_csr, n_rows)
def _transform_multicat_sparse(
self, x_csr: sp.csr_matrix, n_rows: int
) -> sp.csr_matrix:
rows: list[int] = []
cols: list[int] = []
data: list[float] = []
cat_to_idx = {cat: idx for idx, cat in enumerate(self.categories_)}
coo = x_csr.tocoo()
for row, val in zip(coo.row, np.asarray(coo.data, dtype=float), strict=False):
cat_idx = cat_to_idx.get(val, -1)
if cat_idx < 0:
if self.handle_unknown == "raise":
msg = f"Unknown category {val!r} in sparse one-hot encoder"
raise ValueError(msg)
continue
rows.append(int(row))
cols.append(cat_idx)
data.append(1.0)
out: sp.csr_matrix = sp.csr_matrix(
(np.array(data, dtype=self.dtype), (rows, cols)),
shape=(n_rows, len(self.categories_)),
)
if self.mean_center and self.column_means_ is not None and out.data.size > 0:
out.data -= self.column_means_[out.indices]
return out
def _inverse_binary_sparse(
self, z_csr: sp.csr_matrix, n_rows: int
) -> sp.csr_matrix:
means = self.column_means_ if self.mean_center else None
data_out: list[float] = []
row_idx_out: list[int] = []
for row in range(n_rows):
start, end = z_csr.indptr[row], z_csr.indptr[row + 1]
if end <= start:
continue
row_data = z_csr.data[start:end].copy()
if means is not None:
row_data += means[z_csr.indices[start:end]]
cat_val = self.categories_[int(np.argmax(row_data))]
row_idx_out.append(row)
data_out.append(cat_val)
if not data_out:
return sp.csr_matrix((n_rows, 1), dtype=self.dtype)
cols_out = np.zeros(len(data_out), dtype=int)
return sp.csr_matrix(
(np.array(data_out, dtype=self.dtype), (np.array(row_idx_out), cols_out)),
shape=(n_rows, 1),
)
def _inverse_multicat_sparse(
self, z_csr: sp.csr_matrix, n_rows: int
) -> sp.csr_matrix:
means = self.column_means_ if self.mean_center else None
data_out: list[float] = []
row_idx_out: list[int] = []
for row in range(n_rows):
start, end = z_csr.indptr[row], z_csr.indptr[row + 1]
if end <= start:
continue # missing row -> no stored entry
row_indices = z_csr.indices[start:end]
row_data = z_csr.data[start:end].copy()
if means is not None:
row_data += means[row_indices]
max_pos = int(np.argmax(row_data))
cat_idx = int(row_indices[max_pos])
cat_val = self.categories_[cat_idx]
row_idx_out.append(row)
data_out.append(cat_val)
if not data_out:
return sp.csr_matrix((n_rows, 1), dtype=self.dtype)
cols_out = np.zeros(len(data_out), dtype=int)
return sp.csr_matrix(
(np.array(data_out, dtype=self.dtype), (np.array(row_idx_out), cols_out)),
shape=(n_rows, 1),
)
class MissingAwareStandardScaler(_BaseScaler):
"""Standardize continuous columns ignoring missing entries."""
def __init__(self) -> None:
super().__init__()
self.mean_: np.ndarray | None = None
self.scale_: np.ndarray | None = None
self.var_: np.ndarray | None = None
def fit(
self, x: np.ndarray | sp.spmatrix, mask: Mask | None = None
) -> MissingAwareStandardScaler:
if _is_sparse(x):
x_csc = _to_csc(x)
self.n_features_in_ = x_csc.shape[1]
means, vars_ = _sparse_mean_var(x_csc)
else:
x_arr = np.asarray(x, dtype=float)
obs_mask = _ensure_mask(x_arr, mask)
self.n_features_in_ = x_arr.shape[1]
means = np.zeros(self.n_features_in_)
vars_ = np.zeros(self.n_features_in_)
for j in range(self.n_features_in_):
col = x_arr[:, j]
col_obs = obs_mask[:, j]
if not np.any(col_obs):
means[j] = np.nan
vars_[j] = np.nan
continue
col_vals = col[col_obs]
means[j] = float(np.mean(col_vals))
vars_[j] = float(np.var(col_vals))
scales = np.sqrt(vars_)
scales[~np.isfinite(scales)] = 1.0
zero_mask = np.isclose(scales, 0.0)
scales[zero_mask] = 1.0
self.mean_ = means
self.var_ = vars_
self.scale_ = scales
return self
def transform(
self, x: np.ndarray | sp.spmatrix, mask: Mask | None = None
) -> np.ndarray | sp.csr_matrix:
if self.mean_ is None or self.scale_ is None:
raise RuntimeError("Scaler not fitted")
if _is_sparse(x):
x_csr = _to_csr(x, copy=True)
if x_csr.shape[1] != len(self.mean_):
raise ValueError("Input feature count mismatch")
data = x_csr.data
cols = x_csr.indices
data = (data - self.mean_[cols]) / self.scale_[cols]
x_csr.data = data
return x_csr
x_arr = np.asarray(x, dtype=float)
obs_mask = _ensure_mask(x_arr, mask)
z = (x_arr - self.mean_) / self.scale_
z[~obs_mask] = np.nan
return z # type: ignore[no-any-return]
def inverse_transform(
self, z: np.ndarray | sp.spmatrix, mask: Mask | None = None
) -> np.ndarray | sp.csr_matrix:
if self.mean_ is None or self.scale_ is None:
raise RuntimeError("Scaler not fitted")
if _is_sparse(z):
z_csr = _to_csr(z, copy=True)
data = z_csr.data
cols = z_csr.indices
data = data * self.scale_[cols] + self.mean_[cols]
z_csr.data = data
return z_csr
z_arr = np.asarray(z, dtype=float)
obs_mask = _ensure_mask(z_arr, mask)
x = z_arr * self.scale_ + self.mean_
x[~obs_mask] = np.nan
return x # type: ignore[no-any-return]
class MissingAwareMinMaxScaler(_BaseScaler):
"""Scale features to [0, 1] range while ignoring missing entries."""
def __init__(self) -> None:
super().__init__()
self.data_min_: np.ndarray | None = None
self.data_max_: np.ndarray | None = None
self.data_range_: np.ndarray | None = None
def fit(
self, x: np.ndarray | sp.spmatrix, mask: Mask | None = None
) -> MissingAwareMinMaxScaler:
if _is_sparse(x):
x_csc = _to_csc(x)
self.n_features_in_ = x_csc.shape[1]
counts = _sparse_col_counts(x_csc)
data_min = _sparse_safe_min(x_csc, counts)
data_max = _sparse_safe_max(x_csc, counts)
else:
x_arr = np.asarray(x, dtype=float)
obs_mask = _ensure_mask(x_arr, mask)
self.n_features_in_ = x_arr.shape[1]
data_min = np.full(self.n_features_in_, np.nan, dtype=float)
data_max = np.full(self.n_features_in_, np.nan, dtype=float)
for j in range(self.n_features_in_):
col_obs = obs_mask[:, j]
if not np.any(col_obs):
continue
col_vals = x_arr[col_obs, j]
data_min[j] = float(np.min(col_vals))
data_max[j] = float(np.max(col_vals))
data_range = data_max - data_min
data_range[~np.isfinite(data_range)] = 1.0
zero_mask = np.isclose(data_range, 0.0)
data_range[zero_mask] = 1.0
self.data_min_ = data_min
self.data_max_ = data_max
self.data_range_ = data_range
return self
def transform(
self, x: np.ndarray | sp.spmatrix, mask: Mask | None = None
) -> np.ndarray | sp.csr_matrix:
if self.data_min_ is None or self.data_range_ is None:
raise RuntimeError("Scaler not fitted")
if _is_sparse(x):
x_csr = _to_csr(x, copy=True)
if x_csr.shape[1] != len(self.data_min_):
raise ValueError("Input feature count mismatch")
data = x_csr.data
cols = x_csr.indices
data = (data - self.data_min_[cols]) / self.data_range_[cols]
x_csr.data = data
return x_csr
x_arr = np.asarray(x, dtype=float)
obs_mask = _ensure_mask(x_arr, mask)
z = (x_arr - self.data_min_) / self.data_range_
z[~obs_mask] = np.nan
return z # type: ignore[no-any-return]
def inverse_transform(
self, z: np.ndarray | sp.spmatrix, mask: Mask | None = None
) -> np.ndarray | sp.csr_matrix:
if self.data_min_ is None or self.data_range_ is None:
raise RuntimeError("Scaler not fitted")
if _is_sparse(z):
z_csr = _to_csr(z, copy=True)
data = z_csr.data
cols = z_csr.indices
data = data * self.data_range_[cols] + self.data_min_[cols]
z_csr.data = data
return z_csr
z_arr = np.asarray(z, dtype=float)
obs_mask = _ensure_mask(z_arr, mask)
x = z_arr * self.data_range_ + self.data_min_
x[~obs_mask] = np.nan
return x # type: ignore[no-any-return]
@dataclass
class _ColumnPlan:
kind: Literal["categorical", "continuous"]
encoder: Any
slice_start: int
slice_end: int
class AutoEncoder:
"""Column-wise router that applies missing-aware OHE or scaling."""
def __init__(
self,
*,
cardinality_threshold: int = 20,
continuous_scaler: Literal["standard", "minmax"] = "standard",
handle_unknown: Literal["ignore", "raise"] = "ignore",
mean_center_ohe: bool = False,
column_types: Sequence[Literal["categorical", "continuous"]] | None = None,
) -> None:
self.cardinality_threshold = cardinality_threshold
self.continuous_scaler = continuous_scaler
self.handle_unknown = handle_unknown
self.mean_center_ohe = mean_center_ohe
self.column_types = column_types
self.n_features_in_: int | None = None
self.feature_names_out_: list[str] = []
self._plan: list[_ColumnPlan] = []
def _infer_kind(
self, col: np.ndarray, mask: Mask, idx: int
) -> Literal["categorical", "continuous"]:
if self.column_types is not None:
return self.column_types[idx]
observed = col[mask]
if observed.size == 0:
return "categorical"
if observed.dtype.kind in {"U", "S", "O"}:
return "categorical"
if np.issubdtype(observed.dtype, np.integer):
uniq = np.unique(observed)
return (
"categorical"
if uniq.size <= self.cardinality_threshold
else "continuous"
)
return "continuous"
def _infer_kind_sparse(
self, col: sp.spmatrix, idx: int
) -> Literal["categorical", "continuous"]:
if self.column_types is not None:
return self.column_types[idx]
col_csr = _to_csr(col)
data = np.asarray(col_csr.data)
if data.size == 0:
return "categorical"
if np.issubdtype(data.dtype, np.integer):
uniq = np.unique(data)
return (
"categorical"
if uniq.size <= self.cardinality_threshold
else "continuous"
)
return "continuous"
def fit(self, x: np.ndarray | sp.spmatrix, mask: Mask | None = None) -> AutoEncoder:
is_sparse = _is_sparse(x)
if is_sparse and mask is not None:
raise ValueError("mask must be None when fitting sparse data")
if is_sparse:
x_csr = _to_csr(x)
self.n_features_in_ = x_csr.shape[1]
self._plan = []
self.feature_names_out_ = []
col_start = 0
for j in range(self.n_features_in_):
kind = self._infer_kind_sparse(x_csr.getcol(j), j)
encoder: Any
if kind == "categorical":
encoder = MissingAwareSparseOneHotEncoder(
handle_unknown=self.handle_unknown,
mean_center=self.mean_center_ohe,
)
else:
encoder = (
MissingAwareStandardScaler()
if self.continuous_scaler == "standard"
else MissingAwareMinMaxScaler()
)
col_mat = _to_csr(x_csr.getcol(j))
encoder.fit(col_mat, mask=None)
z = encoder.transform(col_mat, mask=None)
width = z.shape[1]
if kind == "categorical" and hasattr(encoder, "categories_"):
names = [f"col{j}_{c}" for c in getattr(encoder, "categories_", [])]
else:
names = [f"col{j}"] * width
self.feature_names_out_.extend(names)
self._plan.append(
_ColumnPlan(
kind=kind,
encoder=encoder,
slice_start=col_start,
slice_end=col_start + width,
)
)
col_start += width
return self
x_dense = np.asarray(x)
obs_mask = _ensure_mask(x_dense, mask)
self.n_features_in_ = x_dense.shape[1]
self._plan = []
self.feature_names_out_ = []
col_start = 0
for j in range(self.n_features_in_):
kind = (
self.column_types[j]
if self.column_types is not None
else self._infer_kind(x_dense[:, j], obs_mask[:, j], j)
)
encoder_dense: Any
if kind == "categorical":
encoder_dense = MissingAwareOneHotEncoder(
handle_unknown=self.handle_unknown,
mean_center=self.mean_center_ohe,
)
else:
encoder_dense = (
MissingAwareStandardScaler()
if self.continuous_scaler == "standard"
else MissingAwareMinMaxScaler()
)
encoder_dense.fit(x_dense[:, [j]], mask=obs_mask[:, [j]])
z = encoder_dense.transform(x_dense[:, [j]], mask=obs_mask[:, [j]])
width = z.shape[1]
self.feature_names_out_.extend(
getattr(encoder_dense, "feature_names_out_", [f"col{j}"] * width)
)
self._plan.append(
_ColumnPlan(
kind=kind,
encoder=encoder_dense,
slice_start=col_start,
slice_end=col_start + width,
)
)
col_start += width
return self
def transform(
self, x: np.ndarray | sp.spmatrix, mask: Mask | None = None
) -> np.ndarray | sp.spmatrix:
if self.n_features_in_ is None:
raise RuntimeError("AutoEncoder not fitted")
is_sparse = _is_sparse(x)
if is_sparse:
if mask is not None:
raise ValueError("mask must be None when transforming sparse data")
x_csr = _to_csr(x)
parts_sparse: list[sp.csr_matrix] = []
for col_idx, plan in enumerate(self._plan):
z_part = plan.encoder.transform(x_csr.getcol(col_idx), mask=None)
parts_sparse.append(cast("sp.csr_matrix", z_part))
if not parts_sparse:
return sp.csr_matrix((x_csr.shape[0], 0))
return sp.hstack(parts_sparse, format="csr") # type: ignore[no-any-return]
x_dense = np.asarray(x)
obs_mask = _ensure_mask(x_dense, mask)
parts_dense: list[np.ndarray] = []
for col_idx, plan in enumerate(self._plan):
z = plan.encoder.transform(
x_dense[:, [col_idx]], mask=obs_mask[:, [col_idx]]
)
parts_dense.append(z)
if not parts_dense:
return np.empty((x_dense.shape[0], 0))
return np.concatenate(tuple(parts_dense), axis=1)
def fit_transform(
self, x: np.ndarray | sp.spmatrix, mask: Mask | None = None
) -> np.ndarray | sp.spmatrix:
return self.fit(x, mask).transform(x, mask)
def inverse_transform(
self, z: np.ndarray | sp.spmatrix, mask: Mask | None = None
) -> np.ndarray | sp.csr_matrix:
if self.n_features_in_ is None:
raise RuntimeError("AutoEncoder not fitted")
if _is_sparse(z):
if mask is not None:
msg = "mask must be None when inverse_transform on sparse data"
raise ValueError(msg)
z_csr = _to_csr(z)
col_blocks: list[sp.csr_matrix] = []
for plan in self._plan:
col_idx = np.arange(plan.slice_start, plan.slice_end, dtype=int)
block_csr = z_csr[:, col_idx]
inv = plan.encoder.inverse_transform(block_csr, mask=None)
if not sp.isspmatrix(inv):
msg = (
"sparse inverse_transform requires encoder to return a"
f" sparse matrix (column kind={plan.kind})"
)
raise ValueError(msg)
inv_csr = sp.csr_matrix(cast("Any", inv))
if inv_csr.shape[1] != 1:
msg = (
"encoder inverse must output a single column for sparse decode"
)
raise ValueError(msg)
col_blocks.append(inv_csr)
if not col_blocks:
return sp.csr_matrix((z_csr.shape[0], 0))
return cast("sp.csr_matrix", sp.hstack(col_blocks, format="csr"))
z_arr = np.asarray(z)
if mask is not None:
validate_mask_compatibility(
z_arr,
mask,
allow_sparse_mask_for_dense=False,
allow_dense_mask_for_sparse=False,
context="autoencoder.inverse_transform",
)
out_cols: list[np.ndarray] = []
for plan in self._plan:
block = z_arr[:, plan.slice_start : plan.slice_end]
inv = plan.encoder.inverse_transform(block, mask=None)
out_cols.append(inv[:, 0])
return np.column_stack(out_cols)
# ── Distributional transforms (#80) ──────────────────────────────────────
class MissingAwareLogTransformer:
"""Apply ``log1p`` (or ``log(x + offset)``) while preserving NaN entries.
This is a *pre-scaling* transform: compress right-skewed features
before standardisation so that the standard deviation better reflects
the bulk of the data rather than extreme tails.
Args:
offset: Additive constant before taking the log. The default
``1.0`` gives the standard ``log1p`` transform.
"""
def __init__(self, *, offset: float = 1.0) -> None:
if offset <= 0:
msg = "offset must be positive"
raise ValueError(msg)
self.offset = offset
self.n_features_in_: int | None = None
def fit(
self,
x: np.ndarray,
mask: Mask | None = None, # noqa: ARG002
) -> MissingAwareLogTransformer:
"""Record input width (stateless transform)."""
self.n_features_in_ = np.asarray(x).shape[1]
return self
def transform(self, x: np.ndarray, mask: Mask | None = None) -> np.ndarray:
"""Apply ``log(x + offset)`` to observed entries."""
if self.n_features_in_ is None:
raise RuntimeError("Transformer not fitted")
x_arr = np.asarray(x, dtype=float)
obs = _ensure_mask(x_arr, mask)
out = np.full_like(x_arr, np.nan)
out[obs] = np.log(x_arr[obs] + self.offset)
return out
def fit_transform(self, x: np.ndarray, mask: Mask | None = None) -> np.ndarray:
return self.fit(x, mask).transform(x, mask)
def inverse_transform(self, z: np.ndarray, mask: Mask | None = None) -> np.ndarray:
"""Reverse via ``exp(z) - offset``."""
if self.n_features_in_ is None:
raise RuntimeError("Transformer not fitted")
z_arr = np.asarray(z, dtype=float)
obs = _ensure_mask(z_arr, mask)
out = np.full_like(z_arr, np.nan)
out[obs] = np.exp(z_arr[obs]) - self.offset
return out