-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathscalers.py
More file actions
222 lines (177 loc) · 7.06 KB
/
scalers.py
File metadata and controls
222 lines (177 loc) · 7.06 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
"""Data scaling functions."""
from scipy import sparse
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.utils.validation import check_array
def _validate_and_align(X_train, X_test):
"""Validate arrays as numeric 2D matrices and ensure matching feature counts.
Parameters
----------
X_train : array-like of shape (n_samples, n_features)
Training feature matrix used for validation reference.
X_test : array-like of shape (m_samples, n_features), optional
Test feature matrix to validate against training matrix.
Returns
-------
(X_train_valid, X_test_valid) : tuple
Validated arrays. X_test_valid is None if X_test is None.
Raises
------
ValueError
If X_test has different number of features than X_train.
"""
X_train = check_array(X_train, accept_sparse=True, dtype="numeric")
if X_test is not None:
X_test = check_array(X_test, accept_sparse=True, dtype="numeric")
if X_test.shape[1] != X_train.shape[1]:
raise ValueError(
f"X_test has {X_test.shape[1]} features but X_train has {X_train.shape[1]}."
)
return X_train, X_test
def apply_scaling(X_train, X_test=None, method=None, return_transformer=False):
"""Apply normalization or standardization to the input data.
The preprocessing is fit on the training data and then applied to both
training and test data (if provided).
Parameters
----------
X_train : array-like of shape (n_samples, n_features)
Feature matrix used specifically for model training.
X_test : array-like of shape (m_samples, n_features), optional
Feature matrix used for model evaluation and prediction.
method : {"norm", "std", None}, optional
- "norm": Min-Max scaling to [0, 1]
- "std" : Standardization (mean=0, std=1)
- None : No preprocessing
return_transformer : bool, default=False
If True, also return the fitted scaling object.
Returns
-------
(X_train_scaled, X_test_scaled) or (X_train_scaled, X_test_scaled, scaler)
Scaled arrays; X_test_scaled is None if X_test is None.
If return_transformer=True and method=None, scaler is None.
Raises
------
ValueError
If an unknown scaling method is specified.
Examples
--------
>>> import numpy as np
>>> from preprocessing.scalers import apply_scaling
>>> X_train = np.array([[1.0, 2.0], [2.0, 4.0], [3.0, 6.0]])
>>> X_test = np.array([[2.5, 5.0]])
>>> X_train_scaled, X_test_scaled = apply_scaling(X_train, X_test, method="norm")
>>> X_train_scaled
array([[0. , 0. ],
[0.5, 0.5],
[1. , 1. ]])
>>> X_test_scaled
array([[0.75, 0.75]])
>>> X_train_scaled, X_test_scaled = apply_scaling(X_train, X_test, method="std")
>>> X_train_scaled.round(3)
array([[-1.225, -1.225],
[ 0. , 0. ],
[ 1.225, 1.225]])
>>> X_test_scaled.round(3)
array([[0.612, 0.612]])
"""
if method is None:
return (X_train, X_test, None) if return_transformer else (X_train, X_test)
if not isinstance(method, str):
raise ValueError("Scaling method must be a string or None.")
key = method.lower()
if key == "norm":
return minmax_scale(X_train, X_test, return_transformer)
elif key == "std":
return standardize(X_train, X_test, return_transformer)
else:
raise ValueError(
f"Unknown scaling method '{method}'. Valid options: 'norm', 'std', None."
)
def minmax_scale(X_train, X_test=None, return_transformer=False):
"""Scale features to a fixed range between 0 and 1.
Fits scaling parameters on training data and applies the same transformation
to both training and test sets.
Parameters
----------
X_train : array-like of shape (n_samples, n_features)
Training feature matrix used to fit scaling parameters.
X_test : array-like of shape (m_samples, n_features), optional
Test feature matrix to transform using fitted parameters.
return_transformer : bool, default=False
If True, also return the fitted scaling object.
Returns
-------
(X_train_scaled, X_test_scaled) or (X_train_scaled, X_test_scaled, scaler)
Scaled arrays; X_test_scaled is None if X_test is None.
Raises
------
ValueError
If X_test has a different number of features than X_train.
Examples
--------
>>> import numpy as np
>>> from preprocessing.scalers import minmax_scale
>>> X_train = np.array([[1.0, 2.0], [2.0, 4.0], [3.0, 6.0]])
>>> X_test = np.array([[2.5, 5.0]])
>>> X_train_scaled, X_test_scaled = minmax_scale(X_train, X_test)
>>> X_train_scaled
array([[0. , 0. ],
[0.5, 0.5],
[1. , 1. ]])
>>> X_test_scaled
array([[0.75, 0.75]])
"""
X_train, X_test = _validate_and_align(X_train, X_test)
scaler = MinMaxScaler(feature_range=(0.0, 1.0))
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test) if X_test is not None else None
if return_transformer:
return X_train_scaled, X_test_scaled, scaler
else:
return X_train_scaled, X_test_scaled
def standardize(X_train, X_test=None, return_transformer=False):
"""Standardize features to have zero mean and unit variance.
Fits scaling parameters on training data and applies the same transformation
to both training and test sets. For sparse matrices, centering is disabled
to preserve sparsity.
Parameters
----------
X_train : array-like of shape (n_samples, n_features)
Feature matrix used specifically for model training.
X_test : array-like of shape (m_samples, n_features), optional
Test feature matrix to transform using fitted parameters.
return_transformer: bool, default=False
If True, also return the fitted scaling object.
Returns
-------
(X_train_scaled, X_test_scaled) or (X_train_scaled, X_test_scaled, scaler)
Scaled arrays; X_test_scaled is None if X_test is None.
Raises
------
ValueError
If X_test has a different number of features than X_train.
Examples
--------
>>> import numpy as np
>>> from preprocessing.scalers import standardize
>>> X_train = np.array([[1.0, 2.0], [2.0, 4.0], [3.0, 6.0]])
>>> X_test = np.array([[2.5, 5.0]])
>>> X_train_scaled, X_test_scaled = standardize(X_train, X_test)
>>> X_train_scaled.round(3)
array([[-1.225, -1.225],
[ 0. , 0. ],
[ 1.225, 1.225]])
>>> X_test_scaled.round(3)
array([[0.612, 0.612]])
"""
X_train, X_test = _validate_and_align(X_train, X_test)
scaler = (
StandardScaler(with_mean=False)
if sparse.issparse(X_train)
else StandardScaler()
)
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test) if X_test is not None else None
if return_transformer:
return X_train_scaled, X_test_scaled, scaler
else:
return X_train_scaled, X_test_scaled