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.
File without changes
@@ -0,0 +1,35 @@
1
+ """Base utilities, kernels, and optimization helpers."""
2
+
3
+ __all__ = [
4
+ "BandwidthOptimizer",
5
+ "KERNEL_REGISTRY",
6
+ "KernelCallable",
7
+ "normalize_l2",
8
+ ]
9
+
10
+
11
+ def __getattr__(name):
12
+ if name in {"KERNEL_REGISTRY"}:
13
+ from probabilisticnn.base.kernels import KERNEL_REGISTRY
14
+
15
+ exports = {
16
+ "KERNEL_REGISTRY": KERNEL_REGISTRY,
17
+ }
18
+ return exports[name]
19
+
20
+ if name == "BandwidthOptimizer":
21
+ from probabilisticnn.base.optim import BandwidthOptimizer
22
+
23
+ return BandwidthOptimizer
24
+
25
+ if name == "KernelCallable":
26
+ from probabilisticnn.base.types import KernelCallable
27
+
28
+ return KernelCallable
29
+
30
+ if name == "normalize_l2":
31
+ from probabilisticnn.base.utils import normalize_l2
32
+
33
+ return normalize_l2
34
+
35
+ raise AttributeError(f"module 'probabilisticnn.base' has no attribute {name!r}")
@@ -0,0 +1,370 @@
1
+ import math
2
+
3
+ import numpy as np
4
+ from probabilisticnn.base.types import KernelCallable
5
+
6
+
7
+ def _validate_bandwidth_numpy(bandwidth) -> None:
8
+ if np.any(bandwidth <= 0):
9
+ raise ValueError("`bandwidth` must be strictly positive.")
10
+
11
+
12
+ def _exp_from_scaled_distance(scaled_distance):
13
+ """Exponentiate a theoretically non-negative scaled distance safely."""
14
+ scaled_distance = np.asarray(scaled_distance)
15
+ scaled_distance = np.maximum(scaled_distance, scaled_distance.dtype.type(0))
16
+ return np.exp(-scaled_distance)
17
+
18
+
19
+ def _gaussian_normalization_constant(bandwidth, n_features: int, bandwidth_sharing: str):
20
+ dtype = np.asarray(bandwidth).dtype
21
+ base_constant = dtype.type(np.power(2.0 * math.pi, -0.5 * n_features))
22
+ if bandwidth_sharing == "per_class":
23
+ return np.asarray(base_constant * np.power(bandwidth, -n_features), dtype=dtype)
24
+ if bandwidth_sharing == "per_class_per_feature":
25
+ return np.asarray(base_constant / np.prod(bandwidth, axis=1), dtype=dtype)
26
+ raise ValueError(f"Unsupported bandwidth_sharing={bandwidth_sharing!r}.")
27
+
28
+
29
+ def _laplacian_normalization_constant(bandwidth, n_features: int, bandwidth_sharing: str):
30
+ dtype = np.asarray(bandwidth).dtype
31
+ base_constant = dtype.type(np.power(2.0, -n_features))
32
+ if bandwidth_sharing == "per_class":
33
+ return np.asarray(base_constant * np.power(bandwidth, -n_features), dtype=dtype)
34
+ if bandwidth_sharing == "per_class_per_feature":
35
+ return np.asarray(base_constant / np.prod(bandwidth, axis=1), dtype=dtype)
36
+ raise ValueError(f"Unsupported bandwidth_sharing={bandwidth_sharing!r}.")
37
+
38
+
39
+ def _exponential_normalization_constant(bandwidth, n_features: int, bandwidth_sharing: str):
40
+ dtype = np.asarray(bandwidth).dtype
41
+ base_constant = math.gamma(0.5 * n_features) / (
42
+ 2.0 * np.power(math.pi, 0.5 * n_features) * math.gamma(n_features)
43
+ )
44
+ base_constant = dtype.type(base_constant)
45
+ if bandwidth_sharing == "per_class":
46
+ return np.asarray(base_constant * np.power(bandwidth, -n_features), dtype=dtype)
47
+ if bandwidth_sharing == "per_class_per_feature":
48
+ return np.asarray(base_constant / np.prod(bandwidth, axis=1), dtype=dtype)
49
+ raise ValueError(f"Unsupported bandwidth_sharing={bandwidth_sharing!r}.")
50
+
51
+
52
+ class GaussianKernel:
53
+ def __call__(
54
+ self,
55
+ X: np.ndarray,
56
+ W: np.ndarray,
57
+ bandwidth, # np.float or array-like with shape (n_features,), (n_patterns,) or (n_patterns, n_features)
58
+ bandwidth_sharing: str,
59
+ normalized: bool = False,
60
+ ) -> np.ndarray:
61
+ """Compute Gaussian kernel values between samples in X and W."""
62
+ _validate_bandwidth_numpy(bandwidth)
63
+
64
+ if bandwidth_sharing == "scalar":
65
+ bandwidth_sq = bandwidth * bandwidth
66
+ if normalized:
67
+ similarities = np.dot(X, W.T)
68
+ scaled_distance = (1.0 - similarities) / bandwidth_sq
69
+ return _exp_from_scaled_distance(scaled_distance)
70
+
71
+ x_norm_sq = np.square(X).sum(axis=1, keepdims=True)
72
+ w_norm_sq = np.square(W).sum(axis=1)
73
+ l2_norm_sq = x_norm_sq + w_norm_sq - 2.0 * np.dot(X, W.T)
74
+ scaled_distance = l2_norm_sq / (2.0 * bandwidth_sq)
75
+ return _exp_from_scaled_distance(scaled_distance)
76
+
77
+ elif bandwidth_sharing == "per_feature":
78
+ bandwidth_sq = np.square(bandwidth)
79
+ bandw_inv = 1.0 / (2.0 * bandwidth_sq)
80
+ x_norm_sq = (np.square(X) * bandw_inv).sum(axis=1, keepdims=True)
81
+ w_norm_sq = (np.square(W) * bandw_inv).sum(axis=1)
82
+ scaled_distance = x_norm_sq + w_norm_sq - 2.0 * np.dot(X, (W * bandw_inv).T)
83
+ return _exp_from_scaled_distance(scaled_distance)
84
+
85
+ elif bandwidth_sharing == "per_class":
86
+ bandwidth_sq = np.square(bandwidth)
87
+ bandw_inv = 1.0 / (2.0 * bandwidth_sq)
88
+ x_norm_sq = np.square(X).sum(axis=1, keepdims=True)
89
+ w_norm_sq = np.square(W).sum(axis=1)
90
+ scaled_distance = (x_norm_sq + w_norm_sq - 2.0 * np.dot(X, W.T)) * bandw_inv
91
+
92
+ dtype = np.asarray(bandwidth).dtype
93
+ n_features = X.shape[1]
94
+ base_constant = dtype.type(np.power(2.0 * math.pi, -0.5 * n_features))
95
+ normalization = base_constant * np.power(bandwidth, -n_features)
96
+ return _exp_from_scaled_distance(scaled_distance) * normalization[None, :]
97
+
98
+ elif bandwidth_sharing == "per_class_per_feature":
99
+ bandwidth_sq = np.square(bandwidth)
100
+ bandw_inv = 1.0 / (2.0 * bandwidth_sq)
101
+ x_norm_sq = np.dot(np.square(X), bandw_inv.T)
102
+ w_norm_sq = (np.square(W) * bandw_inv).sum(axis=1)
103
+ scaled_distance = x_norm_sq + w_norm_sq - 2.0 * np.dot(X, (W * bandw_inv).T)
104
+
105
+ dtype = np.asarray(bandwidth).dtype
106
+ n_features = X.shape[1]
107
+ base_constant = dtype.type(np.power(2.0 * math.pi, -0.5 * n_features))
108
+ normalization = base_constant / np.prod(bandwidth, axis=1)
109
+ return _exp_from_scaled_distance(scaled_distance) * normalization[None, :]
110
+
111
+ else:
112
+ raise ValueError(f"Unknown bandwidth_sharing={bandwidth_sharing!r}.")
113
+
114
+ def log_grad(
115
+ self,
116
+ X: np.ndarray,
117
+ W: np.ndarray,
118
+ bandwidth, # float or array-like with shape (n_features,), (n_patterns,) or (n_patterns, n_features)
119
+ bandwidth_sharing: str,
120
+ normalized: bool = False,
121
+ ):
122
+ """Compute gradient of the log of Gaussian kernel values."""
123
+ _validate_bandwidth_numpy(bandwidth)
124
+ bandwidth_pow_3 = np.power(bandwidth, 3)
125
+
126
+ if bandwidth_sharing == "scalar":
127
+ x_norm_sq = np.square(X).sum(axis=1, keepdims=True)
128
+ w_norm_sq = np.square(W).sum(axis=1)
129
+ l2_norm_sq = x_norm_sq + w_norm_sq - 2.0 * np.dot(X, W.T)
130
+ return l2_norm_sq / (bandwidth_pow_3)
131
+
132
+ elif bandwidth_sharing == "per_feature":
133
+ diff = X[:, None, :] - W[None, :, :]
134
+ np.square(diff, out=diff)
135
+ diff /= bandwidth[None, None, :] ** 3
136
+ return diff
137
+
138
+ elif bandwidth_sharing == "per_class":
139
+ bandw_inv_pow3 = 1.0 / (bandwidth ** 3) # (n_patterns,)
140
+
141
+ x_norm_sq = np.square(X).sum(axis=1, keepdims=True)
142
+ w_norm_sq = np.square(W).sum(axis=1)
143
+
144
+ l2_norm_sq = (
145
+ x_norm_sq
146
+ + w_norm_sq[None, :]
147
+ - 2.0 * np.dot(X, W.T)
148
+ ) # (n_samples, n_patterns)
149
+
150
+ n_features = X.shape[1]
151
+
152
+ return (
153
+ l2_norm_sq * bandw_inv_pow3[None, :]
154
+ - n_features / bandwidth[None, :]
155
+ )
156
+
157
+ elif bandwidth_sharing == "per_class_per_feature":
158
+ diff = X[:, None, :] - W[None, :, :]
159
+ np.square(diff, out=diff)
160
+ diff /= bandwidth[None, :, :] ** 3
161
+ diff -= 1.0 / bandwidth[None, :, :]
162
+ return diff
163
+
164
+ else:
165
+ raise ValueError(f"Unknown bandwidth_sharing={bandwidth_sharing!r}.")
166
+
167
+
168
+ class LaplacianKernel:
169
+ def __call__(
170
+ self,
171
+ X: np.ndarray,
172
+ W: np.ndarray,
173
+ bandwidth, # float or array-like with shape (n_features,), (n_patterns,) or (n_patterns, n_features)
174
+ bandwidth_sharing: str,
175
+ normalized: bool = False,
176
+ ) -> np.ndarray:
177
+ """Compute Laplacian kernel values between samples in X and W."""
178
+ _validate_bandwidth_numpy(bandwidth)
179
+
180
+ if bandwidth_sharing == "scalar":
181
+ l1_norm = np.abs(X[:, None, :] - W[None, :, :]).sum(axis=2)
182
+ scaled_distance = l1_norm / bandwidth
183
+ return _exp_from_scaled_distance(scaled_distance)
184
+
185
+ elif bandwidth_sharing == "per_feature":
186
+ diff = (X[:, None, :] - W[None, :, :]) / bandwidth
187
+ np.abs(diff, out=diff)
188
+ return _exp_from_scaled_distance(diff.sum(axis=2))
189
+
190
+ elif bandwidth_sharing == "per_class":
191
+ l1_norm = np.abs(X[:, None, :] - W[None, :, :]).sum(axis=2)
192
+ scaled_distance = l1_norm / bandwidth # (n_patterns,) broadcasted
193
+ normalization = _laplacian_normalization_constant(bandwidth, X.shape[1], bandwidth_sharing)
194
+ return _exp_from_scaled_distance(scaled_distance) * normalization[None, :]
195
+
196
+ elif bandwidth_sharing == "per_class_per_feature":
197
+ diff = X[:, None, :] - W[None, :, :]
198
+ diff /= bandwidth
199
+ np.abs(diff, out=diff)
200
+ normalization = _laplacian_normalization_constant(bandwidth, X.shape[1], bandwidth_sharing)
201
+ return _exp_from_scaled_distance(diff.sum(axis=2)) * normalization[None, :]
202
+ else:
203
+ raise ValueError(f"Unknown bandwidth_sharing={bandwidth_sharing!r}.")
204
+
205
+ def log_grad(
206
+ self,
207
+ X: np.ndarray,
208
+ W: np.ndarray,
209
+ bandwidth, # float or array-like with shape (n_features,), (n_patterns,) or (n_patterns, n_features)
210
+ bandwidth_sharing: str,
211
+ normalized: bool = False,
212
+ ):
213
+ """Compute gradient of the log of Laplacian kernel values."""
214
+ _validate_bandwidth_numpy(bandwidth)
215
+
216
+ if bandwidth_sharing == "scalar":
217
+ l1_norm = np.abs(X[:, None, :] - W[None, :, :]).sum(axis=2)
218
+ return l1_norm / (bandwidth ** 2)
219
+
220
+ elif bandwidth_sharing == "per_feature":
221
+ diff = X[:, None, :] - W[None, :, :]
222
+ np.abs(diff, out=diff)
223
+ diff /= bandwidth[None, None, :] ** 2
224
+ return diff
225
+
226
+ elif bandwidth_sharing == "per_class":
227
+ l1_norm = np.abs(X[:, None, :] - W[None, :, :]).sum(axis=2)
228
+ n_features = X.shape[1]
229
+ return (
230
+ l1_norm / (bandwidth**2) # (n_patterns,) broadcasted
231
+ - n_features / bandwidth
232
+ )
233
+
234
+ elif bandwidth_sharing == "per_class_per_feature":
235
+ diff = X[:, None, :] - W[None, :, :]
236
+ np.abs(diff, out=diff)
237
+ diff /= bandwidth[None, :, :] ** 2
238
+ diff -= 1.0 / bandwidth[None, :, :]
239
+ return diff
240
+ else:
241
+ raise ValueError(f"Unknown bandwidth_sharing={bandwidth_sharing!r}.")
242
+
243
+
244
+ class ExponentialKernel:
245
+ def __call__(
246
+ self,
247
+ X: np.ndarray,
248
+ W: np.ndarray,
249
+ bandwidth, # float or array-like with shape (n_features,), (n_patterns,) or (n_patterns, n_features)
250
+ bandwidth_sharing: str,
251
+ normalized: bool = False,
252
+ ) -> np.ndarray:
253
+ """Compute exponential kernel values between samples in X and W."""
254
+ _validate_bandwidth_numpy(bandwidth)
255
+
256
+ if bandwidth_sharing == "scalar":
257
+ if normalized:
258
+ l2_norm = np.sqrt(np.clip(2*(1-np.dot(X, W.T)), 0, None))
259
+ return _exp_from_scaled_distance(l2_norm / bandwidth)
260
+
261
+ x_norm_sq = np.square(X).sum(axis=1, keepdims=True)
262
+ w_norm_sq = np.square(W).sum(axis=1)
263
+ l2_norm_sq = x_norm_sq + w_norm_sq - 2.0 * np.dot(X, W.T)
264
+ l2_norm = np.sqrt(np.clip(l2_norm_sq, 0, None))
265
+ return _exp_from_scaled_distance(l2_norm / bandwidth)
266
+
267
+ elif bandwidth_sharing == "per_feature":
268
+ diff = (X[:, None, :] - W[None, :, :]) / bandwidth
269
+ np.square(diff, out=diff)
270
+ return _exp_from_scaled_distance(np.sqrt(diff.sum(axis=2)))
271
+
272
+ elif bandwidth_sharing == "per_class":
273
+ scaled_diff = (X[:, None, :] - W[None, :, :]) / bandwidth[None, :, None]
274
+ scaled_distance = np.sqrt(np.square(scaled_diff).sum(axis=2))
275
+
276
+ dtype = np.asarray(bandwidth).dtype
277
+ n_features = X.shape[1]
278
+ base_constant = dtype.type(math.gamma(0.5 * n_features) / (2.0 * np.power(np.pi, 0.5 * n_features) * math.gamma(n_features)))
279
+ normalization = base_constant * np.power(bandwidth, -n_features)
280
+ return _exp_from_scaled_distance(scaled_distance) * normalization[None, :]
281
+
282
+ elif bandwidth_sharing == "per_class_per_feature":
283
+ diff = X[:, None, :] - W[None, :, :]
284
+ diff /= bandwidth[None, :, :]
285
+ np.square(diff, out=diff)
286
+ normalization = _exponential_normalization_constant(bandwidth, X.shape[1], bandwidth_sharing)
287
+ return _exp_from_scaled_distance(np.sqrt(diff.sum(axis=2))) * normalization[None, :]
288
+ else:
289
+ raise ValueError(f"Unknown bandwidth_sharing={bandwidth_sharing!r}.")
290
+
291
+ def log_grad(
292
+ self,
293
+ X: np.ndarray,
294
+ W: np.ndarray,
295
+ bandwidth, # float or array-like with shape (n_features,), (n_patterns,) or (n_patterns, n_features)
296
+ bandwidth_sharing: str,
297
+ normalized: bool = False,
298
+ ):
299
+ """Compute gradient of the log of Exponential kernel values."""
300
+ _validate_bandwidth_numpy(bandwidth)
301
+
302
+ if bandwidth_sharing == "scalar":
303
+ x_norm_sq = np.square(X).sum(axis=1, keepdims=True)
304
+ w_norm_sq = np.square(W).sum(axis=1)
305
+
306
+ l2_norm_sq = (
307
+ x_norm_sq
308
+ + w_norm_sq[None, :]
309
+ - 2.0 * np.dot(X, W.T)
310
+ )
311
+
312
+ l2_norm_sq = np.maximum(l2_norm_sq, 0.0)
313
+ l2_norm = np.sqrt(l2_norm_sq)
314
+
315
+ return l2_norm / (bandwidth ** 2)
316
+
317
+ elif bandwidth_sharing == "per_feature":
318
+ diff = X[:, None, :] - W[None, :, :] # (n_samples, n_patterns, n_features)
319
+ np.square(diff, out=diff) # diff = (x-w)^2, in-place
320
+ diff /= bandwidth[None, None, :] ** 2 # diff = (x-w)^2/bw^2, in-place
321
+ r = np.sqrt(diff.sum(axis=2, keepdims=True)) # (n_samples, n_patterns, 1)
322
+ diff /= bandwidth[None, None, :] # diff = (x-w)^2/bw^3, in-place
323
+ # where r==0, diff is also 0 (x==w), so 0/inf = 0 correctly
324
+ diff /= np.where(r > 0.0, r, np.inf)
325
+ return diff
326
+
327
+ elif bandwidth_sharing == "per_class":
328
+ x_norm_sq = np.square(X).sum(axis=1, keepdims=True)
329
+ w_norm_sq = np.square(W).sum(axis=1)
330
+
331
+ l2_norm_sq = (
332
+ x_norm_sq
333
+ + w_norm_sq[None, :]
334
+ - 2.0 * np.dot(X, W.T)
335
+ )
336
+
337
+ l2_norm_sq = np.maximum(l2_norm_sq, 0.0)
338
+ l2_norm = np.sqrt(l2_norm_sq)
339
+
340
+ n_features = X.shape[1]
341
+
342
+ return l2_norm / bandwidth[None, :] ** 2 - n_features / bandwidth[None, :]
343
+
344
+ elif bandwidth_sharing == "per_class_per_feature":
345
+ diff = X[:, None, :] - W[None, :, :]
346
+ np.square(diff, out=diff) # diff = (x-w)^2, in-place
347
+ diff /= bandwidth[None, :, :] ** 2 # diff = (x-w)^2/bw^2, in-place
348
+ r = np.sqrt(diff.sum(axis=2, keepdims=True)) # (n_samples, n_patterns, 1)
349
+ diff /= bandwidth[None, :, :] # diff = (x-w)^2/bw^3, in-place
350
+ diff /= np.where(r > 0.0, r, np.inf) # 0/inf = 0 where r==0
351
+ diff -= 1.0 / bandwidth[None, :, :]
352
+ return diff
353
+ else:
354
+ raise ValueError(f"Unknown bandwidth_sharing={bandwidth_sharing!r}.")
355
+
356
+
357
+
358
+ KERNEL_REGISTRY: dict[str, KernelCallable] = {
359
+ "gaussian": GaussianKernel(),
360
+ "laplacian": LaplacianKernel(),
361
+ "exponential": ExponentialKernel(),
362
+ }
363
+
364
+
365
+ def resolve_kernel(kernel: str):
366
+ try:
367
+ return KERNEL_REGISTRY[kernel.lower()]
368
+ except KeyError as exc:
369
+ available = ", ".join(sorted(KERNEL_REGISTRY))
370
+ raise ValueError(f"Unknown kernel={kernel!r}. Available: {available}") from exc