quantatlas 0.2.0__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.
consona/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Consona regression estimators."""
2
+ from ._core import FixedConsonaRegressor
3
+ from ._selection import ConsonaRegressor
4
+
5
+ __version__ = "0.2.0"
6
+ __all__ = ["ConsonaRegressor", "FixedConsonaRegressor"]
consona/_core.py ADDED
@@ -0,0 +1,270 @@
1
+ """Fit Consona with specified regularization and basis settings."""
2
+
3
+ from numbers import Integral, Real
4
+ import warnings
5
+
6
+ import numpy as np
7
+ from scipy.linalg import cho_factor, cho_solve
8
+ from scipy.spatial.distance import cdist
9
+ from sklearn.base import BaseEstimator, RegressorMixin
10
+ from sklearn.linear_model import Ridge
11
+ from sklearn.preprocessing import SplineTransformer, StandardScaler
12
+ from sklearn.utils.validation import check_is_fitted, validate_data
13
+
14
+ from ._prediction import selected_design
15
+
16
+
17
+ class FixedConsonaRegressor(RegressorMixin, BaseEstimator):
18
+ """Fit an affine trend and a screened nonlinear correction.
19
+
20
+ The correction uses splines, quadratic products, and radial features.
21
+ Residual associations across three partitions set each feature's additional
22
+ ridge penalty. Set shrinkage=0 for uniform nonlinear shrinkage.
23
+
24
+ Parameters
25
+ ----------
26
+ alpha : float, default=0.01
27
+ Base nonlinear ridge penalty. The affine slopes use 0.01 * alpha.
28
+ shrinkage : float, default=1.0
29
+ Multiplier for the agreement penalty.
30
+ bandwidth : float, default=1.0
31
+ Width parameter for the Gaussian radial features.
32
+ max_features : int, default=128
33
+ Maximum number of nonlinear features to retain.
34
+ n_knots : int, default=8
35
+ Minimum number of knots in each coordinate spline.
36
+ n_centers : int, default=48
37
+ Maximum number of training rows to use as radial centers.
38
+ mode : {"marginal", "replicated"}, default="marginal"
39
+ Rank nonlinear features by their squared mean residual association or
40
+ by their positive cross-partition association.
41
+ taper : bool, default=True
42
+ Attenuate the nonlinear correction outside the training box.
43
+ random_state : int or None, default=2718
44
+ Seed for radial centers and training partitions.
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ alpha=0.01,
50
+ shrinkage=1.0,
51
+ bandwidth=1.0,
52
+ max_features=128,
53
+ n_knots=8,
54
+ n_centers=48,
55
+ mode="marginal",
56
+ taper=True,
57
+ random_state=2718,
58
+ ):
59
+ self.alpha = alpha
60
+ self.shrinkage = shrinkage
61
+ self.bandwidth = bandwidth
62
+ self.max_features = max_features
63
+ self.n_knots = n_knots
64
+ self.n_centers = n_centers
65
+ self.mode = mode
66
+ self.taper = taper
67
+ self.random_state = random_state
68
+
69
+ def _raw(self, z):
70
+ quadratic = z[:, self.pair_i_] * z[:, self.pair_j_]
71
+ radial = np.exp(
72
+ -cdist(z, self.centers_, "sqeuclidean")
73
+ / (self.bandwidth * self.n_features_in_)
74
+ )
75
+ return np.column_stack((self.splines_.transform(z), quadratic, radial))
76
+
77
+ def _design(self, z):
78
+ a = np.column_stack((np.ones(len(z)), z))
79
+ if type(self)._raw is FixedConsonaRegressor._raw:
80
+ nonlinear = selected_design(self, z, a)
81
+ else:
82
+ # Private basis subclasses can define different bank layouts.
83
+ bank = (self._raw(z) - a @ self.affine_projection_) / self.bank_scale_
84
+ nonlinear = bank[:, self.selected_]
85
+ if self.taper:
86
+ outside = np.maximum(0.0, np.maximum(z - self.upper_, self.lower_ - z))
87
+ weight = (1 + 4 * np.sum(outside * outside, axis=1)) ** -2
88
+ nonlinear *= weight[:, None]
89
+ return np.column_stack((a, nonlinear))
90
+
91
+ def _prepare(self, X, y):
92
+ X, y = validate_data(
93
+ self, X, y, dtype=float, y_numeric=True, ensure_min_samples=24
94
+ )
95
+ self.linear_fallback_ = False
96
+ self.scaler_ = StandardScaler().fit(X)
97
+ z = self.scaler_.transform(X)
98
+ self.lower_, self.upper_ = z.min(axis=0), z.max(axis=0)
99
+ a = np.column_stack((np.ones(len(z)), z))
100
+ rng = np.random.default_rng(self.random_state)
101
+ self.pair_i_, self.pair_j_ = np.triu_indices(z.shape[1])
102
+ self.centers_ = z[
103
+ rng.choice(len(z), min(self.n_centers, len(z)), replace=False)
104
+ ].copy()
105
+ self.effective_knots_ = max(self.n_knots, min(24, 48 // z.shape[1]))
106
+ self.splines_ = SplineTransformer(
107
+ n_knots=self.effective_knots_,
108
+ degree=3,
109
+ include_bias=False,
110
+ extrapolation="linear",
111
+ ).fit(z)
112
+ width = self.splines_.n_features_out_ + len(self.pair_i_) + len(self.centers_)
113
+ if 8 * len(z) * width >= 512 * 1024**2:
114
+ warnings.warn(
115
+ "Consona's raw training bank alone exceeds 512 MiB. "
116
+ "Consider fewer predictors or a smaller training window.",
117
+ UserWarning,
118
+ stacklevel=2,
119
+ )
120
+ bank = self._raw(z)
121
+ self.affine_projection_ = np.linalg.lstsq(a, bank, rcond=1e-9)[0]
122
+ bank -= a @ self.affine_projection_
123
+ self.bank_scale_ = np.maximum(bank.std(axis=0), 0.02)
124
+ bank /= self.bank_scale_
125
+ # Fit the affine nuisance terms separately within each partition.
126
+ pieces = np.array_split(rng.permutation(len(z)), 3)
127
+ moments = []
128
+ for indices in pieces:
129
+ affine = a[indices]
130
+ residual = (
131
+ y[indices] - affine @ np.linalg.lstsq(affine, y[indices], rcond=1e-9)[0]
132
+ )
133
+ moments.append(bank[indices].T @ residual / len(indices))
134
+ moments = np.asarray(moments)
135
+ k = len(moments)
136
+ energy_sum = np.sum(moments * moments, axis=0)
137
+ cross_sum = np.sum(moments, axis=0) ** 2 - energy_sum
138
+ self.cross_energy_ = cross_sum / (k * (k - 1))
139
+ self.agreement_ = np.clip(
140
+ cross_sum / np.maximum((k - 1) * energy_sum, 1e-25), 0.0, 1.0
141
+ )
142
+ if self.mode == "replicated":
143
+ strength = np.maximum(self.cross_energy_, 0.0)
144
+ elif self.mode == "marginal":
145
+ strength = np.mean(moments, axis=0) ** 2
146
+ else:
147
+ raise ValueError("mode must be replicated or marginal")
148
+ count = min(int(self.max_features), max(1, len(z) // 2), len(strength))
149
+ indices = np.argsort(-strength, kind="stable")[:count]
150
+ self.selected_ = indices[
151
+ strength[indices] > max(1e-25, float(np.max(strength)) * 1e-12)
152
+ ]
153
+ self.n_selected_features_ = len(self.selected_)
154
+ self.target_center_ = float(np.mean(y))
155
+ self.target_scale_ = max(float(np.std(y)), 1e-12)
156
+ design = np.column_stack((a, bank[:, self.selected_]))
157
+ target = (y - self.target_center_) / self.target_scale_
158
+ self.gram_ = design.T @ design / len(z)
159
+ self.rhs_ = design.T @ target / len(z)
160
+ self.ridge_diagonal_ = np.r_[
161
+ 0.0, np.full(z.shape[1], 0.01), np.ones(len(self.selected_))
162
+ ]
163
+ reliability = self.agreement_[self.selected_]
164
+ self.extra_penalty_ = np.r_[
165
+ np.zeros(a.shape[1]), (1 - reliability) / (0.1 + reliability)
166
+ ]
167
+ return self
168
+
169
+ def _solve(self, alpha, shrinkage):
170
+ diagonal = (
171
+ alpha * (self.ridge_diagonal_ + shrinkage * self.extra_penalty_) + 1e-10
172
+ )
173
+ return cho_solve(cho_factor(self.gram_ + np.diag(diagonal)), self.rhs_)
174
+
175
+ def _validate_hyperparameters(self):
176
+ for name, value, allow_zero in (
177
+ ("alpha", self.alpha, False),
178
+ ("shrinkage", self.shrinkage, True),
179
+ ("bandwidth", self.bandwidth, False),
180
+ ):
181
+ if (
182
+ not isinstance(value, Real)
183
+ or isinstance(value, bool)
184
+ or not np.isfinite(value)
185
+ or (value < 0 if allow_zero else value <= 0)
186
+ ):
187
+ raise ValueError(
188
+ f"{name} must be a finite {'nonnegative' if allow_zero else 'positive'} number"
189
+ )
190
+ for name, value, minimum in (
191
+ ("max_features", self.max_features, 1),
192
+ ("n_knots", self.n_knots, 2),
193
+ ("n_centers", self.n_centers, 1),
194
+ ):
195
+ if (
196
+ not isinstance(value, Integral)
197
+ or isinstance(value, bool)
198
+ or value < minimum
199
+ ):
200
+ raise ValueError(f"{name} must be an integer >= {minimum}")
201
+ if self.mode not in ("marginal", "replicated"):
202
+ raise ValueError("mode must be marginal or replicated")
203
+ if not isinstance(self.taper, (bool, np.bool_)):
204
+ raise ValueError("taper must be boolean")
205
+ if self.random_state is not None and (
206
+ not isinstance(self.random_state, Integral)
207
+ or isinstance(self.random_state, bool)
208
+ or self.random_state < 0
209
+ ):
210
+ raise ValueError("random_state must be a nonnegative integer or None")
211
+
212
+ def fit(self, X, y):
213
+ """Fit to a dense numerical feature matrix and a single response."""
214
+ self._validate_hyperparameters()
215
+ X, y = validate_data(
216
+ self, X, y, dtype=float, y_numeric=True, ensure_min_samples=1
217
+ )
218
+ names = getattr(self, "feature_names_in_", None)
219
+ self.linear_fallback_ = len(y) < 24
220
+ if self.linear_fallback_:
221
+ self.scaler_ = StandardScaler().fit(X)
222
+ self.fallback_model_ = Ridge(alpha=1.0).fit(self.scaler_.transform(X), y)
223
+ self.n_selected_features_ = 0
224
+ self.coef_ = self.fallback_model_.coef_.copy()
225
+ return self
226
+ self._prepare(X, y)
227
+ if names is not None:
228
+ self.feature_names_in_ = names
229
+ self.coef_ = self._solve(self.alpha, self.shrinkage)
230
+ return self
231
+
232
+ def _query(self, X):
233
+ check_is_fitted(self, "coef_")
234
+ return validate_data(self, X, reset=False, dtype=float)
235
+
236
+ def predict(self, X):
237
+ """Predict the response for each row in X."""
238
+ X = self._query(X)
239
+ prediction = np.empty(len(X))
240
+ for start in range(0, len(X), 2048):
241
+ batch = X[start : start + 2048]
242
+ z = self.scaler_.transform(batch)
243
+ if self.linear_fallback_:
244
+ prediction[start : start + len(batch)] = self.fallback_model_.predict(z)
245
+ else:
246
+ prediction[
247
+ start : start + len(batch)
248
+ ] = self.target_center_ + self.target_scale_ * (
249
+ self._design(z) @ self.coef_
250
+ )
251
+ return prediction
252
+
253
+ def predict_components(self, X):
254
+ """Return the affine prediction and nonlinear correction in target units."""
255
+ X = self._query(X)
256
+ if self.linear_fallback_:
257
+ return self.predict(X), np.zeros(len(X))
258
+ affine, nonlinear = np.empty(len(X)), np.empty(len(X))
259
+ split = self.n_features_in_ + 1
260
+ for start in range(0, len(X), 2048):
261
+ z = self.scaler_.transform(X[start : start + 2048])
262
+ design = self._design(z)
263
+ end = start + len(z)
264
+ affine[start:end] = self.target_center_ + self.target_scale_ * (
265
+ design[:, :split] @ self.coef_[:split]
266
+ )
267
+ nonlinear[start:end] = self.target_scale_ * (
268
+ design[:, split:] @ self.coef_[split:]
269
+ )
270
+ return affine, nonlinear
consona/_prediction.py ADDED
@@ -0,0 +1,27 @@
1
+ """Query only the retained quadratic and radial columns."""
2
+
3
+ import numpy as np
4
+ from scipy.spatial.distance import cdist
5
+
6
+
7
+ def selected_design(model, z, affine):
8
+ """Evaluate retained columns in their fitted order."""
9
+ indices = model.selected_
10
+ n_spline = model.splines_.n_features_out_
11
+ radial_start = n_spline + len(model.pair_i_)
12
+ bank = np.empty((len(z), len(indices)))
13
+ spline = indices < n_spline
14
+ pair = (indices >= n_spline) & (indices < radial_start)
15
+ radial = indices >= radial_start
16
+ if spline.any():
17
+ bank[:, spline] = model.splines_.transform(z)[:, indices[spline]]
18
+ if pair.any():
19
+ pairs = indices[pair] - n_spline
20
+ bank[:, pair] = z[:, model.pair_i_[pairs]] * z[:, model.pair_j_[pairs]]
21
+ if radial.any():
22
+ centers = model.centers_[indices[radial] - radial_start]
23
+ bank[:, radial] = np.exp(
24
+ -cdist(z, centers, "sqeuclidean") / (model.bandwidth * model.n_features_in_)
25
+ )
26
+ bank -= affine @ model.affine_projection_[:, indices]
27
+ return bank / model.bank_scale_[indices]
consona/_selection.py ADDED
@@ -0,0 +1,211 @@
1
+ """Cross-validated regularization for Consona."""
2
+
3
+ from numbers import Integral, Real
4
+
5
+ import numpy as np
6
+ from sklearn.base import BaseEstimator, RegressorMixin
7
+ from sklearn.metrics import mean_squared_error
8
+ from sklearn.model_selection import GroupKFold, KFold
9
+ from sklearn.utils.validation import check_is_fitted, validate_data
10
+
11
+ from ._core import FixedConsonaRegressor
12
+
13
+
14
+ class ConsonaRegressor(RegressorMixin, BaseEstimator):
15
+ """Select Consona penalties and radial bandwidth by cross-validation.
16
+
17
+ An integer cv uses shuffled folds, grouped when fit receives groups.
18
+ For forecasting, pass a chronological splitter that respects when labels
19
+ become available. Each fold fits its own basis and screen.
20
+
21
+ Parameters
22
+ ----------
23
+ cv : int, splitter or iterable of index pairs, default=3
24
+ Inner splits for choosing the configuration with lowest mean fold MSE.
25
+ alphas, shrinkages, bandwidths : sequences of float
26
+ Candidate values for the corresponding FixedConsonaRegressor settings.
27
+ max_features, n_knots, n_centers, mode, taper, random_state
28
+ Passed to FixedConsonaRegressor.
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ cv=3,
34
+ alphas=(1e-5, 0.001, 0.1, 10.0),
35
+ shrinkages=(0.0, 1.0, 10.0, 1e6),
36
+ bandwidths=(0.3, 3.0),
37
+ max_features=128,
38
+ n_knots=8,
39
+ n_centers=48,
40
+ mode="marginal",
41
+ taper=True,
42
+ random_state=2718,
43
+ ):
44
+ self.cv = cv
45
+ self.alphas = alphas
46
+ self.shrinkages = shrinkages
47
+ self.bandwidths = bandwidths
48
+ self.max_features = max_features
49
+ self.n_knots = n_knots
50
+ self.n_centers = n_centers
51
+ self.mode = mode
52
+ self.taper = taper
53
+ self.random_state = random_state
54
+
55
+ def _base(self, **params):
56
+ return FixedConsonaRegressor(
57
+ max_features=self.max_features,
58
+ n_knots=self.n_knots,
59
+ n_centers=self.n_centers,
60
+ mode=self.mode,
61
+ taper=self.taper,
62
+ random_state=self.random_state,
63
+ **params,
64
+ )
65
+
66
+ def fit(self, X, y, groups=None):
67
+ """Tune on the supplied data and refit the selected configuration."""
68
+ X, y = validate_data(
69
+ self, X, y, dtype=float, y_numeric=True, ensure_min_samples=1
70
+ )
71
+ for name, values, zero in (
72
+ ("alphas", self.alphas, False),
73
+ ("shrinkages", self.shrinkages, True),
74
+ ("bandwidths", self.bandwidths, False),
75
+ ):
76
+ if (
77
+ not isinstance(values, (list, tuple, np.ndarray))
78
+ or np.ndim(values) != 1
79
+ or len(values) == 0
80
+ ):
81
+ raise ValueError(f"{name} must be a nonempty sequence")
82
+ if any(
83
+ not isinstance(v, Real)
84
+ or isinstance(v, bool)
85
+ or not np.isfinite(v)
86
+ or (v < 0 if zero else v <= 0)
87
+ for v in values
88
+ ):
89
+ raise ValueError(f"{name} contains invalid values")
90
+ self._base()._validate_hyperparameters()
91
+ if (
92
+ isinstance(self.cv, Integral)
93
+ and not isinstance(self.cv, bool)
94
+ and self.cv < 2
95
+ ):
96
+ raise ValueError("cv must be at least 2")
97
+ if isinstance(self.cv, bool) or not (
98
+ isinstance(self.cv, Integral)
99
+ or hasattr(self.cv, "split")
100
+ or hasattr(self.cv, "__iter__")
101
+ ):
102
+ raise ValueError(
103
+ "cv must be an integer, splitter, or iterable of index pairs"
104
+ )
105
+ if groups is not None:
106
+ groups = np.asarray(groups)
107
+ if groups.ndim != 1 or len(groups) != len(y):
108
+ raise ValueError(
109
+ "groups must be one-dimensional with one value per row"
110
+ )
111
+ self.cv_results_ = []
112
+ if len(y) < 24:
113
+ self.best_params_ = dict(alpha=10.0, shrinkage=1e6, bandwidth=1.0)
114
+ self.selection_status_ = (
115
+ "fewer than 24 rows: standardized ridge fallback (alpha=1)"
116
+ )
117
+ self.regressor_ = self._base(**self.best_params_).fit(X, y)
118
+ self.n_selected_features_ = 0
119
+ self.linear_fallback_ = True
120
+ return self
121
+ if isinstance(self.cv, Integral):
122
+ splitter = (
123
+ KFold(self.cv, shuffle=True, random_state=self.random_state)
124
+ if groups is None
125
+ else GroupKFold(self.cv, shuffle=True, random_state=self.random_state)
126
+ )
127
+ folds = list(splitter.split(X, y, groups))
128
+ elif hasattr(self.cv, "split"):
129
+ folds = list(self.cv.split(X, y, groups))
130
+ else:
131
+ try:
132
+ folds = list(self.cv)
133
+ except TypeError as exc:
134
+ raise ValueError(
135
+ "cv must be an integer, splitter, or iterable of index pairs"
136
+ ) from exc
137
+ if not folds:
138
+ raise ValueError("cv must contain at least one split")
139
+ for train, valid in folds:
140
+ train, valid = np.asarray(train), np.asarray(valid)
141
+ if train.ndim != 1 or valid.ndim != 1 or len(train) == 0 or len(valid) == 0:
142
+ raise ValueError(
143
+ "Each validation split needs nonempty one-dimensional indices"
144
+ )
145
+ if not np.issubdtype(train.dtype, np.integer) or not np.issubdtype(
146
+ valid.dtype, np.integer
147
+ ):
148
+ raise ValueError("Validation indices must be integers")
149
+ if (
150
+ train.min() < 0
151
+ or valid.min() < 0
152
+ or train.max() >= len(y)
153
+ or valid.max() >= len(y)
154
+ ):
155
+ raise ValueError("Validation indices are out of range")
156
+ if np.intersect1d(train, valid).size:
157
+ raise ValueError("Training and validation indices must not overlap")
158
+ if groups is not None and np.intersect1d(groups[train], groups[valid]).size:
159
+ raise ValueError("Groups overlap between training and validation")
160
+ if min(len(train) for train, valid in folds) < 24:
161
+ self.best_params_ = dict(alpha=10.0, shrinkage=1e6, bandwidth=1.0)
162
+ self.selection_status_ = (
163
+ "short-sample conservative settings; no valid inner CV"
164
+ )
165
+ else:
166
+ losses = {}
167
+ for bandwidth in self.bandwidths:
168
+ for train, valid in folds:
169
+ model = self._base(bandwidth=bandwidth)._prepare(X[train], y[train])
170
+ design = model._design(model.scaler_.transform(X[valid]))
171
+ for alpha in self.alphas:
172
+ for shrinkage in self.shrinkages:
173
+ coef = model._solve(alpha, shrinkage)
174
+ pred = model.target_center_ + model.target_scale_ * (
175
+ design @ coef
176
+ )
177
+ losses.setdefault((bandwidth, alpha, shrinkage), []).append(
178
+ mean_squared_error(y[valid], pred)
179
+ )
180
+ best = min(losses, key=lambda key: (np.mean(losses[key]), key))
181
+ bandwidth, alpha, shrinkage = best
182
+ self.best_params_ = dict(
183
+ alpha=alpha, shrinkage=shrinkage, bandwidth=bandwidth
184
+ )
185
+ self.selection_status_ = "training-only cross-validation"
186
+ self.cv_results_ = [
187
+ dict(
188
+ bandwidth=b,
189
+ alpha=a,
190
+ shrinkage=s,
191
+ mean_mse=float(np.mean(loss)),
192
+ fold_mse=[float(v) for v in loss],
193
+ )
194
+ for (b, a, s), loss in losses.items()
195
+ ]
196
+ self.regressor_ = self._base(**self.best_params_).fit(X, y)
197
+ self.n_selected_features_ = self.regressor_.n_selected_features_
198
+ self.linear_fallback_ = self.regressor_.linear_fallback_
199
+ return self
200
+
201
+ def predict(self, X):
202
+ """Predict the response for each row in X."""
203
+ check_is_fitted(self, "regressor_")
204
+ X = validate_data(self, X, reset=False, dtype=float)
205
+ return self.regressor_.predict(X)
206
+
207
+ def predict_components(self, X):
208
+ """Return the fitted affine prediction and tapered nonlinear correction."""
209
+ check_is_fitted(self, "regressor_")
210
+ X = validate_data(self, X, reset=False, dtype=float)
211
+ return self.regressor_.predict_components(X)
quantatlas/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """QuantAtlas estimators for regression and forecasting."""
2
+
3
+ from consona import ConsonaRegressor, FixedConsonaRegressor
4
+
5
+ __version__ = "0.2.0"
6
+ __all__ = ["ConsonaRegressor", "FixedConsonaRegressor"]
@@ -0,0 +1,204 @@
1
+ """Experimental penalties and partitioning schemes for Consona.
2
+
3
+ The evidence option applies a monotone remapping of the original agreement
4
+ score within each partition.
5
+ """
6
+
7
+ import numpy as np
8
+ from scipy.linalg import cho_factor, cho_solve
9
+ from sklearn.base import BaseEstimator, RegressorMixin
10
+ from sklearn.linear_model import Ridge
11
+ from sklearn.preprocessing import StandardScaler
12
+ from sklearn.pipeline import make_pipeline
13
+ from sklearn.utils.validation import check_is_fitted, validate_data
14
+
15
+ from consona import FixedConsonaRegressor
16
+
17
+
18
+ def agreement(moments):
19
+ """Bounded agreement per column of a partition-by-feature moment matrix."""
20
+ count = moments.shape[0]
21
+ energy = np.square(moments).sum(axis=0)
22
+ cross = np.square(moments.sum(axis=0)) - energy
23
+ return np.clip(cross / np.maximum((count - 1) * energy, 1e-25), 0.0, 1.0)
24
+
25
+
26
+ def partition_weights(model, X, y, kind, partition, blocks, repeats, seed, purge=0):
27
+ """Compute experimental weights on the frozen screen, using training rows."""
28
+ dimensions = model.n_features_in_ + 1
29
+ count = model.n_selected_features_
30
+ if kind == "uniform" or count == 0:
31
+ return np.ones(count)
32
+ if kind == "pilot":
33
+ diagonal = 0.01 * model.ridge_diagonal_ + 1e-9
34
+ coefficients = cho_solve(
35
+ cho_factor(model.gram_ + np.diag(diagonal)), model.rhs_
36
+ )
37
+ magnitude = np.abs(coefficients[dimensions:])
38
+ magnitude /= max(float(np.median(magnitude)), 1e-10)
39
+ return np.clip((0.1 + magnitude) ** -2, 0.01, 100.0)
40
+ if partition == "reference" and kind == "agreement":
41
+ return model.extra_penalty_[dimensions:].copy()
42
+
43
+ design = model._design(model.scaler_.transform(X))
44
+ affine, bank = design[:, :dimensions], design[:, dimensions:]
45
+ rng = np.random.default_rng(seed)
46
+ weights = []
47
+ for _ in range(repeats if partition == "repeated" else 1):
48
+ order = np.arange(len(y)) if partition == "blocked" else rng.permutation(len(y))
49
+ parts = np.array_split(order, blocks)
50
+ if purge and partition == "blocked":
51
+ parts = [piece[:-purge] for piece in parts[:-1]] + parts[-1:]
52
+ moments = []
53
+ for piece in parts:
54
+ if len(piece) < 2:
55
+ raise ValueError(
56
+ "Each agreement partition needs at least two rows after purging"
57
+ )
58
+ trend = affine[piece]
59
+ coef = np.linalg.lstsq(trend, y[piece], rcond=1e-9)[0]
60
+ moments.append(bank[piece].T @ (y[piece] - trend @ coef) / len(piece))
61
+ moments = np.stack(moments)
62
+ score = agreement(moments)
63
+ if kind == "evidence":
64
+ signal = blocks * moments.mean(axis=0) ** 2
65
+ noise = moments.var(axis=0, ddof=1)
66
+ score = score * signal / np.maximum(signal + 4 * noise, 1e-25)
67
+ weights.append(1 - score if kind == "linear" else (1 - score) / (0.1 + score))
68
+ return np.mean(weights, axis=0)
69
+
70
+
71
+ def solve_independent(model, alpha_affine, alpha_nonlinear, alpha_agreement, weights):
72
+ """Solve the quadratic conditional on the prepared screened basis."""
73
+ diagonal = (
74
+ np.r_[
75
+ 0.0,
76
+ np.full(model.n_features_in_, alpha_affine),
77
+ alpha_nonlinear + alpha_agreement * weights,
78
+ ]
79
+ + 1e-10
80
+ )
81
+ return cho_solve(cho_factor(model.gram_ + np.diag(diagonal)), model.rhs_)
82
+
83
+
84
+ class ExperimentalConsonaRegressor(RegressorMixin, BaseEstimator):
85
+ """Fixed experimental penalties. Use an outer CV pipeline to tune them.
86
+
87
+ Blocked partitions interpret row order as time order. Purge is a row
88
+ count removed before each block boundary. Callers must verify maturity
89
+ using actual label timestamps for irregular series.
90
+ """
91
+
92
+ def __init__(
93
+ self,
94
+ alpha_affine=0.001,
95
+ alpha_nonlinear=0.1,
96
+ alpha_agreement=0.0,
97
+ penalty="uniform",
98
+ partition="reference",
99
+ n_partitions=3,
100
+ n_repeats=5,
101
+ purge=0,
102
+ bandwidth=1.0,
103
+ max_features=128,
104
+ taper=True,
105
+ random_state=2718,
106
+ ):
107
+ self.alpha_affine = alpha_affine
108
+ self.alpha_nonlinear = alpha_nonlinear
109
+ self.alpha_agreement = alpha_agreement
110
+ self.penalty = penalty
111
+ self.partition = partition
112
+ self.n_partitions = n_partitions
113
+ self.n_repeats = n_repeats
114
+ self.purge = purge
115
+ self.bandwidth = bandwidth
116
+ self.max_features = max_features
117
+ self.taper = taper
118
+ self.random_state = random_state
119
+
120
+ def fit(self, X, y):
121
+ """Fit the basis and apply the configured nonlinear penalty."""
122
+ self._validate()
123
+ X, y = validate_data(self, X, y, dtype=float, y_numeric=True)
124
+ self.linear_fallback_ = len(y) < 24
125
+ if self.linear_fallback_:
126
+ self.regressor_ = make_pipeline(StandardScaler(), Ridge(alpha=1.0)).fit(
127
+ X, y
128
+ )
129
+ self.n_selected_features_ = 0
130
+ self.agreement_weights_ = np.empty(0)
131
+ return self
132
+ model = FixedConsonaRegressor(
133
+ bandwidth=self.bandwidth,
134
+ max_features=self.max_features,
135
+ taper=self.taper,
136
+ random_state=self.random_state,
137
+ )
138
+ model._prepare(X, y)
139
+ weights = partition_weights(
140
+ model,
141
+ X,
142
+ y,
143
+ self.penalty,
144
+ self.partition,
145
+ self.n_partitions,
146
+ self.n_repeats,
147
+ self.random_state,
148
+ self.purge,
149
+ )
150
+ model.coef_ = solve_independent(
151
+ model,
152
+ self.alpha_affine,
153
+ self.alpha_nonlinear,
154
+ self.alpha_agreement,
155
+ weights,
156
+ )
157
+ self.regressor_ = model
158
+ self.agreement_weights_ = weights
159
+ self.n_selected_features_ = model.n_selected_features_
160
+ return self
161
+
162
+ def _validate(self):
163
+ for name in ("alpha_affine", "alpha_nonlinear", "alpha_agreement"):
164
+ value = getattr(self, name)
165
+ if (
166
+ not isinstance(value, (int, float, np.integer, np.floating))
167
+ or not np.isfinite(value)
168
+ or value < 0
169
+ ):
170
+ raise ValueError(f"{name} must be finite and nonnegative")
171
+ if self.penalty not in ("uniform", "pilot", "agreement", "linear", "evidence"):
172
+ raise ValueError("Unsupported penalty")
173
+ if self.partition not in ("reference", "random", "blocked", "repeated"):
174
+ raise ValueError("Unsupported partition")
175
+ for value, name, minimum in (
176
+ (self.n_partitions, "n_partitions", 2),
177
+ (self.n_repeats, "n_repeats", 1),
178
+ (self.purge, "purge", 0),
179
+ ):
180
+ if (
181
+ isinstance(value, bool)
182
+ or not isinstance(value, (int, np.integer))
183
+ or value < minimum
184
+ ):
185
+ raise ValueError(f"{name} must be an integer >= {minimum}")
186
+ if self.purge and self.partition != "blocked":
187
+ raise ValueError("Purging requires chronological blocked partitions")
188
+ if (
189
+ self.partition == "reference"
190
+ and self.penalty == "agreement"
191
+ and self.n_partitions != 3
192
+ ):
193
+ raise ValueError("The reference agreement uses three partitions")
194
+ FixedConsonaRegressor(
195
+ bandwidth=self.bandwidth,
196
+ max_features=self.max_features,
197
+ taper=self.taper,
198
+ random_state=self.random_state,
199
+ )._validate_hyperparameters()
200
+
201
+ def predict(self, X):
202
+ """Predict the response for each row in X."""
203
+ check_is_fitted(self, "regressor_")
204
+ return self.regressor_.predict(validate_data(self, X, reset=False, dtype=float))
@@ -0,0 +1,27 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Quant Atlas
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+ 3. Neither the name of the copyright holder nor the names of its contributors
15
+ may be used to endorse or promote products derived from this software without
16
+ specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25
+ AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.1
2
+ Name: quantatlas
3
+ Version: 0.2.0
4
+ Summary: QuantAtlas regression and forecasting library featuring Consona
5
+ Author: Quant Atlas
6
+ License: BSD-3-Clause
7
+ Project-URL: Quant Atlas, https://www.quant-atlas.com/
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/x-rst
14
+ License-File: LICENSE
15
+ Requires-Dist: numpy >=1.24
16
+ Requires-Dist: scipy >=1.10
17
+ Requires-Dist: scikit-learn >=1.7
18
+ Provides-Extra: benchmark
19
+ Requires-Dist: pandas >=2 ; extra == 'benchmark'
20
+ Requires-Dist: xgboost >=2 ; extra == 'benchmark'
21
+ Requires-Dist: catboost >=1.2 ; extra == 'benchmark'
22
+ Requires-Dist: matplotlib >=3.7 ; extra == 'benchmark'
23
+ Requires-Dist: psutil >=5 ; extra == 'benchmark'
24
+ Requires-Dist: xlrd >=2 ; extra == 'benchmark'
25
+ Provides-Extra: docs
26
+ Requires-Dist: sphinx >=7 ; extra == 'docs'
27
+ Requires-Dist: matplotlib >=3.7 ; extra == 'docs'
28
+ Provides-Extra: test
29
+ Requires-Dist: pytest >=7.4 ; extra == 'test'
30
+ Requires-Dist: pandas >=2 ; extra == 'test'
31
+ Requires-Dist: threadpoolctl >=3 ; extra == 'test'
32
+
33
+ QuantAtlas and Consona
34
+ ======================
35
+
36
+ Consona fits an affine trend and a nonlinear correction using dense
37
+ numerical inputs. It penalizes correction features using their residual
38
+ associations across training partitions. Outside the range observed
39
+ along each input coordinate, the correction fades toward zero.
40
+
41
+ Install the included wheel
42
+ --------------------------
43
+
44
+ ::
45
+
46
+ python -m pip install ./quantatlas-0.2.0-py3-none-any.whl
47
+
48
+ The wheel is supplied with the release archive. Python 3.10 or later and
49
+ scikit-learn 1.7 or later are required. The validation record lists the
50
+ specific versions used for the release checks.
51
+
52
+ Quick start
53
+ -----------
54
+
55
+ ::
56
+
57
+ from sklearn.datasets import load_diabetes
58
+ from sklearn.model_selection import train_test_split
59
+ from quantatlas import ConsonaRegressor
60
+
61
+ X, y = load_diabetes(return_X_y=True)
62
+ Xtr, Xte, ytr, yte = train_test_split(X, y, random_state=42)
63
+ model = ConsonaRegressor(random_state=42).fit(Xtr, ytr)
64
+ prediction = model.predict(Xte)
65
+ affine, nonlinear = model.predict_components(Xte)
66
+
67
+ The last line returns components in response units. Their sum recovers
68
+ the prediction to floating-point tolerance. Agreement scores describe
69
+ the selected basis coordinates. They are not probabilities of feature
70
+ relevance, confidence levels or causal effects.
71
+
72
+ Architecture
73
+ ------------
74
+
75
+ Consona projects coordinate splines, pairwise products, and radial
76
+ features off the affine design. It screens those columns and estimates
77
+ agreement weights. A generalized ridge solve fits the retained columns
78
+ and the affine term together. Prediction adds the two fitted components.
79
+
80
+ Practical validation
81
+ --------------------
82
+
83
+ The default CV assumes exchangeable observations. Pass groups to
84
+ ConsonaRegressor for grouped integer CV. For timestamped or serial data
85
+ pass a chronological splitter with appropriate horizon gaps and independently
86
+ enforce label maturity when timestamps are irregular or rows have been
87
+ filtered. The algorithm takes features as supplied and cannot infer
88
+ whether they would be known at prediction time.
89
+
90
+ Put imputation and category encoding inside the validation folds. Use
91
+ FixedConsonaRegressor inside a pipeline with external GridSearchCV or
92
+ RandomizedSearchCV when fitting preprocessing or tuning the penalty in
93
+ the same procedure. Sparse matrices and native missing values are outside
94
+ the dense numerical interface. The companion examples exercise grouped
95
+ and chronological use and external preprocessing.
96
+
97
+ Use FixedConsonaRegressor to set alpha, shrinkage, bandwidth and taper
98
+ explicitly. Set shrinkage=0 to use the same penalty on all retained
99
+ nonlinear features.
100
+ The experimental namespace exposes separate affine, base nonlinear and
101
+ extra agreement penalties and repeated or chronological partitions.
102
+ The experimental option penalty="evidence" applies a monotone remapping
103
+ of the agreement score within each partition. Both weights use the same
104
+ residual moments.
105
+
106
+ Use and limitations
107
+ -------------------
108
+
109
+ On the original domain-balanced benchmark, Consona scored 0.4960 NRMSE,
110
+ ridge 0.5446, and Extra Trees 0.4564. The phase-two and final studies show
111
+ a benefit from adaptive shrinkage in some controlled signals, with limited
112
+ evidence of incremental real-data benefit over well-tuned uniform shrinkage.
113
+ Results and their weighting conventions appear in the full manuscript.
114
+
115
+ The taper assumes the fitted affine model is a sensible fallback. It
116
+ does not detect every unusual combination within the training box or
117
+ repair a structural change in the affine relationship. The raw training
118
+ bank grows quadratically with input dimension. Check memory and tuning
119
+ time on your own workload before using many predictors or frequent refits.
120
+ The release skips unselected quadratic and radial columns at prediction.
121
+
122
+ Reproducibility, citation and license
123
+ -------------------------------------
124
+
125
+ The companion archive carries the manuscript, source, table and figure code,
126
+ protocols, case metrics, tutorial and environment versions. Original data
127
+ come from their cited repositories. The complete acquisition and replay
128
+ steps appear in REPLICATION.rst.
129
+
130
+ Cite Sofien Kaabar, CFA (2026), Consona: Agreement-Weighted Nonlinear
131
+ Regression with Controlled Extrapolation, Quant Atlas technical report,
132
+ and QuantAtlas 0.2.0 for the software. See CITATION.cff. The software
133
+ retains the BSD 3-Clause license in LICENSE.
@@ -0,0 +1,11 @@
1
+ consona/__init__.py,sha256=3gMB1PP7rjKLJ9Sn_-8LDz9epLpaLjc9xr1FVSKRxsM,204
2
+ consona/_core.py,sha256=JNwDOKuGQHjv2QrCYebqqy9keAOp5oell4an3WwiJCI,11382
3
+ consona/_prediction.py,sha256=udMrReMfld_vhr_xbl6UREf9uzj9Ub3stOzANPxhnPE,1103
4
+ consona/_selection.py,sha256=ngyBaPZnKdZAwBbV5fcJwlGlYuo6C6J1dwYq6Ao_7HM,8833
5
+ quantatlas/__init__.py,sha256=XoHSTAJ6dwGtbHLdPpg9zk7xnWIlqtCykdVIc4rd0_c,206
6
+ quantatlas/experimental.py,sha256=f4kzhqx1LHzp93zzPSl3zI1urZoR0a_IafvLvdSmW3A,7988
7
+ quantatlas-0.2.0.dist-info/LICENSE,sha256=k2jMrlXoIBlXKEXFaeottVjq288-eH6kulMhTzZAwVw,1517
8
+ quantatlas-0.2.0.dist-info/METADATA,sha256=h_TpC3Fc0VVMJaVbvdFhSInhqrbGf7qD6ArJuR0G6_k,5727
9
+ quantatlas-0.2.0.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
10
+ quantatlas-0.2.0.dist-info/top_level.txt,sha256=7tYf4XNEfoLWwKGxxdw7IBeEoRPauYSBNDhlD-EzV-w,19
11
+ quantatlas-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.41.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ consona
2
+ quantatlas