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,207 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from probabilisticnn.base.optim import BandwidthOptimizer
|
|
4
|
+
from probabilisticnn.common import AdaptivePatternLayer
|
|
5
|
+
from sklearn.base import BaseEstimator, RegressorMixin
|
|
6
|
+
from sklearn.utils.validation import check_is_fitted, validate_data
|
|
7
|
+
from probabilisticnn.common.pattern_layer import PatternLayer
|
|
8
|
+
from probabilisticnn.grnn.layers import SummationLayer
|
|
9
|
+
from probabilisticnn.base.utils import normalize_l2
|
|
10
|
+
from probabilisticnn.base.utils import cast_to_dtype
|
|
11
|
+
from probabilisticnn.base.utils import validate_backend
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class GRNN(RegressorMixin, BaseEstimator):
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
bandwidth=1.0,
|
|
19
|
+
kernel="gaussian",
|
|
20
|
+
backend="numpy",
|
|
21
|
+
compute_dtype="auto",
|
|
22
|
+
normalize=False,
|
|
23
|
+
) -> None:
|
|
24
|
+
self.bandwidth = bandwidth
|
|
25
|
+
self.kernel = kernel
|
|
26
|
+
self.backend = backend
|
|
27
|
+
self.compute_dtype = compute_dtype
|
|
28
|
+
self.normalize = normalize
|
|
29
|
+
|
|
30
|
+
def fit(self, X, y):
|
|
31
|
+
validate_backend(self.backend)
|
|
32
|
+
X, y = validate_data(self, X, y)
|
|
33
|
+
X = cast_to_dtype(X, self.compute_dtype)
|
|
34
|
+
y = cast_to_dtype(y, self.compute_dtype)
|
|
35
|
+
self.bandwidth_ = cast_to_dtype(self.bandwidth, self.compute_dtype)
|
|
36
|
+
|
|
37
|
+
self.pattern_layer_ = PatternLayer(
|
|
38
|
+
self.bandwidth_,
|
|
39
|
+
self.kernel,
|
|
40
|
+
normalize=self.normalize,
|
|
41
|
+
backend=self.backend,
|
|
42
|
+
).fit(X)
|
|
43
|
+
|
|
44
|
+
self.summation_layer_ = SummationLayer().fit(y)
|
|
45
|
+
|
|
46
|
+
return self
|
|
47
|
+
|
|
48
|
+
def predict(self, X):
|
|
49
|
+
check_is_fitted(self, ["pattern_layer_", "summation_layer_"])
|
|
50
|
+
X = validate_data(self, X, reset=False)
|
|
51
|
+
X = cast_to_dtype(X, self.compute_dtype)
|
|
52
|
+
|
|
53
|
+
if self.backend == "numba":
|
|
54
|
+
from probabilisticnn.numba_backend import grnn_jit_inference
|
|
55
|
+
|
|
56
|
+
X_transformed = normalize_l2(X) if self.pattern_layer_.normalize else X
|
|
57
|
+
out = grnn_jit_inference(
|
|
58
|
+
kernel=self.kernel,
|
|
59
|
+
X=X_transformed,
|
|
60
|
+
W=self.pattern_layer_.patterns_,
|
|
61
|
+
y=self.summation_layer_.y_,
|
|
62
|
+
bandwidth=self.pattern_layer_.bandwidth_,
|
|
63
|
+
bandwidth_sharing="scalar",
|
|
64
|
+
normalized=self.pattern_layer_.normalize,
|
|
65
|
+
)
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
K = self.pattern_layer_.transform(X)
|
|
69
|
+
out = self.summation_layer_.transform(K)
|
|
70
|
+
return out
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class AdaptiveGRNN(GRNN):
|
|
74
|
+
|
|
75
|
+
bandwidth_sharing = "per_feature"
|
|
76
|
+
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
kernel="gaussian",
|
|
80
|
+
loss="mse",
|
|
81
|
+
max_iter=100,
|
|
82
|
+
solver="auto",
|
|
83
|
+
solver_options=None,
|
|
84
|
+
normalize=False,
|
|
85
|
+
backend="numpy",
|
|
86
|
+
compute_dtype="auto",
|
|
87
|
+
) -> None:
|
|
88
|
+
self.loss = loss
|
|
89
|
+
self.kernel = kernel
|
|
90
|
+
self.max_iter = max_iter
|
|
91
|
+
self.normalize = normalize
|
|
92
|
+
self.solver = solver
|
|
93
|
+
self.solver_options = solver_options
|
|
94
|
+
self.backend = backend
|
|
95
|
+
self.compute_dtype = compute_dtype
|
|
96
|
+
|
|
97
|
+
def fit(self, X, y):
|
|
98
|
+
validate_backend(self.backend)
|
|
99
|
+
X, y = validate_data(self, X, y)
|
|
100
|
+
X = cast_to_dtype(X, self.compute_dtype)
|
|
101
|
+
y = cast_to_dtype(y, self.compute_dtype)
|
|
102
|
+
|
|
103
|
+
self.pattern_layer_ = AdaptivePatternLayer(
|
|
104
|
+
kernel=self.kernel,
|
|
105
|
+
bandwidth_sharing=self.bandwidth_sharing,
|
|
106
|
+
normalize=self.normalize,
|
|
107
|
+
backend=self.backend,
|
|
108
|
+
compute_dtype=self.compute_dtype,
|
|
109
|
+
).fit(X)
|
|
110
|
+
self.summation_layer_ = SummationLayer().fit(y)
|
|
111
|
+
self.optimizer_ = BandwidthOptimizer(
|
|
112
|
+
model=self,
|
|
113
|
+
loss=self.loss,
|
|
114
|
+
max_iter=self.max_iter,
|
|
115
|
+
solver=self.solver,
|
|
116
|
+
solver_options=self.solver_options,
|
|
117
|
+
).optimize()
|
|
118
|
+
self.bandwidth_ = self.optimizer_.bandwidth_
|
|
119
|
+
self.n_iter_ = self.optimizer_.n_iter_
|
|
120
|
+
self.converged_ = self.optimizer_.converged_
|
|
121
|
+
return self
|
|
122
|
+
|
|
123
|
+
def predict(self, X):
|
|
124
|
+
check_is_fitted(self, ["bandwidth_", "pattern_layer_", "summation_layer_", "optimizer_"])
|
|
125
|
+
X = validate_data(self, X, reset=False)
|
|
126
|
+
X = cast_to_dtype(X, self.compute_dtype)
|
|
127
|
+
|
|
128
|
+
if self.backend == "numba":
|
|
129
|
+
from probabilisticnn.numba_backend import grnn_jit_inference
|
|
130
|
+
X_transformed = normalize_l2(X) if self.pattern_layer_.normalize else X
|
|
131
|
+
bandwidth = self.pattern_layer_._prepare_bandwidth(self.pattern_layer_.bandwidth_)
|
|
132
|
+
out = grnn_jit_inference(
|
|
133
|
+
kernel=self.kernel,
|
|
134
|
+
X=X_transformed,
|
|
135
|
+
W=self.pattern_layer_.patterns_,
|
|
136
|
+
y=self.summation_layer_.y_,
|
|
137
|
+
bandwidth=bandwidth,
|
|
138
|
+
bandwidth_sharing=self.pattern_layer_.bandwidth_sharing,
|
|
139
|
+
normalized=self.normalize,
|
|
140
|
+
)
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
K = self.pattern_layer_.transform(X)
|
|
144
|
+
out = self.summation_layer_.transform(K)
|
|
145
|
+
return out
|
|
146
|
+
|
|
147
|
+
def _forward_train(self, bandwidth = None):
|
|
148
|
+
K_loo = self.pattern_layer_._loo(bandwidth)
|
|
149
|
+
out = self.summation_layer_.transform(K_loo)
|
|
150
|
+
return out
|
|
151
|
+
|
|
152
|
+
def grad(self, X, y, bandwidth=None, loo=False, K=None):
|
|
153
|
+
"""Compute gradient of the models function.
|
|
154
|
+
returns shape (n_samples, n_features)
|
|
155
|
+
"""
|
|
156
|
+
if K is not None:
|
|
157
|
+
X_for_grad = self.pattern_layer_.patterns_
|
|
158
|
+
elif loo:
|
|
159
|
+
X_for_grad = self.pattern_layer_.patterns_
|
|
160
|
+
K = self.pattern_layer_._loo(bandwidth)
|
|
161
|
+
else:
|
|
162
|
+
X_for_grad = X
|
|
163
|
+
K = self.pattern_layer_.transform(X)
|
|
164
|
+
|
|
165
|
+
pred = self.summation_layer_.transform(K) # shape (n_samples,)
|
|
166
|
+
|
|
167
|
+
K_sum = K.sum(axis=1, keepdims=True)
|
|
168
|
+
|
|
169
|
+
w = np.divide(
|
|
170
|
+
K,
|
|
171
|
+
K_sum,
|
|
172
|
+
out=np.zeros_like(K),
|
|
173
|
+
where=K_sum != 0,
|
|
174
|
+
) # shape (n_samples, n_patterns)
|
|
175
|
+
|
|
176
|
+
y_patterns = self.summation_layer_.y_ # shape (n_patterns,)
|
|
177
|
+
|
|
178
|
+
# coef[i, c] = p_ic * (y_c - f_i)
|
|
179
|
+
coef = w * (y_patterns[None, :] - pred[:, None])
|
|
180
|
+
|
|
181
|
+
if loo:
|
|
182
|
+
if K.shape[0] != K.shape[1]:
|
|
183
|
+
raise ValueError("LOO gradient expects square K: n_samples == n_patterns.")
|
|
184
|
+
idx = np.arange(K.shape[0])
|
|
185
|
+
coef[idx, idx] = 0.0
|
|
186
|
+
|
|
187
|
+
if bandwidth is None:
|
|
188
|
+
bandwidth = self.pattern_layer_.bandwidth_params
|
|
189
|
+
|
|
190
|
+
# chunked computation to avoid materialising (n_samples, n_patterns, n_features).
|
|
191
|
+
from probabilisticnn.base.utils import _log_grad_block_size
|
|
192
|
+
n_samples = X_for_grad.shape[0]
|
|
193
|
+
n_patterns = self.pattern_layer_.patterns_.shape[0]
|
|
194
|
+
n_features = X_for_grad.shape[1]
|
|
195
|
+
block = _log_grad_block_size(n_samples, n_patterns, n_features)
|
|
196
|
+
result = np.empty((n_samples, n_features), dtype=X_for_grad.dtype)
|
|
197
|
+
for start in range(0, n_samples, block):
|
|
198
|
+
end = min(start + block, n_samples)
|
|
199
|
+
lg = self.pattern_layer_.kernel_.log_grad(
|
|
200
|
+
X_for_grad[start:end],
|
|
201
|
+
self.pattern_layer_.patterns_,
|
|
202
|
+
bandwidth=bandwidth,
|
|
203
|
+
bandwidth_sharing=self.pattern_layer_.bandwidth_sharing,
|
|
204
|
+
normalized=self.pattern_layer_.normalize,
|
|
205
|
+
)
|
|
206
|
+
result[start:end] = np.einsum("ic,ick->ik", coef[start:end], lg)
|
|
207
|
+
return result
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
class SummationLayer:
|
|
4
|
+
|
|
5
|
+
def fit(self, y):
|
|
6
|
+
self.y_ = y
|
|
7
|
+
return self
|
|
8
|
+
|
|
9
|
+
def transform(self, K):
|
|
10
|
+
denom = np.sum(K, axis=1)
|
|
11
|
+
nom = np.matmul(K, self.y_)
|
|
12
|
+
out = np.divide(nom, denom, out=np.zeros_like(nom, dtype=K.dtype), where=denom > 0)
|
|
13
|
+
return out
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Optional numba-backed inference for ProbabilisticNN."""
|
|
2
|
+
|
|
3
|
+
from probabilisticnn.numba_backend.inference import pnn_jit_inference
|
|
4
|
+
from probabilisticnn.numba_backend.inference import grnn_jit_inference
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"pnn_jit_inference",
|
|
8
|
+
"grnn_jit_inference",
|
|
9
|
+
]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from probabilisticnn.numba_backend.kernels import resolve_matrix_kernel
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def grnn_jit_inference(
|
|
7
|
+
kernel: str,
|
|
8
|
+
X: np.ndarray,
|
|
9
|
+
W: np.ndarray,
|
|
10
|
+
y: np.ndarray,
|
|
11
|
+
bandwidth,
|
|
12
|
+
bandwidth_sharing: str,
|
|
13
|
+
normalized: bool = False,
|
|
14
|
+
):
|
|
15
|
+
"""Compute GRNN output with the numba kernel backend.
|
|
16
|
+
|
|
17
|
+
Mirrors the numpy path (compute K, then reduce with BLAS @) for a fair
|
|
18
|
+
apples-to-apples comparison. Faster because fastmath enables FP rewrites
|
|
19
|
+
and JIT eliminates Python overhead.
|
|
20
|
+
"""
|
|
21
|
+
bandwidth_arr = np.asarray(bandwidth, dtype=X.dtype)
|
|
22
|
+
bandwidth_arg = bandwidth_arr[()] if bandwidth_sharing == "scalar" else bandwidth_arr
|
|
23
|
+
|
|
24
|
+
W_cast = np.asarray(W, dtype=X.dtype)
|
|
25
|
+
K = resolve_matrix_kernel(kernel, bandwidth_sharing)(X, W_cast, bandwidth_arg, normalized)
|
|
26
|
+
nom = K @ y
|
|
27
|
+
denom = K.sum(axis=1)
|
|
28
|
+
safe_denom = np.where(denom > 0, denom, np.ones_like(denom))
|
|
29
|
+
return np.where(denom > 0, nom / safe_denom, np.zeros_like(nom))
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from probabilisticnn.numba_backend.kernels import resolve_matrix_kernel
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def pnn_jit_inference(
|
|
7
|
+
kernel: str,
|
|
8
|
+
X: np.ndarray,
|
|
9
|
+
W: np.ndarray,
|
|
10
|
+
y_encoded: np.ndarray,
|
|
11
|
+
n_classes: int,
|
|
12
|
+
likelihood_multiplier: np.ndarray,
|
|
13
|
+
bandwidth,
|
|
14
|
+
bandwidth_sharing: str,
|
|
15
|
+
normalized: bool = False,
|
|
16
|
+
):
|
|
17
|
+
"""Compute PNN output with the numba kernel backend.
|
|
18
|
+
|
|
19
|
+
Mirrors the numpy path (compute K, then reduce with BLAS @) for a fair
|
|
20
|
+
apples-to-apples comparison. Faster because fastmath enables FP rewrites
|
|
21
|
+
and JIT eliminates Python overhead.
|
|
22
|
+
"""
|
|
23
|
+
likelihood_multiplier = np.asarray(likelihood_multiplier, dtype=X.dtype)
|
|
24
|
+
bandwidth_arr = np.asarray(bandwidth, dtype=X.dtype)
|
|
25
|
+
bandwidth_arg = bandwidth_arr[()] if bandwidth_sharing == "scalar" else bandwidth_arr
|
|
26
|
+
|
|
27
|
+
n_patterns = W.shape[0]
|
|
28
|
+
class_mask = np.zeros((n_patterns, n_classes), dtype=X.dtype)
|
|
29
|
+
class_mask[np.arange(n_patterns), y_encoded] = 1.0
|
|
30
|
+
|
|
31
|
+
W_cast = np.asarray(W, dtype=X.dtype)
|
|
32
|
+
K = resolve_matrix_kernel(kernel, bandwidth_sharing)(X, W_cast, bandwidth_arg, normalized)
|
|
33
|
+
f = K @ class_mask
|
|
34
|
+
return np.argmax(f * likelihood_multiplier, axis=1).astype(np.int64)
|