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,458 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from probabilisticnn.base.types import KernelCallable
|
|
5
|
+
from numba import njit
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@njit(fastmath=True, cache=True)
|
|
9
|
+
def _rowwise_product(values: np.ndarray) -> np.ndarray:
|
|
10
|
+
out = np.empty(values.shape[0], dtype=values.dtype)
|
|
11
|
+
for i in range(values.shape[0]):
|
|
12
|
+
out[i] = np.prod(values[i])
|
|
13
|
+
return out
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# ==============================================================================
|
|
17
|
+
# Matrix-level kernels (return full K matrix)
|
|
18
|
+
# Used by the public gaussian_kernel / laplacian_kernel / exponential_kernel API.
|
|
19
|
+
# ==============================================================================
|
|
20
|
+
|
|
21
|
+
# ------------------------------------------------------------------------------
|
|
22
|
+
# gaussian kernel
|
|
23
|
+
# Uses the : ||x-w||^2 = ||x||^2 + ||w||^2 - 2 x·w — no 3-D tensor.
|
|
24
|
+
# ------------------------------------------------------------------------------
|
|
25
|
+
@njit(parallel=True, fastmath=True, cache=True)
|
|
26
|
+
def _gaussian_kernel_scalar_bandw(
|
|
27
|
+
X: np.ndarray,
|
|
28
|
+
W: np.ndarray,
|
|
29
|
+
bandwidth: np.float32 | np.float64,
|
|
30
|
+
normalized: bool = False,
|
|
31
|
+
) -> np.ndarray:
|
|
32
|
+
bandwidth_sq = bandwidth * bandwidth
|
|
33
|
+
if normalized:
|
|
34
|
+
similarities = np.dot(X, W.T)
|
|
35
|
+
one = similarities.dtype.type(1)
|
|
36
|
+
zero = similarities.dtype.type(0)
|
|
37
|
+
scaled_distance = (one - similarities) / bandwidth_sq
|
|
38
|
+
scaled_distance = np.maximum(scaled_distance, zero)
|
|
39
|
+
return np.exp(-scaled_distance)
|
|
40
|
+
|
|
41
|
+
x_norm_sq = np.square(X).sum(axis=1).reshape((X.shape[0], 1))
|
|
42
|
+
w_norm_sq = np.square(W).sum(axis=1)
|
|
43
|
+
cross_term = np.dot(X, W.T)
|
|
44
|
+
l2_norm_sq = x_norm_sq + w_norm_sq - (cross_term + cross_term)
|
|
45
|
+
scaled_distance = l2_norm_sq / (bandwidth_sq + bandwidth_sq)
|
|
46
|
+
scaled_distance = np.maximum(scaled_distance, scaled_distance.dtype.type(0))
|
|
47
|
+
return np.exp(-scaled_distance)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@njit(parallel=True, fastmath=True, cache=True)
|
|
51
|
+
def _gaussian_kernel_per_feature(
|
|
52
|
+
X: np.ndarray,
|
|
53
|
+
W: np.ndarray,
|
|
54
|
+
bandwidth: np.ndarray,
|
|
55
|
+
normalized: bool = False,
|
|
56
|
+
) -> np.ndarray:
|
|
57
|
+
bandwidth_sq = np.square(bandwidth)
|
|
58
|
+
bandw_inv = np.reciprocal(bandwidth_sq + bandwidth_sq)
|
|
59
|
+
x_norm_sq = (
|
|
60
|
+
(np.square(X) * bandw_inv)
|
|
61
|
+
.sum(axis=1)
|
|
62
|
+
.reshape((X.shape[0], 1))
|
|
63
|
+
)
|
|
64
|
+
w_norm_sq = (
|
|
65
|
+
(np.square(W) * bandw_inv)
|
|
66
|
+
.sum(axis=1)
|
|
67
|
+
)
|
|
68
|
+
cross_term = np.dot(X, (W * bandw_inv).T)
|
|
69
|
+
scaled_distance = x_norm_sq + w_norm_sq - (cross_term + cross_term)
|
|
70
|
+
scaled_distance = np.maximum(scaled_distance, scaled_distance.dtype.type(0))
|
|
71
|
+
return np.exp(-scaled_distance)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@njit(parallel=True, fastmath=True, cache=True)
|
|
75
|
+
def _gaussian_kernel_per_class(
|
|
76
|
+
X: np.ndarray,
|
|
77
|
+
W: np.ndarray,
|
|
78
|
+
bandwidth: np.ndarray,
|
|
79
|
+
normalized: bool = False,
|
|
80
|
+
) -> np.ndarray:
|
|
81
|
+
dtype = X.dtype
|
|
82
|
+
n_features = X.shape[1]
|
|
83
|
+
bandwidth_sq = np.square(bandwidth)
|
|
84
|
+
bandw_inv = np.reciprocal(bandwidth_sq + bandwidth_sq)
|
|
85
|
+
x_norm_sq = np.square(X).sum(axis=1).reshape((X.shape[0], 1))
|
|
86
|
+
w_norm_sq = np.square(W).sum(axis=1)
|
|
87
|
+
cross_term = np.dot(X, W.T)
|
|
88
|
+
scaled_distance = (x_norm_sq + w_norm_sq - (cross_term + cross_term)) * bandw_inv
|
|
89
|
+
scaled_distance = np.maximum(scaled_distance, scaled_distance.dtype.type(0))
|
|
90
|
+
normalization = dtype.type(np.power(2.0 * np.pi, -0.5 * n_features)) * np.power(bandwidth, -n_features)
|
|
91
|
+
normalization = normalization.astype(dtype)
|
|
92
|
+
return np.exp(-scaled_distance) * normalization.reshape((1, normalization.shape[0]))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@njit(parallel=True, fastmath=True, cache=True)
|
|
96
|
+
def _gaussian_kernel_per_class_per_feature(
|
|
97
|
+
X: np.ndarray,
|
|
98
|
+
W: np.ndarray,
|
|
99
|
+
bandwidth: np.ndarray,
|
|
100
|
+
normalized: bool = False,
|
|
101
|
+
) -> np.ndarray:
|
|
102
|
+
dtype = X.dtype
|
|
103
|
+
n_features = X.shape[1]
|
|
104
|
+
bandwidth_sq = np.square(bandwidth)
|
|
105
|
+
bandw_inv = np.reciprocal(bandwidth_sq + bandwidth_sq)
|
|
106
|
+
x_norm_sq = np.dot(np.square(X), bandw_inv.T)
|
|
107
|
+
w_norm_sq = (np.square(W) * bandw_inv).sum(axis=1)
|
|
108
|
+
cross_term = np.dot(X, (W * bandw_inv).T)
|
|
109
|
+
scaled_distance = x_norm_sq + w_norm_sq - (cross_term + cross_term)
|
|
110
|
+
scaled_distance = np.maximum(scaled_distance, scaled_distance.dtype.type(0))
|
|
111
|
+
normalization = dtype.type(np.power(2.0 * np.pi, -0.5 * n_features)) / _rowwise_product(bandwidth)
|
|
112
|
+
normalization = normalization.astype(dtype)
|
|
113
|
+
return np.exp(-scaled_distance) * normalization.reshape((1, normalization.shape[0]))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# ------------------------------------------------------------------------------
|
|
117
|
+
# laplacian kernel
|
|
118
|
+
# L1 distance cannot use the factorization — explicit loops avoid the
|
|
119
|
+
# (n_samples, n_patterns, n_features) intermediate tensor.
|
|
120
|
+
# ------------------------------------------------------------------------------
|
|
121
|
+
@njit(fastmath=True, cache=True)
|
|
122
|
+
def _laplacian_kernel_scalar_bandw(
|
|
123
|
+
X: np.ndarray,
|
|
124
|
+
W: np.ndarray,
|
|
125
|
+
bandwidth: np.float32 | np.float64,
|
|
126
|
+
normalized: bool = False,
|
|
127
|
+
) -> np.ndarray:
|
|
128
|
+
n_samples = X.shape[0]
|
|
129
|
+
n_patterns = W.shape[0]
|
|
130
|
+
n_features = X.shape[1]
|
|
131
|
+
dtype = X.dtype
|
|
132
|
+
out = np.empty((n_samples, n_patterns), dtype=dtype)
|
|
133
|
+
inv_bw = dtype.type(1.0) / bandwidth
|
|
134
|
+
for i in range(n_samples):
|
|
135
|
+
for j in range(n_patterns):
|
|
136
|
+
acc = dtype.type(0.0)
|
|
137
|
+
for k in range(n_features):
|
|
138
|
+
d = X[i, k] - W[j, k]
|
|
139
|
+
if d < dtype.type(0.0):
|
|
140
|
+
d = -d
|
|
141
|
+
acc += d
|
|
142
|
+
out[i, j] = dtype.type(math.exp(float(-acc * inv_bw)))
|
|
143
|
+
return out
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@njit(fastmath=True, cache=True)
|
|
147
|
+
def _laplacian_kernel_per_feature(
|
|
148
|
+
X: np.ndarray,
|
|
149
|
+
W: np.ndarray,
|
|
150
|
+
bandwidth: np.ndarray,
|
|
151
|
+
normalized: bool = False,
|
|
152
|
+
) -> np.ndarray:
|
|
153
|
+
n_samples = X.shape[0]
|
|
154
|
+
n_patterns = W.shape[0]
|
|
155
|
+
n_features = X.shape[1]
|
|
156
|
+
dtype = X.dtype
|
|
157
|
+
out = np.empty((n_samples, n_patterns), dtype=dtype)
|
|
158
|
+
for i in range(n_samples):
|
|
159
|
+
for j in range(n_patterns):
|
|
160
|
+
acc = dtype.type(0.0)
|
|
161
|
+
for k in range(n_features):
|
|
162
|
+
d = X[i, k] - W[j, k]
|
|
163
|
+
if d < dtype.type(0.0):
|
|
164
|
+
d = -d
|
|
165
|
+
acc += d / bandwidth[k]
|
|
166
|
+
out[i, j] = dtype.type(math.exp(float(-acc)))
|
|
167
|
+
return out
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@njit(fastmath=True, cache=True)
|
|
171
|
+
def _laplacian_kernel_per_class(
|
|
172
|
+
X: np.ndarray,
|
|
173
|
+
W: np.ndarray,
|
|
174
|
+
bandwidth: np.ndarray,
|
|
175
|
+
normalized: bool = False,
|
|
176
|
+
) -> np.ndarray:
|
|
177
|
+
dtype = X.dtype
|
|
178
|
+
n_samples = X.shape[0]
|
|
179
|
+
n_patterns = W.shape[0]
|
|
180
|
+
n_features = X.shape[1]
|
|
181
|
+
out = np.empty((n_samples, n_patterns), dtype=dtype)
|
|
182
|
+
base_c = dtype.type(np.power(2.0, -n_features))
|
|
183
|
+
norm = (base_c * np.power(bandwidth, -n_features)).astype(dtype)
|
|
184
|
+
for i in range(n_samples):
|
|
185
|
+
for j in range(n_patterns):
|
|
186
|
+
acc = dtype.type(0.0)
|
|
187
|
+
for k in range(n_features):
|
|
188
|
+
d = X[i, k] - W[j, k]
|
|
189
|
+
if d < dtype.type(0.0):
|
|
190
|
+
d = -d
|
|
191
|
+
acc += d
|
|
192
|
+
out[i, j] = dtype.type(math.exp(float(-acc / bandwidth[j]))) * norm[j]
|
|
193
|
+
return out
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
@njit(fastmath=True, cache=True)
|
|
197
|
+
def _laplacian_kernel_per_class_per_feature(
|
|
198
|
+
X: np.ndarray,
|
|
199
|
+
W: np.ndarray,
|
|
200
|
+
bandwidth: np.ndarray,
|
|
201
|
+
normalized: bool = False,
|
|
202
|
+
) -> np.ndarray:
|
|
203
|
+
dtype = X.dtype
|
|
204
|
+
n_samples = X.shape[0]
|
|
205
|
+
n_patterns = W.shape[0]
|
|
206
|
+
n_features = X.shape[1]
|
|
207
|
+
out = np.empty((n_samples, n_patterns), dtype=dtype)
|
|
208
|
+
base_c = dtype.type(np.power(2.0, -n_features))
|
|
209
|
+
norm = (base_c / _rowwise_product(bandwidth.astype(dtype))).astype(dtype)
|
|
210
|
+
for i in range(n_samples):
|
|
211
|
+
for j in range(n_patterns):
|
|
212
|
+
acc = dtype.type(0.0)
|
|
213
|
+
for k in range(n_features):
|
|
214
|
+
d = X[i, k] - W[j, k]
|
|
215
|
+
if d < dtype.type(0.0):
|
|
216
|
+
d = -d
|
|
217
|
+
acc += d / bandwidth[j, k]
|
|
218
|
+
out[i, j] = dtype.type(math.exp(float(-acc))) * norm[j]
|
|
219
|
+
return out
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
# ------------------------------------------------------------------------------
|
|
223
|
+
# exponential kernel — uses kernel trick for L2, no 3-D tensor needed.
|
|
224
|
+
# ------------------------------------------------------------------------------
|
|
225
|
+
@njit(parallel=True, fastmath=True, cache=True)
|
|
226
|
+
def _exponential_kernel_scalar_bandw(
|
|
227
|
+
X: np.ndarray,
|
|
228
|
+
W: np.ndarray,
|
|
229
|
+
bandwidth: np.float32 | np.float64,
|
|
230
|
+
normalized: bool = False,
|
|
231
|
+
) -> np.ndarray:
|
|
232
|
+
if normalized:
|
|
233
|
+
similarities = np.dot(X, W.T)
|
|
234
|
+
one = similarities.dtype.type(1)
|
|
235
|
+
zero = similarities.dtype.type(0)
|
|
236
|
+
l2_norm_sq = one - similarities
|
|
237
|
+
l2_norm_sq = l2_norm_sq + l2_norm_sq
|
|
238
|
+
l2_norm_sq = np.maximum(l2_norm_sq, zero)
|
|
239
|
+
l2_norm = np.sqrt(l2_norm_sq)
|
|
240
|
+
scaled_distance = l2_norm / bandwidth
|
|
241
|
+
scaled_distance = np.maximum(scaled_distance, zero)
|
|
242
|
+
return np.exp(-scaled_distance)
|
|
243
|
+
|
|
244
|
+
x_norm_sq = np.square(X).sum(axis=1).reshape((X.shape[0], 1))
|
|
245
|
+
w_norm_sq = np.square(W).sum(axis=1)
|
|
246
|
+
cross_term = np.dot(X, W.T)
|
|
247
|
+
l2_norm_sq = x_norm_sq + w_norm_sq - (cross_term + cross_term)
|
|
248
|
+
l2_norm_sq = np.maximum(l2_norm_sq, l2_norm_sq.dtype.type(0))
|
|
249
|
+
l2_norm = np.sqrt(l2_norm_sq)
|
|
250
|
+
scaled_distance = l2_norm / bandwidth
|
|
251
|
+
scaled_distance = np.maximum(scaled_distance, scaled_distance.dtype.type(0))
|
|
252
|
+
return np.exp(-scaled_distance)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
@njit(parallel=True, fastmath=True, cache=True)
|
|
256
|
+
def _exponential_kernel_per_feature(
|
|
257
|
+
X: np.ndarray,
|
|
258
|
+
W: np.ndarray,
|
|
259
|
+
bandwidth: np.ndarray,
|
|
260
|
+
normalized: bool = False,
|
|
261
|
+
) -> np.ndarray:
|
|
262
|
+
x_scaled = X / bandwidth
|
|
263
|
+
w_scaled = W / bandwidth
|
|
264
|
+
x_norm_sq = np.square(x_scaled).sum(axis=1).reshape((X.shape[0], 1))
|
|
265
|
+
w_norm_sq = np.square(w_scaled).sum(axis=1)
|
|
266
|
+
cross_term = np.dot(x_scaled, w_scaled.T)
|
|
267
|
+
scaled_distance_sq = x_norm_sq + w_norm_sq - (cross_term + cross_term)
|
|
268
|
+
scaled_distance_sq = np.maximum(scaled_distance_sq, scaled_distance_sq.dtype.type(0))
|
|
269
|
+
scaled_distance = np.sqrt(scaled_distance_sq)
|
|
270
|
+
scaled_distance = np.maximum(scaled_distance, scaled_distance.dtype.type(0))
|
|
271
|
+
return np.exp(-scaled_distance)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
@njit(parallel=True, fastmath=True, cache=True)
|
|
275
|
+
def _exponential_kernel_per_class(
|
|
276
|
+
X: np.ndarray,
|
|
277
|
+
W: np.ndarray,
|
|
278
|
+
bandwidth: np.ndarray,
|
|
279
|
+
normalized: bool = False,
|
|
280
|
+
) -> np.ndarray:
|
|
281
|
+
dtype = X.dtype
|
|
282
|
+
n_features = X.shape[1]
|
|
283
|
+
bandw_inv = np.reciprocal(bandwidth)
|
|
284
|
+
bandw_inv_sq = np.square(bandw_inv)
|
|
285
|
+
x_norm_sq = np.square(X).sum(axis=1).reshape((X.shape[0], 1))
|
|
286
|
+
w_norm_sq = np.square(W).sum(axis=1)
|
|
287
|
+
cross_term = np.dot(X, W.T)
|
|
288
|
+
scaled_distance_sq = (x_norm_sq + w_norm_sq - (cross_term + cross_term)) * bandw_inv_sq
|
|
289
|
+
scaled_distance_sq = np.maximum(scaled_distance_sq, scaled_distance_sq.dtype.type(0))
|
|
290
|
+
scaled_distance = np.sqrt(scaled_distance_sq)
|
|
291
|
+
scaled_distance = np.maximum(scaled_distance, scaled_distance.dtype.type(0))
|
|
292
|
+
normalization = dtype.type(
|
|
293
|
+
math.gamma(0.5 * n_features) / (2.0 * np.power(np.pi, 0.5 * n_features) * math.gamma(n_features))
|
|
294
|
+
) * np.power(bandwidth, -n_features)
|
|
295
|
+
normalization = normalization.astype(dtype)
|
|
296
|
+
return np.exp(-scaled_distance) * normalization.reshape((1, normalization.shape[0]))
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
@njit(parallel=True, fastmath=True, cache=True)
|
|
300
|
+
def _exponential_kernel_per_class_per_feature(
|
|
301
|
+
X: np.ndarray,
|
|
302
|
+
W: np.ndarray,
|
|
303
|
+
bandwidth: np.ndarray,
|
|
304
|
+
normalized: bool = False,
|
|
305
|
+
) -> np.ndarray:
|
|
306
|
+
dtype = X.dtype
|
|
307
|
+
n_features = X.shape[1]
|
|
308
|
+
bandw_inv = np.reciprocal(bandwidth)
|
|
309
|
+
bandw_inv_sq = np.square(bandw_inv)
|
|
310
|
+
x_norm_sq = np.dot(np.square(X), bandw_inv_sq.T)
|
|
311
|
+
w_norm_sq = (np.square(W) * bandw_inv_sq).sum(axis=1)
|
|
312
|
+
cross_term = np.dot(X, (W * bandw_inv_sq).T)
|
|
313
|
+
scaled_distance_sq = x_norm_sq + w_norm_sq - (cross_term + cross_term)
|
|
314
|
+
scaled_distance_sq = np.maximum(scaled_distance_sq, scaled_distance_sq.dtype.type(0))
|
|
315
|
+
scaled_distance = np.sqrt(scaled_distance_sq)
|
|
316
|
+
scaled_distance = np.maximum(scaled_distance, scaled_distance.dtype.type(0))
|
|
317
|
+
normalization = dtype.type(
|
|
318
|
+
math.gamma(0.5 * n_features) / (2.0 * np.power(np.pi, 0.5 * n_features) * math.gamma(n_features))
|
|
319
|
+
) / _rowwise_product(bandwidth)
|
|
320
|
+
normalization = normalization.astype(dtype)
|
|
321
|
+
return np.exp(-scaled_distance) * normalization.reshape((1, normalization.shape[0]))
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
# ==============================================================================
|
|
325
|
+
# Matrix-kernel dispatch
|
|
326
|
+
# ==============================================================================
|
|
327
|
+
|
|
328
|
+
# Maps (kernel, bandwidth_sharing) to matrix-level @njit(fastmath=True) function.
|
|
329
|
+
_MATRIX_KERNEL_REGISTRY: dict = {
|
|
330
|
+
("gaussian", "scalar"): _gaussian_kernel_scalar_bandw,
|
|
331
|
+
("gaussian", "per_feature"): _gaussian_kernel_per_feature,
|
|
332
|
+
("gaussian", "per_class"): _gaussian_kernel_per_class,
|
|
333
|
+
("gaussian", "per_class_per_feature"): _gaussian_kernel_per_class_per_feature,
|
|
334
|
+
|
|
335
|
+
("laplacian", "scalar"): _laplacian_kernel_scalar_bandw,
|
|
336
|
+
("laplacian", "per_feature"): _laplacian_kernel_per_feature,
|
|
337
|
+
("laplacian", "per_class"): _laplacian_kernel_per_class,
|
|
338
|
+
("laplacian", "per_class_per_feature"): _laplacian_kernel_per_class_per_feature,
|
|
339
|
+
|
|
340
|
+
("exponential", "scalar"): _exponential_kernel_scalar_bandw,
|
|
341
|
+
("exponential", "per_feature"): _exponential_kernel_per_feature,
|
|
342
|
+
("exponential", "per_class"): _exponential_kernel_per_class,
|
|
343
|
+
("exponential", "per_class_per_feature"): _exponential_kernel_per_class_per_feature,
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def resolve_matrix_kernel(kernel: str, bandwidth_sharing: str):
|
|
348
|
+
"""Return the matrix-level @njit kernel for (kernel, bandwidth_sharing)."""
|
|
349
|
+
key = (kernel.lower(), bandwidth_sharing)
|
|
350
|
+
try:
|
|
351
|
+
return _MATRIX_KERNEL_REGISTRY[key]
|
|
352
|
+
except KeyError as exc:
|
|
353
|
+
raise ValueError(
|
|
354
|
+
f"No matrix kernel for kernel={kernel!r}, bandwidth_sharing={bandwidth_sharing!r}"
|
|
355
|
+
) from exc
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
# ==============================================================================
|
|
359
|
+
# Public matrix-kernel API (kept for direct use / testing)
|
|
360
|
+
# ==============================================================================
|
|
361
|
+
|
|
362
|
+
def gaussian_kernel(
|
|
363
|
+
X: np.ndarray,
|
|
364
|
+
W: np.ndarray,
|
|
365
|
+
bandwidth,
|
|
366
|
+
bandwidth_sharing: str | None = None,
|
|
367
|
+
normalized: bool = False,
|
|
368
|
+
) -> np.ndarray:
|
|
369
|
+
"""Compute Gaussian kernel values between samples in X and W."""
|
|
370
|
+
if np.any(bandwidth <= 0):
|
|
371
|
+
raise ValueError("`bandwidth` must be strictly positive.")
|
|
372
|
+
|
|
373
|
+
dtype = X.dtype
|
|
374
|
+
X = np.asarray(X, dtype=dtype)
|
|
375
|
+
W = np.asarray(W, dtype=dtype)
|
|
376
|
+
bandwidth_arr = np.asarray(bandwidth, dtype=dtype)
|
|
377
|
+
|
|
378
|
+
if bandwidth_sharing == "scalar":
|
|
379
|
+
return _gaussian_kernel_scalar_bandw(X, W, bandwidth_arr[()], normalized)
|
|
380
|
+
elif bandwidth_sharing == "per_feature":
|
|
381
|
+
return _gaussian_kernel_per_feature(X, W, bandwidth_arr, normalized)
|
|
382
|
+
elif bandwidth_sharing == "per_class":
|
|
383
|
+
return _gaussian_kernel_per_class(X, W, bandwidth_arr, normalized)
|
|
384
|
+
elif bandwidth_sharing == "per_class_per_feature":
|
|
385
|
+
return _gaussian_kernel_per_class_per_feature(X, W, bandwidth_arr, normalized)
|
|
386
|
+
else:
|
|
387
|
+
raise ValueError(f"Unknown bandwidth_sharing.")
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def laplacian_kernel(
|
|
391
|
+
X: np.ndarray,
|
|
392
|
+
W: np.ndarray,
|
|
393
|
+
bandwidth,
|
|
394
|
+
bandwidth_sharing: str | None = None,
|
|
395
|
+
normalized: bool = False,
|
|
396
|
+
) -> np.ndarray:
|
|
397
|
+
"""Compute Laplacian kernel values between samples in X and W."""
|
|
398
|
+
if np.any(bandwidth <= 0):
|
|
399
|
+
raise ValueError("`bandwidth` must be strictly positive.")
|
|
400
|
+
|
|
401
|
+
dtype = X.dtype
|
|
402
|
+
X = np.asarray(X, dtype=dtype)
|
|
403
|
+
W = np.asarray(W, dtype=dtype)
|
|
404
|
+
bandwidth_arr = np.asarray(bandwidth, dtype=dtype)
|
|
405
|
+
|
|
406
|
+
if bandwidth_sharing == "scalar":
|
|
407
|
+
return _laplacian_kernel_scalar_bandw(X, W, bandwidth_arr[()], normalized)
|
|
408
|
+
elif bandwidth_sharing == "per_feature":
|
|
409
|
+
return _laplacian_kernel_per_feature(X, W, bandwidth_arr, normalized)
|
|
410
|
+
elif bandwidth_sharing == "per_class":
|
|
411
|
+
return _laplacian_kernel_per_class(X, W, bandwidth_arr, normalized)
|
|
412
|
+
elif bandwidth_sharing == "per_class_per_feature":
|
|
413
|
+
return _laplacian_kernel_per_class_per_feature(X, W, bandwidth_arr, normalized)
|
|
414
|
+
else:
|
|
415
|
+
raise ValueError(f"Unknown bandwidth_sharing")
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def exponential_kernel(
|
|
419
|
+
X: np.ndarray,
|
|
420
|
+
W: np.ndarray,
|
|
421
|
+
bandwidth,
|
|
422
|
+
bandwidth_sharing: str | None = None,
|
|
423
|
+
normalized: bool = False,
|
|
424
|
+
) -> np.ndarray:
|
|
425
|
+
"""Compute Exponential kernel values between samples in X and W."""
|
|
426
|
+
if np.any(bandwidth <= 0):
|
|
427
|
+
raise ValueError("`bandwidth` must be strictly positive.")
|
|
428
|
+
|
|
429
|
+
dtype = X.dtype
|
|
430
|
+
X = np.asarray(X, dtype=dtype)
|
|
431
|
+
W = np.asarray(W, dtype=dtype)
|
|
432
|
+
bandwidth_arr = np.asarray(bandwidth, dtype=dtype)
|
|
433
|
+
|
|
434
|
+
if bandwidth_sharing == "scalar":
|
|
435
|
+
return _exponential_kernel_scalar_bandw(X, W, bandwidth_arr[()], normalized)
|
|
436
|
+
elif bandwidth_sharing == "per_feature":
|
|
437
|
+
return _exponential_kernel_per_feature(X, W, bandwidth_arr, normalized)
|
|
438
|
+
elif bandwidth_sharing == "per_class":
|
|
439
|
+
return _exponential_kernel_per_class(X, W, bandwidth_arr, normalized)
|
|
440
|
+
elif bandwidth_sharing == "per_class_per_feature":
|
|
441
|
+
return _exponential_kernel_per_class_per_feature(X, W, bandwidth_arr, normalized)
|
|
442
|
+
else:
|
|
443
|
+
raise ValueError(f"Unknown bandwidth_sharing.")
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
KERNEL_REGISTRY: dict[str, KernelCallable] = {
|
|
447
|
+
"gaussian": gaussian_kernel,
|
|
448
|
+
"laplacian": laplacian_kernel,
|
|
449
|
+
"exponential": exponential_kernel,
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def resolve_kernel(kernel: str):
|
|
454
|
+
try:
|
|
455
|
+
return KERNEL_REGISTRY[kernel.lower()]
|
|
456
|
+
except KeyError as exc:
|
|
457
|
+
available = ", ".join(sorted(KERNEL_REGISTRY))
|
|
458
|
+
raise ValueError(f"Unknown kernel={kernel!r}. Available: {available}") from exc
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
from probabilisticnn.base.utils import cast_to_dtype
|
|
2
|
+
import numpy as np
|
|
3
|
+
from sklearn.base import BaseEstimator, TransformerMixin
|
|
4
|
+
from sklearn.utils.validation import validate_data, check_is_fitted
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class SummationLayer(BaseEstimator, TransformerMixin):
|
|
8
|
+
def __init__(self):
|
|
9
|
+
super().__init__()
|
|
10
|
+
|
|
11
|
+
def fit(self, X, y):
|
|
12
|
+
X, y = validate_data(self, X, y)
|
|
13
|
+
self.classes_, self.y_encoded_, self.counts_ = np.unique(y, return_inverse=True, return_counts=True)
|
|
14
|
+
|
|
15
|
+
n_train = X.shape[0]
|
|
16
|
+
self.n_classes_ = len(self.classes_)
|
|
17
|
+
self.n_train_ = n_train
|
|
18
|
+
|
|
19
|
+
self.class_mask_ = np.zeros((n_train, self.n_classes_), dtype=X.dtype)
|
|
20
|
+
self.class_mask_[np.arange(n_train), self.y_encoded_] = 1.0
|
|
21
|
+
return self
|
|
22
|
+
|
|
23
|
+
def transform(self, K):
|
|
24
|
+
check_is_fitted(self, ["classes_", "class_mask_", "n_train_"])
|
|
25
|
+
|
|
26
|
+
if K.shape[1] != self.n_train_:
|
|
27
|
+
raise ValueError(
|
|
28
|
+
f"K has {K.shape[1]} columns, but expected {self.n_train_} train samples."
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
f_unnormalized = np.matmul(K, self.class_mask_)
|
|
32
|
+
|
|
33
|
+
f = f_unnormalized / self.n_classes_
|
|
34
|
+
self.last_f_ = f
|
|
35
|
+
return f
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class OutputLayer:
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
losses,
|
|
42
|
+
compute_dtype
|
|
43
|
+
):
|
|
44
|
+
self.losses = losses
|
|
45
|
+
self.compute_dtype = compute_dtype
|
|
46
|
+
|
|
47
|
+
def fit(self, y):
|
|
48
|
+
self.classes_, self.y_encoded_, counts = np.unique(y, return_inverse=True, return_counts=True)
|
|
49
|
+
self.n_classes_ = len(self.classes_)
|
|
50
|
+
self.prior_ = cast_to_dtype(counts / counts.sum(), self.compute_dtype)
|
|
51
|
+
|
|
52
|
+
if isinstance(self.losses, str) and self.losses == "uniform":
|
|
53
|
+
losses = cast_to_dtype(np.ones(self.n_classes_), self.compute_dtype)
|
|
54
|
+
elif isinstance(self.losses, np.ndarray) or isinstance(self.losses, list):
|
|
55
|
+
losses = cast_to_dtype(self.losses, self.compute_dtype)
|
|
56
|
+
if losses.shape[0] != self.n_classes_ or losses.ndim != 1:
|
|
57
|
+
raise ValueError("`losses` must have one value per class.")
|
|
58
|
+
else:
|
|
59
|
+
raise ValueError(f"Unknown losses={self.losses!r}.")
|
|
60
|
+
|
|
61
|
+
self.likelihood_multiplier_ = self.prior_ * losses
|
|
62
|
+
return self
|
|
63
|
+
|
|
64
|
+
def transform_encoded(self, f):
|
|
65
|
+
"""Predict encoded class indices from class densities.
|
|
66
|
+
|
|
67
|
+
Предсказывает закодированные индексы классов по значениям плотности.
|
|
68
|
+
"""
|
|
69
|
+
likelihood_multiplier = np.asarray(self.likelihood_multiplier_, dtype=f.dtype)
|
|
70
|
+
posterior = f * likelihood_multiplier
|
|
71
|
+
return np.argmax(posterior, axis=1)
|
|
72
|
+
|
|
73
|
+
def transform(self, f):
|
|
74
|
+
classes_enc = self.transform_encoded(f)
|
|
75
|
+
classes = self.classes_[classes_enc]
|
|
76
|
+
return classes
|
|
77
|
+
|
|
78
|
+
def posteriori(self, f):
|
|
79
|
+
prior = np.asarray(self.prior_, dtype=f.dtype)
|
|
80
|
+
nom = prior * f
|
|
81
|
+
denom = np.sum(nom, axis=1, keepdims=True)
|
|
82
|
+
fallback = np.broadcast_to(prior, nom.shape).copy()
|
|
83
|
+
return np.divide(nom, denom, out=fallback, where=denom > 0)
|