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.
@@ -0,0 +1,444 @@
1
+ import numpy as np
2
+
3
+
4
+ def log_likelihood_ratio_loss(y_true, y_pred, f, proba=None, eps=1e-8):
5
+ """Minimize the negative true-vs-competitor log likelihood ratio."""
6
+ y_true = np.asarray(y_true, dtype=np.intp)
7
+
8
+ if f.shape[1] < 2:
9
+ return float(f.sum() * 0.0)
10
+
11
+ idx = np.arange(f.shape[0], dtype=np.intp)
12
+ f_true = f[idx, y_true]
13
+
14
+ competitors = f.copy()
15
+ competitors[idx, y_true] = -np.inf
16
+ f_competitor = np.max(competitors, axis=1)
17
+ log_lr = np.log(f_true + eps) - np.log(f_competitor + eps)
18
+ return float(-np.mean(log_lr))
19
+
20
+
21
+ def correct_class_probability_loss(y_true, y_pred, f, proba, eps=1e-8):
22
+ """Maximize the posterior probability assigned to the correct class."""
23
+ y_true = np.asarray(y_true, dtype=np.intp)
24
+ idx = np.arange(proba.shape[0], dtype=np.intp)
25
+ return float(-np.mean(proba[idx, y_true]))
26
+
27
+
28
+ def _chunked_grad_contract(
29
+ coef,
30
+ X_for_grad,
31
+ W,
32
+ bw_for_kernel,
33
+ kernel,
34
+ bandwidth_sharing,
35
+ normalized,
36
+ pattern_classes,
37
+ n_classes,
38
+ ):
39
+ """Contract coef with log_kernel_grad in row chunks.
40
+
41
+ Avoids materialising a full (n_samples, n_patterns, n_features) tensor for
42
+ per_feature and per_class_per_feature sharing modes. Peak allocation is
43
+ (block, n_patterns, n_features) where block is chosen to stay under 256 MB.
44
+ """
45
+ from probabilisticnn.base.utils import _log_grad_block_size
46
+
47
+ n_samples, n_patterns = coef.shape
48
+ n_features = X_for_grad.shape[1]
49
+ block = _log_grad_block_size(n_samples, n_patterns, n_features, itemsize=8)
50
+ coef_f64 = np.asarray(coef, dtype=np.float64)
51
+
52
+ if bandwidth_sharing == "per_feature":
53
+ grad = np.zeros(n_features, dtype=np.float64)
54
+ for start in range(0, n_samples, block):
55
+ end = min(start + block, n_samples)
56
+ lg = np.asarray(
57
+ kernel.log_grad(
58
+ X_for_grad[start:end],
59
+ W,
60
+ bandwidth=bw_for_kernel,
61
+ bandwidth_sharing=bandwidth_sharing,
62
+ normalized=normalized,
63
+ ),
64
+ dtype=np.float64,
65
+ )
66
+ grad += np.einsum("ij,ijd->d", coef_f64[start:end], lg)
67
+ return grad
68
+
69
+ # per_class_per_feature
70
+ per_pattern_feature_grad = np.zeros((n_patterns, n_features), dtype=np.float64)
71
+ for start in range(0, n_samples, block):
72
+ end = min(start + block, n_samples)
73
+ lg = np.asarray(
74
+ kernel.log_grad(
75
+ X_for_grad[start:end],
76
+ W,
77
+ bandwidth=bw_for_kernel,
78
+ bandwidth_sharing=bandwidth_sharing,
79
+ normalized=normalized,
80
+ ),
81
+ dtype=np.float64,
82
+ )
83
+ per_pattern_feature_grad += np.einsum("ij,ijd->jd", coef_f64[start:end], lg)
84
+ grad = np.zeros((n_classes, n_features), dtype=np.float64)
85
+ np.add.at(grad, pattern_classes, per_pattern_feature_grad)
86
+ return grad
87
+
88
+
89
+ class BCELoss:
90
+ def __call__(self, y_true, y_pred, f, proba, eps=1e-8):
91
+ """Binary or multiclass BCE over posterior probabilities."""
92
+ proba = np.clip(np.asarray(proba, dtype=proba.dtype), eps, 1.0 - eps)
93
+ y_true = np.asarray(y_true)
94
+
95
+ if proba.shape[1] == 1:
96
+ bce_input = proba[:, 0]
97
+ bce_target = y_true.astype(bce_input.dtype, copy=False)
98
+ elif proba.shape[1] == 2:
99
+ bce_input = proba[:, 1]
100
+ bce_target = y_true.astype(bce_input.dtype, copy=False)
101
+ else:
102
+ bce_input = proba
103
+ bce_target = np.eye(proba.shape[1], dtype=bce_input.dtype)[y_true.astype(np.intp)]
104
+
105
+ loss = -(bce_target * np.log(bce_input) + (1.0 - bce_target) * np.log(1.0 - bce_input))
106
+ return float(np.mean(loss))
107
+
108
+ def grad(self, X, y, y_pred, model, loo=True, bandwidth=None, K=None, eps=1e-8):
109
+ if K is not None:
110
+ X_for_grad = model.pattern_layer_.patterns_
111
+ elif loo:
112
+ X_for_grad = model.pattern_layer_.patterns_
113
+ K = model.pattern_layer_._loo(bandwidth)
114
+ else:
115
+ X_for_grad = X
116
+ K = model.pattern_layer_.transform(X)
117
+ f = model.summation_layer_.transform(K)
118
+ n_samples, n_classes = f.shape
119
+ idx = np.arange(n_samples, dtype=np.intp)
120
+
121
+ _, y_encoded = np.unique(y, return_inverse=True)
122
+ priors = model.output_layer_.prior_
123
+
124
+ evidence = f * priors[None, :]
125
+ evidence_sum = evidence.sum(axis=1, keepdims=True)
126
+ evidence_sum = np.maximum(evidence_sum, eps)
127
+
128
+ proba = evidence / evidence_sum
129
+ proba = np.clip(proba, eps, 1.0 - eps)
130
+
131
+ H = np.zeros_like(proba, dtype=proba.dtype)
132
+ if proba.shape[1] == 1:
133
+ target = y.astype(proba.dtype, copy=False)
134
+ p = proba[:, 0]
135
+ H[:, 0] = (p - target) / (n_samples * p * (1.0 - p))
136
+ elif proba.shape[1] == 2:
137
+ target = y_encoded.astype(proba.dtype, copy=False)
138
+ p = proba[:, 1]
139
+ H[:, 1] = (p - target) / (n_samples * p * (1.0 - p))
140
+ else:
141
+ target = np.eye(proba.shape[1], dtype=proba.dtype)[y_encoded]
142
+ H = (
143
+ -(target / proba)
144
+ + (1.0 - target) / (1.0 - proba)
145
+ ) / (n_samples * proba.shape[1])
146
+
147
+ weighted_H = np.sum(H * proba, axis=1, keepdims=True)
148
+
149
+ G = (
150
+ priors[None, :]
151
+ / evidence_sum
152
+ * (H - weighted_H)
153
+ )
154
+
155
+ pattern_classes = np.asarray(
156
+ model.summation_layer_.y_encoded_,
157
+ dtype=np.intp,
158
+ )
159
+
160
+ coef = K * G[:, pattern_classes]
161
+
162
+ if loo:
163
+ if K.shape[0] != K.shape[1]:
164
+ raise ValueError("LOO gradient expects square K: n_samples == n_patterns.")
165
+
166
+ diag = np.arange(K.shape[0])
167
+ coef[diag, diag] = 0.0
168
+
169
+ bw = bandwidth if bandwidth is not None else model.pattern_layer_.bandwidth_
170
+ if hasattr(model.pattern_layer_, "_prepare_bandwidth"):
171
+ bw_for_kernel = model.pattern_layer_._prepare_bandwidth(bw)
172
+ else:
173
+ bw_for_kernel = bw
174
+
175
+ bandwidth_sharing = model.pattern_layer_.bandwidth_sharing
176
+ if bandwidth_sharing in ("per_feature", "per_class_per_feature"):
177
+ return _chunked_grad_contract(
178
+ coef=coef,
179
+ X_for_grad=X_for_grad,
180
+ W=model.pattern_layer_.patterns_,
181
+ bw_for_kernel=bw_for_kernel,
182
+ kernel=model.pattern_layer_.kernel_,
183
+ bandwidth_sharing=bandwidth_sharing,
184
+ normalized=model.pattern_layer_.normalize,
185
+ pattern_classes=pattern_classes,
186
+ n_classes=n_classes,
187
+ )
188
+
189
+ log_kernel_grad = model.pattern_layer_.kernel_.log_grad(
190
+ X_for_grad,
191
+ model.pattern_layer_.patterns_,
192
+ bandwidth=bw_for_kernel,
193
+ bandwidth_sharing=bandwidth_sharing,
194
+ normalized=model.pattern_layer_.normalize,
195
+ )
196
+ return self._contract_log_kernel_grad(
197
+ coef=coef,
198
+ log_kernel_grad=log_kernel_grad,
199
+ bandwidth_sharing=bandwidth_sharing,
200
+ pattern_classes=pattern_classes,
201
+ n_classes=n_classes,
202
+ )
203
+
204
+ def _contract_log_kernel_grad(
205
+ self,
206
+ coef,
207
+ log_kernel_grad,
208
+ bandwidth_sharing,
209
+ pattern_classes,
210
+ n_classes,
211
+ ):
212
+ # coef: (n_samples, n_patterns)
213
+ # log_kernel_grad: (n_samples, n_patterns) for scalar/per_class,
214
+ # (n_samples, n_patterns, n_features) for per_feature/per_class_per_feature
215
+ if bandwidth_sharing == "scalar":
216
+ return np.sum(coef * log_kernel_grad)
217
+
218
+ if bandwidth_sharing == "per_feature":
219
+ return np.einsum("ij,ijd->d", coef, log_kernel_grad)
220
+
221
+ if bandwidth_sharing == "per_class":
222
+ per_pattern_grad = np.sum(coef * log_kernel_grad, axis=0)
223
+ grad = np.zeros(n_classes, coef.dtype)
224
+ np.add.at(grad, pattern_classes, per_pattern_grad)
225
+ return grad
226
+
227
+ if bandwidth_sharing == "per_class_per_feature":
228
+ per_pattern_feature_grad = np.einsum("ij,ijd->jd", coef, log_kernel_grad)
229
+ n_features = per_pattern_feature_grad.shape[1]
230
+ grad = np.zeros((n_classes, n_features), dtype=coef.dtype)
231
+ np.add.at(grad, pattern_classes, per_pattern_feature_grad)
232
+ return grad
233
+
234
+ raise ValueError(f"Unknown bandwidth_sharing={bandwidth_sharing!r}.")
235
+
236
+
237
+ class CrossEntropyLoss:
238
+ def __call__(self, y_true, y_pred, f, proba, eps=1e-8):
239
+ """Cross entropy over posterior probabilities."""
240
+ proba = np.clip(np.asarray(proba, dtype=proba.dtype), eps, 1.0 - eps)
241
+ y_true = np.asarray(y_true, dtype=np.intp)
242
+ idx = np.arange(proba.shape[0], dtype=np.intp)
243
+ return float(-np.mean(np.log(proba[idx, y_true])))
244
+
245
+ def grad(self, X, y, y_pred, model, loo=True, bandwidth=None, K=None, eps=1e-8):
246
+ """Gradient of the cross entropy loss."""
247
+ if K is not None:
248
+ X_for_grad = model.pattern_layer_.patterns_
249
+ elif loo:
250
+ X_for_grad = model.pattern_layer_.patterns_
251
+ K = model.pattern_layer_._loo(bandwidth)
252
+ else:
253
+ X_for_grad = X
254
+ K = model.pattern_layer_.transform(X)
255
+
256
+ f = model.summation_layer_.transform(K)
257
+
258
+ n_samples = f.shape[0]
259
+ idx = np.arange(n_samples, dtype=np.intp)
260
+
261
+ _, y_encoded = np.unique(y, return_inverse=True)
262
+
263
+ priors = model.output_layer_.prior_
264
+ if priors.ndim == 0:
265
+ priors = np.full(f.shape[1], float(priors), priors.dtype)
266
+
267
+ evidence = f * priors[None, :]
268
+ evidence_sum = evidence.sum(axis=1)
269
+ evidence_sum = np.maximum(evidence_sum, eps)
270
+
271
+ f_true = f[idx, y_encoded]
272
+ f_true = np.maximum(f_true, eps)
273
+ G = priors[None, :] / evidence_sum[:, None]
274
+ G[idx, y_encoded] -= 1.0 / f_true
275
+ G /= n_samples
276
+ pattern_classes = np.asarray(
277
+ model.summation_layer_.y_encoded_,
278
+ dtype=np.intp,
279
+ )
280
+
281
+ coef = K * G[:, pattern_classes]
282
+ if loo:
283
+ if K.shape[0] != K.shape[1]:
284
+ raise ValueError("LOO gradient expects square K: n_samples == n_patterns.")
285
+
286
+ diag = np.arange(K.shape[0])
287
+ coef[diag, diag] = 0.0
288
+
289
+ bw = bandwidth if bandwidth is not None else model.pattern_layer_.bandwidth_
290
+ if hasattr(model.pattern_layer_, "_prepare_bandwidth"):
291
+ bw_for_kernel = model.pattern_layer_._prepare_bandwidth(bw)
292
+ else:
293
+ bw_for_kernel = bw
294
+
295
+ bandwidth_sharing = model.pattern_layer_.bandwidth_sharing
296
+ if bandwidth_sharing in ("per_feature", "per_class_per_feature"):
297
+ return _chunked_grad_contract(
298
+ coef=coef,
299
+ X_for_grad=X_for_grad,
300
+ W=model.pattern_layer_.patterns_,
301
+ bw_for_kernel=bw_for_kernel,
302
+ kernel=model.pattern_layer_.kernel_,
303
+ bandwidth_sharing=bandwidth_sharing,
304
+ normalized=model.pattern_layer_.normalize,
305
+ pattern_classes=pattern_classes,
306
+ n_classes=f.shape[1],
307
+ )
308
+
309
+ log_kernel_grad = model.pattern_layer_.kernel_.log_grad(
310
+ X_for_grad,
311
+ model.pattern_layer_.patterns_,
312
+ bandwidth=bw_for_kernel,
313
+ bandwidth_sharing=bandwidth_sharing,
314
+ normalized=model.pattern_layer_.normalize,
315
+ )
316
+ return self._contract_log_kernel_grad(
317
+ coef=coef,
318
+ log_kernel_grad=log_kernel_grad,
319
+ bandwidth_sharing=bandwidth_sharing,
320
+ pattern_classes=pattern_classes,
321
+ n_classes=f.shape[1],
322
+ )
323
+
324
+ def _contract_log_kernel_grad(
325
+ self,
326
+ coef,
327
+ log_kernel_grad,
328
+ bandwidth_sharing,
329
+ pattern_classes,
330
+ n_classes,
331
+ ):
332
+ # coef: (n_samples, n_patterns)
333
+ # log_kernel_grad: (n_samples, n_patterns) for scalar/per_class,
334
+ # (n_samples, n_patterns, n_features) for per_feature/per_class_per_feature
335
+ if bandwidth_sharing == "scalar":
336
+ return np.sum(coef * log_kernel_grad)
337
+
338
+ if bandwidth_sharing == "per_feature":
339
+ return np.einsum("ij,ijd->d", coef, log_kernel_grad)
340
+
341
+ if bandwidth_sharing == "per_class":
342
+ per_pattern_grad = np.sum(coef * log_kernel_grad, axis=0)
343
+ grad = np.zeros(n_classes, dtype=coef.dtype)
344
+ np.add.at(grad, pattern_classes, per_pattern_grad)
345
+ return grad
346
+
347
+ if bandwidth_sharing == "per_class_per_feature":
348
+ per_pattern_feature_grad = np.einsum("ij,ijd->jd", coef, log_kernel_grad)
349
+ n_features = per_pattern_feature_grad.shape[1]
350
+ grad = np.zeros((n_classes, n_features), dtype=coef.dtype)
351
+ np.add.at(grad, pattern_classes, per_pattern_feature_grad)
352
+ return grad
353
+
354
+ raise ValueError(f"Unknown bandwidth_sharing={bandwidth_sharing!r}.")
355
+
356
+
357
+ class MSELoss:
358
+
359
+ def __call__(self, y_pred, y_true):
360
+ """Mean squared error."""
361
+ y_pred = np.asarray(y_pred)
362
+ y_true = np.asarray(y_true)
363
+ return float(np.mean(np.square(y_pred - y_true)))
364
+
365
+ def grad(self, X, y, y_pred, model, loo=True, bandwidth=None, K=None):
366
+ """Gradient of the MSE loss."""
367
+ model_grad = model.grad(X, y, bandwidth=bandwidth, loo=loo, K=K)
368
+ upstream = 2.0 * (y_pred - y) / X.shape[0]
369
+ grad_loss = upstream @ model_grad
370
+ return grad_loss
371
+
372
+
373
+ class HuberLoss:
374
+ def __init__(self, delta=1.0):
375
+ self.delta = float(delta)
376
+
377
+ def __call__(self, y_pred, y_true):
378
+ """Huber loss."""
379
+ y_pred = np.asarray(y_pred)
380
+ y_true = np.asarray(y_true)
381
+ error = y_pred - y_true
382
+ abs_error = np.abs(error)
383
+
384
+ quadratic = 0.5 * np.square(error)
385
+ linear = self.delta * (abs_error - 0.5 * self.delta)
386
+ loss = np.where(abs_error <= self.delta, quadratic, linear)
387
+ return float(np.mean(loss))
388
+
389
+ def grad(self, X, y, y_pred, model, loo=True, bandwidth=None, K=None):
390
+ """Gradient of the Huber loss."""
391
+ model_grad = model.grad(X, y, bandwidth=bandwidth, loo=loo, K=K)
392
+ error = np.asarray(y_pred) - np.asarray(y)
393
+ upstream = np.where(
394
+ np.abs(error) <= self.delta,
395
+ error,
396
+ self.delta * np.sign(error),
397
+ ) / X.shape[0]
398
+ grad_loss = upstream @ model_grad
399
+ return grad_loss
400
+
401
+
402
+ class MAELoss:
403
+ def __call__(self, y_pred, y_true):
404
+ """Mean absolute error."""
405
+ y_pred = np.asarray(y_pred)
406
+ y_true = np.asarray(y_true)
407
+ return float(np.mean(np.abs(y_pred - y_true)))
408
+
409
+
410
+ PNN_LOSS_REGISTRY = {
411
+ "log_likelihood_ratio": log_likelihood_ratio_loss,
412
+ "correct_class_probability": correct_class_probability_loss,
413
+ "bce": BCELoss(),
414
+ "cross_entropy": CrossEntropyLoss(),
415
+ }
416
+
417
+ GRNN_LOSS_REGISTRY = {
418
+ "mse": MSELoss(),
419
+ "mae": MAELoss(),
420
+ "huber": HuberLoss(),
421
+ }
422
+
423
+
424
+ def _resolve_loss(loss: str, model):
425
+ """Resolve a string loss name into a callable loss function."""
426
+ from probabilisticnn.pnn.pnn import PNN
427
+ from probabilisticnn.grnn.grnn import GRNN
428
+
429
+ if isinstance(model, PNN):
430
+ if callable(loss):
431
+ return loss
432
+ try:
433
+ return PNN_LOSS_REGISTRY[loss.lower()]
434
+ except KeyError as exc:
435
+ available = ", ".join(sorted(PNN_LOSS_REGISTRY))
436
+ raise ValueError(f"Unknown loss={loss!r}. Available: {available}") from exc
437
+ if isinstance(model, GRNN):
438
+ if callable(loss):
439
+ return loss
440
+ try:
441
+ return GRNN_LOSS_REGISTRY[loss.lower()]
442
+ except KeyError as exc:
443
+ available = ", ".join(sorted(GRNN_LOSS_REGISTRY))
444
+ raise ValueError(f"Unknown loss={loss!r}. Available: {available}") from exc