ProbabilisticNN 0.0.1__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.
- probabilisticnn/__init__.py +0 -0
- probabilisticnn/base/__init__.py +35 -0
- probabilisticnn/base/kernels.py +370 -0
- probabilisticnn/base/loss.py +444 -0
- probabilisticnn/base/optim.py +325 -0
- probabilisticnn/base/types.py +15 -0
- probabilisticnn/base/utils.py +103 -0
- probabilisticnn/common/__init__.py +8 -0
- probabilisticnn/common/pattern_layer.py +215 -0
- probabilisticnn/grnn/__init__.py +8 -0
- probabilisticnn/grnn/grnn.py +207 -0
- probabilisticnn/grnn/layers.py +13 -0
- probabilisticnn/numba_backend/__init__.py +9 -0
- probabilisticnn/numba_backend/inference/__init__.py +7 -0
- probabilisticnn/numba_backend/inference/grnn.py +29 -0
- probabilisticnn/numba_backend/inference/pnn.py +34 -0
- probabilisticnn/numba_backend/kernels.py +458 -0
- probabilisticnn/pnn/__init__.py +8 -0
- probabilisticnn/pnn/layers.py +83 -0
- probabilisticnn/pnn/pnn.py +239 -0
- probabilisticnn-0.0.1.dist-info/METADATA +344 -0
- probabilisticnn-0.0.1.dist-info/RECORD +25 -0
- probabilisticnn-0.0.1.dist-info/WHEEL +5 -0
- probabilisticnn-0.0.1.dist-info/licenses/LICENCE +19 -0
- probabilisticnn-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import warnings
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from scipy.optimize import minimize
|
|
5
|
+
|
|
6
|
+
from probabilisticnn.base.utils import cast_to_dtype
|
|
7
|
+
from probabilisticnn.base.loss import _resolve_loss
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
SOLVER_REGISTRY = {
|
|
11
|
+
"auto": "SLSQP",
|
|
12
|
+
"lbfgs": "L-BFGS-B",
|
|
13
|
+
"l_bfgs_b": "L-BFGS-B",
|
|
14
|
+
"bfgs": "BFGS",
|
|
15
|
+
"cg": "CG",
|
|
16
|
+
"newton_cg": "Newton-CG",
|
|
17
|
+
"slsqp": "SLSQP",
|
|
18
|
+
"tnc": "TNC",
|
|
19
|
+
"nelder_mead": "Nelder-Mead",
|
|
20
|
+
"powell": "Powell",
|
|
21
|
+
"cobyla": "COBYLA",
|
|
22
|
+
"cobyqa": "COBYQA",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
GRADIENT_SOLVERS = {
|
|
26
|
+
"L-BFGS-B",
|
|
27
|
+
"BFGS",
|
|
28
|
+
"CG",
|
|
29
|
+
"Newton-CG",
|
|
30
|
+
"SLSQP",
|
|
31
|
+
"TNC",
|
|
32
|
+
}
|
|
33
|
+
BOUNDED_SOLVERS = {
|
|
34
|
+
"L-BFGS-B",
|
|
35
|
+
"SLSQP",
|
|
36
|
+
"TNC",
|
|
37
|
+
"Powell",
|
|
38
|
+
"Nelder-Mead",
|
|
39
|
+
"COBYQA",
|
|
40
|
+
}
|
|
41
|
+
DEFAULT_MIN_BANDWIDTH = 1e-6
|
|
42
|
+
DEFAULT_MAX_BANDWIDTH = 1e6
|
|
43
|
+
INVALID_OBJECTIVE = 1e12
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _resolve_solver(solver):
|
|
47
|
+
try:
|
|
48
|
+
return SOLVER_REGISTRY[solver.lower()]
|
|
49
|
+
except KeyError as exc:
|
|
50
|
+
available = ", ".join(sorted(SOLVER_REGISTRY))
|
|
51
|
+
raise ValueError(f"Unknown solver={solver!r}. Available: {available}") from exc
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class BandwidthOptimizer:
|
|
55
|
+
"""Optimize AdaptivePNN/AdaptiveGRNN bandwidth parameters."""
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
model,
|
|
60
|
+
loss="log_likelihood_ratio",
|
|
61
|
+
max_iter=100,
|
|
62
|
+
solver="auto",
|
|
63
|
+
solver_options=None,
|
|
64
|
+
):
|
|
65
|
+
self.max_iter = max_iter
|
|
66
|
+
self.loss = loss
|
|
67
|
+
self.loss_fn_ = _resolve_loss(loss, model)
|
|
68
|
+
self.model = model
|
|
69
|
+
self.solver = _resolve_solver(solver)
|
|
70
|
+
self.solver_options = solver_options
|
|
71
|
+
|
|
72
|
+
def _is_pnn_model(self):
|
|
73
|
+
if not hasattr(self, "is_pnn_model"):
|
|
74
|
+
from probabilisticnn.pnn.pnn import PNN
|
|
75
|
+
self.is_pnn_model = isinstance(self.model, PNN)
|
|
76
|
+
return self.is_pnn_model
|
|
77
|
+
|
|
78
|
+
def _infer_dtype(self):
|
|
79
|
+
compute_dtype = getattr(self.model, "compute_dtype", "auto")
|
|
80
|
+
if compute_dtype in {"float32", "float64"}:
|
|
81
|
+
return compute_dtype
|
|
82
|
+
|
|
83
|
+
pattern_dtype = getattr(self.model.pattern_layer_.patterns_, "dtype", None)
|
|
84
|
+
if pattern_dtype == np.float32:
|
|
85
|
+
return "float32"
|
|
86
|
+
if pattern_dtype == np.float64:
|
|
87
|
+
return "float64"
|
|
88
|
+
return "auto"
|
|
89
|
+
|
|
90
|
+
def _forward_state(self, bandwidth):
|
|
91
|
+
"""Run the model's LOO training forward pass."""
|
|
92
|
+
if self._is_pnn_model():
|
|
93
|
+
y_pred = self.model._forward_train(bandwidth, return_encoded=True)
|
|
94
|
+
f = self.model.summation_layer_.last_f_
|
|
95
|
+
proba = self.model.output_layer_.posteriori(f)
|
|
96
|
+
return y_pred, f, proba
|
|
97
|
+
|
|
98
|
+
y_pred = self.model._forward_train(bandwidth)
|
|
99
|
+
return y_pred, None, None
|
|
100
|
+
|
|
101
|
+
def _gradient_args(self):
|
|
102
|
+
"""Build additional arguments for scipy.optimize.minimize jac callback."""
|
|
103
|
+
X = self.model.pattern_layer_.patterns_
|
|
104
|
+
if self._is_pnn_model():
|
|
105
|
+
y = self.model.y_
|
|
106
|
+
else:
|
|
107
|
+
y = self.model.summation_layer_.y_
|
|
108
|
+
return (X, y, self.model, True)
|
|
109
|
+
|
|
110
|
+
def _bandwidth_limits(self):
|
|
111
|
+
"""Return safe lower/upper bounds for bandwidth parameters."""
|
|
112
|
+
min_bandwidth = float(getattr(self.model, "min_bandwidth", DEFAULT_MIN_BANDWIDTH))
|
|
113
|
+
max_bandwidth = float(getattr(self.model, "max_bandwidth", DEFAULT_MAX_BANDWIDTH))
|
|
114
|
+
|
|
115
|
+
if not np.isfinite(min_bandwidth) or not np.isfinite(max_bandwidth):
|
|
116
|
+
raise ValueError("Bandwidth bounds must be finite.")
|
|
117
|
+
if min_bandwidth <= 0:
|
|
118
|
+
raise ValueError("min_bandwidth must be strictly positive.")
|
|
119
|
+
if min_bandwidth >= max_bandwidth:
|
|
120
|
+
raise ValueError("min_bandwidth must be smaller than max_bandwidth.")
|
|
121
|
+
|
|
122
|
+
return min_bandwidth, max_bandwidth
|
|
123
|
+
|
|
124
|
+
def _theta_limits(self):
|
|
125
|
+
"""Return bandwidth bounds mapped into the log-parameterization."""
|
|
126
|
+
min_bandwidth, max_bandwidth = self._bandwidth_limits()
|
|
127
|
+
return np.log(min_bandwidth), np.log(max_bandwidth)
|
|
128
|
+
|
|
129
|
+
def _theta_is_safe(self, theta):
|
|
130
|
+
"""Return whether theta is finite and within the solver bounds."""
|
|
131
|
+
theta = np.asarray(theta, dtype=np.float64)
|
|
132
|
+
if not np.isfinite(theta).all():
|
|
133
|
+
return False
|
|
134
|
+
|
|
135
|
+
theta_min, theta_max = self._theta_limits()
|
|
136
|
+
return bool(np.all(theta >= theta_min) and np.all(theta <= theta_max))
|
|
137
|
+
|
|
138
|
+
def _pack_bandwidth(self):
|
|
139
|
+
"""Pack current bandwidth into a flat log-space vector.
|
|
140
|
+
|
|
141
|
+
Log-parameterization keeps bandwidth positive without box constraints.
|
|
142
|
+
"""
|
|
143
|
+
min_bandwidth, max_bandwidth = self._bandwidth_limits()
|
|
144
|
+
bandwidth_params = np.asarray(
|
|
145
|
+
np.clip(self.model.pattern_layer_.bandwidth_params, min_bandwidth, max_bandwidth),
|
|
146
|
+
dtype=np.float64,
|
|
147
|
+
)
|
|
148
|
+
bandwidth_params = np.log(bandwidth_params)
|
|
149
|
+
if self.model.pattern_layer_.bandwidth_sharing == "per_class_per_feature":
|
|
150
|
+
return bandwidth_params.ravel().copy()
|
|
151
|
+
return bandwidth_params.copy()
|
|
152
|
+
|
|
153
|
+
def _unpack_bandwidth(self, theta):
|
|
154
|
+
"""Unpack bandwidth from the log-space optimization vector."""
|
|
155
|
+
theta = np.asarray(theta, dtype=np.float64)
|
|
156
|
+
pattern_layer = self.model.pattern_layer_
|
|
157
|
+
bandwidth_sharing = pattern_layer.bandwidth_sharing
|
|
158
|
+
|
|
159
|
+
if bandwidth_sharing == "per_feature":
|
|
160
|
+
return np.exp(theta).reshape(pattern_layer.feature_size)
|
|
161
|
+
if bandwidth_sharing == "per_class":
|
|
162
|
+
return np.exp(theta).reshape(pattern_layer.n_classes_)
|
|
163
|
+
if bandwidth_sharing == "per_class_per_feature":
|
|
164
|
+
return np.exp(theta).reshape(pattern_layer.n_classes_, pattern_layer.feature_size)
|
|
165
|
+
|
|
166
|
+
raise ValueError(f"Unknown bandwidth_sharing={bandwidth_sharing!r}.")
|
|
167
|
+
|
|
168
|
+
def _objective(self, theta, *args, **kwargs):
|
|
169
|
+
"""Compute the scalar optimization objective."""
|
|
170
|
+
theta = np.asarray(theta, dtype=np.float64)
|
|
171
|
+
if not self._theta_is_safe(theta):
|
|
172
|
+
return INVALID_OBJECTIVE
|
|
173
|
+
|
|
174
|
+
bandwidth = self._unpack_bandwidth(theta)
|
|
175
|
+
if not np.isfinite(bandwidth).all() or np.any(bandwidth <= 0):
|
|
176
|
+
return INVALID_OBJECTIVE
|
|
177
|
+
|
|
178
|
+
y_pred, f, proba = self._forward_state(bandwidth)
|
|
179
|
+
|
|
180
|
+
if self._is_pnn_model():
|
|
181
|
+
y_true = self.model.output_layer_.y_encoded_
|
|
182
|
+
loss = self.loss_fn_(y_true, y_pred, f, proba)
|
|
183
|
+
else:
|
|
184
|
+
y_true = self.model.summation_layer_.y_
|
|
185
|
+
loss = self.loss_fn_(y_pred, y_true)
|
|
186
|
+
|
|
187
|
+
return float(loss) if np.isfinite(loss) else INVALID_OBJECTIVE
|
|
188
|
+
|
|
189
|
+
def _jac(self, theta, X, y, model, loo=True):
|
|
190
|
+
"""Compute the gradient of the objective function."""
|
|
191
|
+
theta = np.asarray(theta, dtype=np.float64)
|
|
192
|
+
if not self._theta_is_safe(theta):
|
|
193
|
+
return np.zeros_like(theta)
|
|
194
|
+
|
|
195
|
+
bandwidth = self._unpack_bandwidth(theta)
|
|
196
|
+
if not np.isfinite(bandwidth).all() or np.any(bandwidth <= 0):
|
|
197
|
+
return np.zeros_like(theta)
|
|
198
|
+
|
|
199
|
+
y_pred, f, proba = self._forward_state(bandwidth)
|
|
200
|
+
grad_bandwidth = np.asarray(
|
|
201
|
+
self.loss_fn_.grad(X, y, y_pred, model, loo=loo, bandwidth=bandwidth),
|
|
202
|
+
dtype=np.float64,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
# Optimization runs in theta = log(bandwidth), so apply
|
|
206
|
+
# dL/dtheta = dL/dbandwidth * dbandwidth/dtheta = dL/dbandwidth * bandwidth.
|
|
207
|
+
grad_theta = grad_bandwidth * np.asarray(bandwidth, dtype=np.float64)
|
|
208
|
+
return np.ravel(grad_theta)
|
|
209
|
+
|
|
210
|
+
def _objective_and_jac(self, theta):
|
|
211
|
+
"""Compute loss and gradient in one pass, sharing a single LOO kernel evaluation.
|
|
212
|
+
|
|
213
|
+
Returns (loss, grad_theta) as required by scipy when jac=True.
|
|
214
|
+
"""
|
|
215
|
+
theta = np.asarray(theta, dtype=np.float64)
|
|
216
|
+
if not self._theta_is_safe(theta):
|
|
217
|
+
return INVALID_OBJECTIVE, np.zeros_like(theta)
|
|
218
|
+
|
|
219
|
+
bandwidth = self._unpack_bandwidth(theta)
|
|
220
|
+
if not np.isfinite(bandwidth).all() or np.any(bandwidth <= 0):
|
|
221
|
+
return INVALID_OBJECTIVE, np.zeros_like(theta)
|
|
222
|
+
|
|
223
|
+
# Single _loo call shared by both the loss value and the gradient.
|
|
224
|
+
K = self.model.pattern_layer_._loo(bandwidth)
|
|
225
|
+
|
|
226
|
+
X = self.model.pattern_layer_.patterns_
|
|
227
|
+
if self._is_pnn_model():
|
|
228
|
+
f = self.model.summation_layer_.transform(K)
|
|
229
|
+
proba = self.model.output_layer_.posteriori(f)
|
|
230
|
+
y_pred = self.model.output_layer_.transform_encoded(f)
|
|
231
|
+
y_true = self.model.output_layer_.y_encoded_
|
|
232
|
+
y = self.model.y_
|
|
233
|
+
loss = self.loss_fn_(y_true, y_pred, f, proba)
|
|
234
|
+
else:
|
|
235
|
+
y_pred = self.model.summation_layer_.transform(K)
|
|
236
|
+
y = self.model.summation_layer_.y_
|
|
237
|
+
loss = self.loss_fn_(y_pred, y)
|
|
238
|
+
|
|
239
|
+
if not np.isfinite(loss):
|
|
240
|
+
return INVALID_OBJECTIVE, np.zeros_like(theta)
|
|
241
|
+
|
|
242
|
+
grad_bandwidth = np.asarray(
|
|
243
|
+
self.loss_fn_.grad(X, y, y_pred, self.model, loo=True, bandwidth=bandwidth, K=K),
|
|
244
|
+
dtype=np.float64,
|
|
245
|
+
)
|
|
246
|
+
grad_theta = grad_bandwidth * np.asarray(bandwidth, dtype=np.float64)
|
|
247
|
+
return float(loss), np.ravel(grad_theta)
|
|
248
|
+
|
|
249
|
+
def optimize(self):
|
|
250
|
+
"""Optimize bandwidths and store the best observed parameters."""
|
|
251
|
+
theta_min, theta_max = self._theta_limits()
|
|
252
|
+
theta0 = np.asarray(self._pack_bandwidth(), dtype=np.float64)
|
|
253
|
+
theta0 = np.clip(theta0, theta_min, theta_max)
|
|
254
|
+
|
|
255
|
+
uses_gradient = self.solver in GRADIENT_SOLVERS and hasattr(self.loss_fn_, "grad")
|
|
256
|
+
minimize_kwargs = {}
|
|
257
|
+
if self.solver in BOUNDED_SOLVERS:
|
|
258
|
+
minimize_kwargs["bounds"] = [(theta_min, theta_max)] * theta0.size
|
|
259
|
+
|
|
260
|
+
if uses_gradient:
|
|
261
|
+
result = minimize(
|
|
262
|
+
self._objective_and_jac,
|
|
263
|
+
theta0,
|
|
264
|
+
method=self.solver,
|
|
265
|
+
jac=True,
|
|
266
|
+
options={
|
|
267
|
+
"maxiter": self.max_iter,
|
|
268
|
+
**(self.solver_options or {}),
|
|
269
|
+
},
|
|
270
|
+
**minimize_kwargs,
|
|
271
|
+
)
|
|
272
|
+
else:
|
|
273
|
+
result = minimize(
|
|
274
|
+
self._objective,
|
|
275
|
+
theta0,
|
|
276
|
+
method=self.solver,
|
|
277
|
+
options={
|
|
278
|
+
"maxiter": self.max_iter,
|
|
279
|
+
**(self.solver_options or {}),
|
|
280
|
+
},
|
|
281
|
+
**minimize_kwargs,
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
bandwidth = cast_to_dtype(self._unpack_bandwidth(result.x), self._infer_dtype())
|
|
285
|
+
|
|
286
|
+
self.solver_ = self.solver
|
|
287
|
+
self.optimization_result_ = result
|
|
288
|
+
self.bandwidth_ = bandwidth
|
|
289
|
+
self.n_iter_ = getattr(result, "nit", None)
|
|
290
|
+
self.converged_ = bool(result.success)
|
|
291
|
+
|
|
292
|
+
self.model.pattern_layer_.bandwidth_ = self.bandwidth_
|
|
293
|
+
self.model.pattern_layer_.bandwidth_params = self.bandwidth_.copy()
|
|
294
|
+
self.model.pattern_layer_.converged_ = self.converged_
|
|
295
|
+
self.model.pattern_layer_.n_iter_ = self.n_iter_
|
|
296
|
+
|
|
297
|
+
if hasattr(self.model, "bandwidth_"):
|
|
298
|
+
self.model.bandwidth_ = self.bandwidth_
|
|
299
|
+
|
|
300
|
+
if not self.converged_:
|
|
301
|
+
diagnostic_fields = {
|
|
302
|
+
"solver": self.solver,
|
|
303
|
+
"status": getattr(result, "status", None),
|
|
304
|
+
"success": getattr(result, "success", None),
|
|
305
|
+
"message": getattr(result, "message", None),
|
|
306
|
+
"fun": getattr(result, "fun", None),
|
|
307
|
+
"nit": getattr(result, "nit", None),
|
|
308
|
+
"nfev": getattr(result, "nfev", None),
|
|
309
|
+
"njev": getattr(result, "njev", None),
|
|
310
|
+
"x": getattr(result, "x", None),
|
|
311
|
+
"theta0": theta0,
|
|
312
|
+
"bandwidth": bandwidth,
|
|
313
|
+
"max_iter": self.max_iter,
|
|
314
|
+
"solver_options": self.solver_options,
|
|
315
|
+
}
|
|
316
|
+
diagnostics = ", ".join(
|
|
317
|
+
f"{key}={value!r}" for key, value in diagnostic_fields.items()
|
|
318
|
+
)
|
|
319
|
+
warnings.warn(
|
|
320
|
+
f"Optimization did not converge. Diagnostics: {diagnostics}",
|
|
321
|
+
RuntimeWarning,
|
|
322
|
+
stacklevel=2,
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
return self
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def normalize_l2(X: np.ndarray) -> np.ndarray:
|
|
5
|
+
"""Normalize each sample to unit L2 norm."""
|
|
6
|
+
norms = np.linalg.norm(X, axis=1, keepdims=True)
|
|
7
|
+
norms = np.where(norms == 0.0, 1.0, norms)
|
|
8
|
+
return X / norms
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def cast_to_dtype(X: np.ndarray | np.generic | float | int, dtype: str):
|
|
12
|
+
"""Cast arrays or scalars to a specified floating dtype."""
|
|
13
|
+
|
|
14
|
+
if dtype == "auto":
|
|
15
|
+
arr = np.asarray(X)
|
|
16
|
+
|
|
17
|
+
if isinstance(arr, np.ndarray):
|
|
18
|
+
if arr.dtype == np.float32 or arr.dtype == np.float64:
|
|
19
|
+
if not arr.flags.c_contiguous:
|
|
20
|
+
arr = np.ascontiguousarray(arr)
|
|
21
|
+
return arr
|
|
22
|
+
|
|
23
|
+
arr = np.asarray(arr, dtype=np.float64)
|
|
24
|
+
if not arr.flags.c_contiguous:
|
|
25
|
+
arr = np.ascontiguousarray(arr)
|
|
26
|
+
return arr
|
|
27
|
+
|
|
28
|
+
return np.float64(arr)
|
|
29
|
+
|
|
30
|
+
if dtype == "float64":
|
|
31
|
+
target_dtype = np.float64
|
|
32
|
+
elif dtype == "float32":
|
|
33
|
+
target_dtype = np.float32
|
|
34
|
+
else:
|
|
35
|
+
raise ValueError(f"Invalid dtype={dtype!r}. Supported: 'float64', 'float32'.")
|
|
36
|
+
|
|
37
|
+
if isinstance(X, np.ndarray):
|
|
38
|
+
X = np.asarray(X, dtype=target_dtype)
|
|
39
|
+
if not X.flags.c_contiguous:
|
|
40
|
+
X = np.ascontiguousarray(X)
|
|
41
|
+
return X
|
|
42
|
+
|
|
43
|
+
if np.isscalar(X):
|
|
44
|
+
return target_dtype(X)
|
|
45
|
+
|
|
46
|
+
raise TypeError("cast_to_dtype supports numpy arrays and scalar numeric values.")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def as_bandwidth_array(bandwidth, dtype=None):
|
|
50
|
+
"""Return scalar bandwidths as scalars and vector bandwidths as arrays."""
|
|
51
|
+
arr = np.asarray(bandwidth, dtype=dtype)
|
|
52
|
+
if arr.ndim == 0:
|
|
53
|
+
return arr[()]
|
|
54
|
+
if not arr.flags.c_contiguous:
|
|
55
|
+
arr = np.ascontiguousarray(arr)
|
|
56
|
+
return arr
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_LOG_GRAD_BYTES_TARGET = 256 * 1024 * 1024 # 256 MB
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _log_grad_block_size(n_samples: int, n_patterns: int, n_features: int, itemsize: int = 8) -> int:
|
|
63
|
+
"""Row block size that keeps a (block, n_patterns, n_features) chunk under 256 MB."""
|
|
64
|
+
elements = max(1, _LOG_GRAD_BYTES_TARGET // (n_patterns * n_features * itemsize))
|
|
65
|
+
return min(elements, n_samples)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def pattern_block_size(
|
|
69
|
+
n_patterns: int,
|
|
70
|
+
n_features: int,
|
|
71
|
+
bandwidth_sharing: str,
|
|
72
|
+
) -> int:
|
|
73
|
+
if n_patterns <= 128:
|
|
74
|
+
return n_patterns
|
|
75
|
+
|
|
76
|
+
target_work = 65536
|
|
77
|
+
|
|
78
|
+
if bandwidth_sharing == "per_class_per_feature":
|
|
79
|
+
target_work //= 2
|
|
80
|
+
elif bandwidth_sharing == "scalar":
|
|
81
|
+
target_work *= 2
|
|
82
|
+
|
|
83
|
+
block = target_work // max(n_features, 1)
|
|
84
|
+
|
|
85
|
+
ladder = (64, 128, 256, 512, 1024)
|
|
86
|
+
block = max(64, min(block, 1024))
|
|
87
|
+
|
|
88
|
+
block = max(v for v in ladder if v <= block)
|
|
89
|
+
return min(block, n_patterns)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def validate_backend(backend):
|
|
93
|
+
if backend not in {"numpy", "numba"}:
|
|
94
|
+
raise ValueError(f"Unknown backend={backend!r}. Available: 'numpy', 'numba'.")
|
|
95
|
+
if backend == "numba":
|
|
96
|
+
try:
|
|
97
|
+
from probabilisticnn.numba_backend import pnn_jit_inference, grnn_jit_inference
|
|
98
|
+
except ImportError as exc:
|
|
99
|
+
raise ImportError(
|
|
100
|
+
"Numba backend is not available. Install it with "
|
|
101
|
+
"`pip install probabilisticnn[numba]`. "
|
|
102
|
+
f"Original import error: {exc}"
|
|
103
|
+
) from exc
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
from sklearn.base import BaseEstimator, TransformerMixin
|
|
2
|
+
from sklearn.utils.validation import check_is_fitted, validate_data
|
|
3
|
+
import numpy as np
|
|
4
|
+
from probabilisticnn.base.utils import normalize_l2
|
|
5
|
+
from probabilisticnn.base.utils import cast_to_dtype
|
|
6
|
+
from probabilisticnn.base.utils import as_bandwidth_array
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class PatternLayer(TransformerMixin, BaseEstimator):
|
|
10
|
+
"""Map input samples to kernel responses over the reference set."""
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
bandwidth: float = 0.5,
|
|
15
|
+
kernel="gaussian",
|
|
16
|
+
normalize: bool = True,
|
|
17
|
+
backend="numpy"
|
|
18
|
+
) -> None:
|
|
19
|
+
self.bandwidth = bandwidth
|
|
20
|
+
self.kernel = kernel
|
|
21
|
+
self.normalize = normalize
|
|
22
|
+
self.backend = backend
|
|
23
|
+
|
|
24
|
+
def fit(self, X, y=None):
|
|
25
|
+
from probabilisticnn.base.kernels import resolve_kernel
|
|
26
|
+
self.kernel_ = resolve_kernel(self.kernel)
|
|
27
|
+
|
|
28
|
+
self.bandwidth_ = as_bandwidth_array(self.bandwidth)
|
|
29
|
+
self.patterns_ = normalize_l2(X) if self.normalize else X
|
|
30
|
+
return self
|
|
31
|
+
|
|
32
|
+
def transform(self, X):
|
|
33
|
+
check_is_fitted(self, ["kernel_", "patterns_", "bandwidth_"])
|
|
34
|
+
X = validate_data(self, X, reset=False)
|
|
35
|
+
X_transformed = normalize_l2(X) if self.normalize else X.copy()
|
|
36
|
+
return self.kernel_(
|
|
37
|
+
X_transformed,
|
|
38
|
+
self.patterns_,
|
|
39
|
+
bandwidth=self.bandwidth_,
|
|
40
|
+
bandwidth_sharing="scalar",
|
|
41
|
+
normalized=self.normalize,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class AdaptivePatternLayer(TransformerMixin, BaseEstimator):
|
|
46
|
+
"""Map input samples to kernel responses with optimizable bandwidth parameters.
|
|
47
|
+
|
|
48
|
+
Bandwidth can be shared per feature, per class, or per class per feature.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
kernel,
|
|
54
|
+
bandwidth_sharing="per_feature",
|
|
55
|
+
normalize=True,
|
|
56
|
+
backend="numpy",
|
|
57
|
+
compute_dtype="auto",
|
|
58
|
+
) -> None:
|
|
59
|
+
self.bandwidth_sharing = bandwidth_sharing
|
|
60
|
+
self.kernel = kernel
|
|
61
|
+
self.normalize = normalize
|
|
62
|
+
self.backend = backend
|
|
63
|
+
self.compute_dtype = compute_dtype
|
|
64
|
+
|
|
65
|
+
def fit(self, X, y=None):
|
|
66
|
+
X = validate_data(self, X)
|
|
67
|
+
|
|
68
|
+
from probabilisticnn.base.kernels import resolve_kernel
|
|
69
|
+
self.kernel_ = resolve_kernel(self.kernel)
|
|
70
|
+
|
|
71
|
+
if self.normalize:
|
|
72
|
+
self.patterns_ = normalize_l2(X)
|
|
73
|
+
else:
|
|
74
|
+
self.patterns_ = X
|
|
75
|
+
|
|
76
|
+
self.feature_size = X.shape[1]
|
|
77
|
+
|
|
78
|
+
# initialize bandwidth from data std to give optimizer a sensible starting point
|
|
79
|
+
if self.bandwidth_sharing == "per_feature":
|
|
80
|
+
std = cast_to_dtype(np.std(self.patterns_, axis=0), self.compute_dtype) + 1e-12
|
|
81
|
+
self.bandwidth_params = std
|
|
82
|
+
elif self.bandwidth_sharing == "per_class":
|
|
83
|
+
if y is None:
|
|
84
|
+
raise ValueError("`y` is required when bandwidth_sharing='per_class'.")
|
|
85
|
+
y = np.asarray(y)
|
|
86
|
+
if y.ndim != 1:
|
|
87
|
+
y = y.ravel()
|
|
88
|
+
if y.shape[0] != self.patterns_.shape[0]:
|
|
89
|
+
raise ValueError("`y` must have the same number of samples as `X`.")
|
|
90
|
+
self.classes_, self.y_encoded_ = np.unique(y, return_inverse=True)
|
|
91
|
+
self.n_classes_ = len(self.classes_)
|
|
92
|
+
|
|
93
|
+
self.bandwidth_params = cast_to_dtype(np.zeros(self.n_classes_), self.compute_dtype)
|
|
94
|
+
for cl in np.unique(self.y_encoded_):
|
|
95
|
+
self.bandwidth_params[cl] = (
|
|
96
|
+
cast_to_dtype(
|
|
97
|
+
np.std(
|
|
98
|
+
self.patterns_[self.y_encoded_ == cl],
|
|
99
|
+
axis=0,
|
|
100
|
+
).mean(),
|
|
101
|
+
self.compute_dtype,
|
|
102
|
+
)
|
|
103
|
+
+ 1e-12
|
|
104
|
+
)
|
|
105
|
+
elif self.bandwidth_sharing == "per_class_per_feature":
|
|
106
|
+
if y is None:
|
|
107
|
+
raise ValueError("`y` is required when bandwidth_sharing='per_class_per_feature'.")
|
|
108
|
+
y = np.asarray(y)
|
|
109
|
+
if y.ndim != 1:
|
|
110
|
+
y = y.ravel()
|
|
111
|
+
if y.shape[0] != self.patterns_.shape[0]:
|
|
112
|
+
raise ValueError("`y` must have the same number of samples as `X`.")
|
|
113
|
+
self.classes_, self.y_encoded_ = np.unique(y, return_inverse=True)
|
|
114
|
+
self.n_classes_ = len(self.classes_)
|
|
115
|
+
|
|
116
|
+
self.bandwidth_params = cast_to_dtype(
|
|
117
|
+
np.zeros((self.n_classes_, self.feature_size)),
|
|
118
|
+
self.compute_dtype,
|
|
119
|
+
)
|
|
120
|
+
for cl in np.unique(self.y_encoded_):
|
|
121
|
+
self.bandwidth_params[cl] = (
|
|
122
|
+
cast_to_dtype(
|
|
123
|
+
np.std(
|
|
124
|
+
self.patterns_[self.y_encoded_ == cl],
|
|
125
|
+
axis=0,
|
|
126
|
+
),
|
|
127
|
+
self.compute_dtype,
|
|
128
|
+
) + 1e-12
|
|
129
|
+
)
|
|
130
|
+
else:
|
|
131
|
+
raise ValueError(f"Unknown bandwidth_sharing={self.bandwidth_sharing}")
|
|
132
|
+
return self
|
|
133
|
+
|
|
134
|
+
def __broadcast_bandwidth(self, bandwidth_vector):
|
|
135
|
+
"""Expand class-level bandwidth to pattern-level by indexing with y_encoded_."""
|
|
136
|
+
if self.bandwidth_sharing == "per_feature":
|
|
137
|
+
return bandwidth_vector
|
|
138
|
+
elif self.bandwidth_sharing == "per_class":
|
|
139
|
+
return bandwidth_vector[self.y_encoded_] # (n_classes,) → (n_patterns,)
|
|
140
|
+
elif self.bandwidth_sharing == "per_class_per_feature":
|
|
141
|
+
return bandwidth_vector[self.y_encoded_] # (n_classes, n_features) → (n_patterns, n_features)
|
|
142
|
+
else:
|
|
143
|
+
raise ValueError(f"Unknown bandwidth_sharing={self.bandwidth_sharing}")
|
|
144
|
+
|
|
145
|
+
def _prepare_bandwidth(self, bandwidth):
|
|
146
|
+
"""Normalize raw bandwidth parameters to the kernel-ready shape.
|
|
147
|
+
|
|
148
|
+
Приводит параметры ширины к форме, которую ожидает kernel-функция.
|
|
149
|
+
"""
|
|
150
|
+
bandwidth = cast_to_dtype(np.asarray(bandwidth), self.compute_dtype)
|
|
151
|
+
n_patterns = self.patterns_.shape[0]
|
|
152
|
+
|
|
153
|
+
if self.bandwidth_sharing == "per_feature":
|
|
154
|
+
expected_shape = (self.feature_size,)
|
|
155
|
+
if bandwidth.shape != expected_shape:
|
|
156
|
+
raise ValueError(
|
|
157
|
+
f"Invalid bandwidth shape for 'per_feature': expected {expected_shape}, got {bandwidth.shape}."
|
|
158
|
+
)
|
|
159
|
+
return bandwidth
|
|
160
|
+
|
|
161
|
+
if self.bandwidth_sharing == "per_class":
|
|
162
|
+
raw_shape = (self.n_classes_,)
|
|
163
|
+
broadcast_shape = (n_patterns, 1)
|
|
164
|
+
if bandwidth.shape == raw_shape:
|
|
165
|
+
return self.__broadcast_bandwidth(bandwidth)
|
|
166
|
+
if bandwidth.shape == broadcast_shape:
|
|
167
|
+
return bandwidth
|
|
168
|
+
raise ValueError(
|
|
169
|
+
f"Invalid bandwidth shape for 'per_class': expected {raw_shape} or {broadcast_shape}, got {bandwidth.shape}."
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
if self.bandwidth_sharing == "per_class_per_feature":
|
|
173
|
+
raw_shape = (self.n_classes_, self.feature_size)
|
|
174
|
+
broadcast_shape = (n_patterns, self.feature_size)
|
|
175
|
+
if bandwidth.shape == raw_shape:
|
|
176
|
+
return self.__broadcast_bandwidth(bandwidth)
|
|
177
|
+
if bandwidth.shape == broadcast_shape:
|
|
178
|
+
return bandwidth
|
|
179
|
+
raise ValueError(
|
|
180
|
+
"Invalid bandwidth shape for 'per_class_per_feature': "
|
|
181
|
+
f"expected {raw_shape} or {broadcast_shape}, got {bandwidth.shape}."
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
raise ValueError(f"Unknown bandwidth_sharing={self.bandwidth_sharing}")
|
|
185
|
+
|
|
186
|
+
def _loo(self, bandwidth=None):
|
|
187
|
+
"""Return the kernel matrix for Leave-One-Out: K computed on training patterns with diagonal zeroed."""
|
|
188
|
+
if bandwidth is None:
|
|
189
|
+
bandwidth = self.bandwidth_params
|
|
190
|
+
bandwidth = self._prepare_bandwidth(bandwidth)
|
|
191
|
+
K = self.kernel_(
|
|
192
|
+
self.patterns_,
|
|
193
|
+
self.patterns_,
|
|
194
|
+
bandwidth=bandwidth,
|
|
195
|
+
bandwidth_sharing=self.bandwidth_sharing,
|
|
196
|
+
normalized=self.normalize,
|
|
197
|
+
)
|
|
198
|
+
np.fill_diagonal(K, 0.0)
|
|
199
|
+
return K
|
|
200
|
+
|
|
201
|
+
def transform(self, X):
|
|
202
|
+
check_is_fitted(self, ["kernel_", "patterns_", "converged_", "bandwidth_"])
|
|
203
|
+
X = validate_data(self, X, reset=False)
|
|
204
|
+
if self.normalize:
|
|
205
|
+
X_transformed = normalize_l2(X)
|
|
206
|
+
else:
|
|
207
|
+
X_transformed = X
|
|
208
|
+
bandwidth = self._prepare_bandwidth(self.bandwidth_)
|
|
209
|
+
return self.kernel_(
|
|
210
|
+
X_transformed,
|
|
211
|
+
self.patterns_,
|
|
212
|
+
bandwidth=bandwidth,
|
|
213
|
+
bandwidth_sharing=self.bandwidth_sharing,
|
|
214
|
+
normalized=self.normalize,
|
|
215
|
+
)
|