tesseractboost 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.
@@ -0,0 +1,5 @@
1
+ """Gradient boosting with functional tensor units."""
2
+ from .estimator import TesseractBoostRegressor, TesseractBoostClassifier
3
+
4
+ __version__ = '0.2.0'
5
+ __all__ = ['TesseractBoostRegressor', 'TesseractBoostClassifier']
@@ -0,0 +1,128 @@
1
+ from dataclasses import dataclass
2
+ import numpy as np
3
+ from scipy.interpolate import BSpline
4
+ def basis(ref,x,m,kind):
5
+ z=np.zeros((len(x),4,m))
6
+ for k in range(4):
7
+ r=np.sort(ref[:,k]);v=x[:,k];rank=(np.searchsorted(r,v,'left')+np.searchsorted(r,v,'right'))/2;t=np.clip((rank-.5)/(len(r)-1),0,1)
8
+ if kind=='spline_core':
9
+ knots=np.r_[np.zeros(4),np.arange(1,m-3)/(m-3),np.ones(4)];z[:,k]=BSpline.design_matrix(t,knots,3).toarray()
10
+ else:
11
+ u=t*(m-1);lo=u.astype(int);hi=np.minimum(lo+1,m-1);w=u-lo;z[np.arange(len(x)),k,lo]+=1-w;z[np.arange(len(x)),k,hi]+=w
12
+ return z
13
+
14
+
15
+
16
+ class MomentBasis:
17
+ """Train-only ECDF and weighted orthogonalization of cubic B-splines.
18
+
19
+ Hessian weights affect moments, not the empirical rank coordinate. The
20
+ latter is defined on positive-sample-weight training rows. The cache is
21
+ immutable during prediction. C1 tanh shoulders are bounded, not linear.
22
+ """
23
+
24
+ def __init__(self, reference, weights=None, anchor_mode='raw',
25
+ tail_quantile=.01, anchor_clip=None, ecdf=None, columns=None):
26
+ reference = np.asarray(reference, dtype=float)
27
+ self.ecdf = ECDFReference.fit(reference) if ecdf is None else ecdf
28
+ self.columns = tuple(range(reference.shape[1])) if columns is None else tuple(columns)
29
+ self.anchor_mode = anchor_mode
30
+ self.anchor_clip = anchor_clip
31
+ self.lower, self.upper = np.quantile(reference,
32
+ [tail_quantile, 1-tail_quantile], axis=0)
33
+ self.shoulder = np.maximum(self.upper-self.lower, 1e-12)
34
+ if anchor_clip is not None:
35
+ mid = np.median(reference, axis=0)
36
+ magnitude = np.maximum(np.max(np.abs(reference), axis=0), 1.)
37
+ spread = np.maximum(np.std(reference/magnitude, axis=0)*magnitude, 1e-12)
38
+ self.clip_lower = mid-anchor_clip*spread
39
+ self.clip_upper = mid+anchor_clip*spread
40
+ self.weights = (np.full(len(reference), 1/len(reference)) if weights is None
41
+ else np.asarray(weights, dtype=float)/np.sum(weights))
42
+ raw = self.anchor(reference)
43
+ # Preserve the exact unweighted arithmetic used by v0.2.
44
+ equal = weights is None or np.all(np.asarray(weights) == 1)
45
+ self.magnitude = np.maximum(np.max(np.abs(raw), axis=0), 1.)
46
+ self.extreme = bool(np.any(self.magnitude > 1e100))
47
+ if self.extreme:
48
+ scaled = raw/self.magnitude
49
+ self.scaled_mean = self.weights@scaled
50
+ self.scaled_std = np.sqrt(self.weights@((scaled-self.scaled_mean)**2)).clip(1e-12)
51
+ self.mean = self.scaled_mean*self.magnitude
52
+ self.scale = self.scaled_std*self.magnitude
53
+ else:
54
+ self.mean = raw.mean(0) if equal else self.weights @ raw
55
+ centered = raw-self.mean
56
+ if not self.extreme:
57
+ self.scale = (raw.std(0) if equal else
58
+ np.sqrt(self.weights @ (centered*centered))).clip(1e-12)
59
+ z = ((raw/self.magnitude-self.scaled_mean)/self.scaled_std if self.extreme
60
+ else centered/self.scale)
61
+ b = self.splines(reference)
62
+ self.bmean = b.mean(0) if equal else np.einsum('n,nqm->qm', self.weights, b)
63
+ residual = b-self.bmean
64
+ self.projection = (np.mean(z[:, :, None]*residual, 0) if equal else
65
+ np.einsum('n,nq,nqm->qm', self.weights, z, residual))
66
+ self.z_train = z
67
+ self.a_train = residual-z[:, :, None]*self.projection
68
+
69
+ def anchor(self, x):
70
+ if self.anchor_mode == 'winsorized':
71
+ out = np.clip(x, self.lower, self.upper)
72
+ elif self.anchor_mode == 'soft_clip':
73
+ # Clipping the argument avoids overflow without affecting tanh at
74
+ # floating point precision. The derivative at both joins is 1.
75
+ with np.errstate(over='ignore'):
76
+ below = np.clip((x-self.lower)/self.shoulder, -40, 40)
77
+ above = np.clip((x-self.upper)/self.shoulder, -40, 40)
78
+ out = np.where(x < self.lower,
79
+ self.lower+self.shoulder*np.tanh(below),
80
+ np.where(x > self.upper,
81
+ self.upper+self.shoulder*np.tanh(above), x))
82
+ else:
83
+ out = x
84
+ if self.anchor_clip is not None:
85
+ out = np.clip(out, self.clip_lower, self.clip_upper)
86
+ return out
87
+
88
+ def splines(self, x):
89
+ if hasattr(self, 'ecdf'):
90
+ return self.ecdf.splines(x, self.columns)
91
+ # Compatibility with alpha artifacts.
92
+ return _splines(x, tuple(self.sorted_reference.T))
93
+
94
+ def transform(self, x):
95
+ raw = self.anchor(np.asarray(x))
96
+ z = ((raw/self.magnitude-self.scaled_mean)/self.scaled_std if self.extreme
97
+ else (raw-self.mean)/self.scale)
98
+ return z, self.splines(x)-self.bmean-z[:, :, None]*self.projection
99
+
100
+ def _splines(x, references):
101
+ result = np.empty((len(x), len(references), 12))
102
+ knots = np.r_[np.zeros(4), np.arange(1, 9)/9, np.ones(4)]
103
+ for j, sorted_values in enumerate(references):
104
+ values = x[:, j]
105
+ rank = (np.searchsorted(sorted_values, values, 'left') +
106
+ np.searchsorted(sorted_values, values, 'right'))/2
107
+ positions = np.clip((rank-.5)/(len(sorted_values)-1), 0, 1)
108
+ result[:, j] = BSpline.design_matrix(positions, knots, 3).toarray()
109
+ return result
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class ECDFReference:
114
+ """One sorted grid per encoded feature, shared by every fitted unit."""
115
+
116
+ values: tuple
117
+
118
+ @classmethod
119
+ def fit(cls, x, max_knots=None):
120
+ ordered = np.sort(x, axis=0)
121
+ if max_knots is not None and len(x) > max_knots:
122
+ # Empirical inverse CDF on a uniform grid of quantile levels.
123
+ indices = np.rint(np.linspace(0, len(x)-1, max_knots)).astype(int)
124
+ ordered = ordered[indices]
125
+ return cls(tuple(np.ascontiguousarray(col) for col in ordered.T))
126
+
127
+ def splines(self, x, columns):
128
+ return _splines(x, tuple(self.values[j] for j in columns))
@@ -0,0 +1,399 @@
1
+ """TesseractBoost: numeric regression, serializable sklearn estimator.
2
+
3
+ The first unit is unshrunk, matching H03; subsequent units fit residuals.
4
+ No implicit test-set early stopping. Use select_model for internal CV.
5
+ """
6
+ import time
7
+ import numpy as np
8
+ from sklearn.base import BaseEstimator, RegressorMixin
9
+ from sklearn.feature_selection import mutual_info_regression
10
+ from sklearn.utils.validation import check_is_fitted
11
+ from ._solver import anchored_train, representation
12
+ from ._basis import basis, ECDFReference
13
+
14
+
15
+ def design(z):
16
+ shape = (2,)*z.shape[1]
17
+ ids = np.array(np.unravel_index(np.arange(2**z.shape[1]), shape)).T
18
+ return np.prod(np.where(ids[None, :, :] == 1, z[:, None, :], 1.), axis=2)
19
+
20
+
21
+ def choose_columns(x, y, seed, policy):
22
+ valid = np.flatnonzero(x.std(0) > 1e-12)
23
+ if len(valid) < 4:
24
+ return np.r_[valid, np.repeat(x.shape[1]-1, 4-len(valid))]
25
+ mi = mutual_info_regression(x[:, valid], y, random_state=seed)
26
+ ranked = valid[np.argsort(-mi, kind='stable')]
27
+ base = ranked[:4]
28
+ if policy == 'marginal' or len(valid) == 4:
29
+ return base
30
+ rng = np.random.default_rng(seed)
31
+ # Cheap pair screening uses centered products; all preprocessing is training-only.
32
+ z = (x-x.mean(0))/np.maximum(x.std(0), 1e-8)
33
+ pool = np.unique(np.r_[ranked[:16], rng.choice(valid, min(16, len(valid)), replace=False)])
34
+ pairs = [(i, j) for a, i in enumerate(pool) for j in pool[a+1:]]
35
+ yc = y-y.mean()
36
+ def relevance(pair):
37
+ w = z[:, pair[0]]*z[:, pair[1]]; w = w-w.mean()
38
+ return abs(w@yc)/max(np.linalg.norm(w), 1e-8)
39
+ top = sorted(pairs, key=relevance, reverse=True)[:3]
40
+ candidates = [base]
41
+ for i, j in top:
42
+ candidates.append(np.array([i, j]+[int(k) for k in ranked if k not in (i,j)][:2]))
43
+ candidates.extend([rng.choice(valid, 4, replace=False) for _ in range(2)])
44
+ # GCV is a TRAINING proxy, not an unbiased external validation estimate.
45
+ # The entire selector is evaluated inside the benchmark's inner folds.
46
+ best, winner = np.inf, base
47
+ for cols in candidates:
48
+ f = design(z[:, cols]); p = np.eye(16)*.01; p[0, 0] = 1e-8
49
+ gram = f.T@f/len(y); inv = np.linalg.inv(gram+p)
50
+ c = inv@(f.T@yc/len(y)); df = np.trace(inv@gram)
51
+ score = np.mean((f@c-yc)**2)/max(1-df/len(y), .1)**2
52
+ if score < best: best, winner = score, cols
53
+ return winner
54
+
55
+
56
+ class TesseractUnit:
57
+ def fit(self, x, y, tau, order_base, seed, policy, max_iter=150, tol=1e-9):
58
+ self.cols = choose_columns(x, y, seed, policy)
59
+ self.reference = x[:, self.cols].copy()
60
+ self.mean = float(y.mean()); self.scale = max(float(y.std()), 1e-8)
61
+ _, meta = anchored_train(self.reference, (y-self.mean)/self.scale,
62
+ 2, tau, float('inf'), curve_tau=tau,
63
+ order_base=order_base,max_iter=max_iter,tol=tol)
64
+ self.theta = meta.pop('theta'); self.core = meta.pop('core'); self.meta = meta
65
+ self.xmean=self.reference.mean(0); self.xscale=self.reference.std(0).clip(1e-12)
66
+ zz=(self.reference-self.xmean)/self.xscale
67
+ bb=basis(self.reference,self.reference,12,'spline_core')
68
+ self.bmean=bb.mean(0); self.projection=np.mean(zz[:,:,None]*(bb-self.bmean),0)
69
+ return self
70
+
71
+ def splines(self, x):
72
+ if hasattr(self, 'ecdf'):
73
+ return self.ecdf.splines(x, self.cols)
74
+ return basis(self.reference, x, 12, 'spline_core')
75
+
76
+ def predict(self, x):
77
+ xx=x[:,self.cols];z=(xx-self.xmean)/self.xscale
78
+ a=self.splines(xx)-self.bmean-z[:,:,None]*self.projection
79
+ h = z + np.einsum('nqm,qm->nq', a, self.theta[:, 0, :])
80
+ return (design(h)@self.core)*self.scale+self.mean
81
+
82
+
83
+ class TesseractBoostRegressor(RegressorMixin, BaseEstimator):
84
+ def __init__(self, n_estimators=32, learning_rate=.25, tau=.1,
85
+ selection='interaction', order_base=4., random_state=0, max_iter=150, tol=1e-9):
86
+ self.n_estimators=n_estimators; self.learning_rate=learning_rate
87
+ self.tau=tau; self.selection=selection; self.order_base=order_base
88
+ self.random_state=random_state; self.max_iter=max_iter; self.tol=tol
89
+
90
+ def _transform(self, X):
91
+ x=np.asarray(X, dtype=float)
92
+ if x.ndim != 2 or x.shape[1] != self.n_features_in_:
93
+ raise ValueError('Unexpected number of columns')
94
+ if np.isinf(x).any(): raise ValueError('Infinite inputs are unsupported')
95
+ missing=np.isnan(x)
96
+ x=np.where(missing, self.medians_, x)
97
+ return np.c_[x, missing[:, self.missing_columns_].astype(float), np.zeros(len(x))]
98
+
99
+ def fit(self, X, y):
100
+ x=np.asarray(X, dtype=float); y=np.asarray(y, dtype=float)
101
+ if x.ndim != 2 or len(x)!=len(y) or y.ndim!=1 or len(y)<8:
102
+ raise ValueError('Expected 2D X and one-dimensional y, at least 8 rows')
103
+ if not np.isfinite(y).all() or np.isinf(x).any(): raise ValueError('Nonfinite target or infinity')
104
+ if int(self.n_estimators)<1 or not 0<self.learning_rate<=1 or self.tau<=0:
105
+ raise ValueError('Invalid boosting hyperparameters')
106
+ if self.selection not in ('marginal','interaction'): raise ValueError('Unknown selection')
107
+ self.n_features_in_=x.shape[1]
108
+ self.medians_=np.array([np.median(v[np.isfinite(v)]) if np.isfinite(v).any() else 0 for v in x.T])
109
+ self.missing_columns_=np.flatnonzero(np.isnan(x).any(0))
110
+ x=self._transform(x); self.ecdf_reference_=ECDFReference.fit(x); pred=np.zeros(len(y)); self.estimators_=[]
111
+ self.train_mse_=[]; self.fit_cpu_=0.; start=time.process_time()
112
+ for stage in range(int(self.n_estimators)):
113
+ unit=TesseractUnit().fit(x, y-pred, self.tau, self.order_base,
114
+ self.random_state+stage, self.selection, self.max_iter, self.tol)
115
+ unit.ecdf = self.ecdf_reference_
116
+ del unit.reference
117
+ weight=1. if stage==0 else self.learning_rate
118
+ pred+=weight*unit.predict(x); self.estimators_.append(unit)
119
+ self.train_mse_.append(float(np.mean((pred-y)**2)))
120
+ self.fit_cpu_=time.process_time()-start
121
+ return self
122
+
123
+ def staged_predict(self, X):
124
+ check_is_fitted(self, 'estimators_'); x=self._transform(X); pred=np.zeros(len(x))
125
+ for stage, unit in enumerate(self.estimators_):
126
+ pred+=(1. if stage==0 else self.learning_rate)*unit.predict(x)
127
+ yield pred.copy()
128
+
129
+ def predict(self, X):
130
+ for pred in self.staged_predict(X): pass
131
+ return pred
132
+
133
+
134
+
135
+ # Extended engine. The definitions above remain the v0.2 arithmetic path.
136
+ from itertools import combinations
137
+ from scipy.special import expit, logsumexp
138
+ from ._basis import MomentBasis
139
+ from ._solver import weighted_train
140
+
141
+
142
+ def loss_derivatives(y, prediction, loss, delta=1., quantile=.5, smoothing=.1):
143
+ """Per-row loss, gradient and diagonal Hessian in raw-score space.
144
+
145
+ Quantile uses smooth pinball: s*logaddexp(0,r/s)-q*r,
146
+ r=prediction-y. This is NOT the nonsmooth exact pinball objective.
147
+ Multiclass uses a diagonal Hessian approximation with coupled line search.
148
+ """
149
+ if loss == 'log_loss':
150
+ if prediction.ndim == 1:
151
+ probability = expit(prediction)
152
+ return (np.logaddexp(0, prediction)-y*prediction,
153
+ probability-y, probability*(1-probability))
154
+ probability = np.exp(prediction-logsumexp(prediction, axis=1, keepdims=True))
155
+ target = np.eye(prediction.shape[1])[y.astype(int)]
156
+ values = logsumexp(prediction, axis=1)-prediction[np.arange(len(y)), y.astype(int)]
157
+ return values, probability-target, probability*(1-probability)
158
+ residual = prediction-y
159
+ if loss == 'squared_error':
160
+ return .5*residual**2, residual, np.ones_like(residual)
161
+ if loss == 'huber':
162
+ root = np.hypot(delta, residual)
163
+ # Rationalized form avoids catastrophic cancellation near zero.
164
+ values = delta*(residual*(residual/root))/(1+delta/root)
165
+ return values, delta*(residual/root), (delta/root)**3
166
+ probability = expit(residual/smoothing)
167
+ return (smoothing*np.logaddexp(0, residual/smoothing)-quantile*residual,
168
+ probability-quantile, probability*(1-probability)/smoothing)
169
+
170
+
171
+ def screened_columns(x, target, weights, seed, policy, max_features, max_order=4):
172
+ """Bounded beam screening of degree 1..4 residual moment projections.
173
+
174
+ Stage 1 costs O(np); stage 2 considers a bounded beam + exploration per
175
+ degree. Scores are training proxies, never external validation scores.
176
+ High-order zero-marginal signals can be missed: no recovery guarantee.
177
+ """
178
+ w = weights/weights.sum()
179
+ magnitude = np.maximum(np.max(np.abs(x), axis=0), 1e-300)
180
+ scaled = x/magnitude
181
+ mean = w@scaled
182
+ scale = np.sqrt(w@((scaled-mean)**2))
183
+ valid = np.flatnonzero(scale > 1e-12)
184
+ if len(valid) <= max_order:
185
+ return np.r_[valid, np.repeat(x.shape[1]-1, max_order-len(valid))], {'screened': False}
186
+ z = np.clip((scaled-mean)/np.maximum(scale, 1e-12), -20, 20)
187
+ yc = target-w@target
188
+ relevance = np.abs(z.T@(w*yc))
189
+ ranked = valid[np.argsort(-relevance[valid], kind='stable')]
190
+ if policy == 'marginal' or max_order == 1:
191
+ return ranked[:max_order], {'screened': True, 'candidates': len(valid), 'degrees': [1]}
192
+ rng = np.random.default_rng(seed)
193
+ limit = min(len(valid), max_features or 32)
194
+ keep = max(2, limit//2)
195
+ remaining = np.setdiff1d(valid, ranked[:keep])
196
+ pool = np.r_[ranked[:keep], rng.choice(remaining, limit-keep, replace=False)]
197
+ beam = [(int(j),) for j in pool]
198
+ proposals = {tuple(sorted(ranked[:max_order]))}
199
+ count = 0
200
+ for degree in range(2, max_order+1):
201
+ candidates = {tuple(sorted((*term, int(j)))) for term in beam
202
+ for j in pool if j not in term}
203
+ # Independent exploration protects against a beam containing only
204
+ # marginally strong columns; it does not exhaust all p choose d.
205
+ candidates.update(tuple(sorted(rng.choice(valid, degree, replace=False)))
206
+ for _ in range(limit))
207
+ candidates = sorted(candidates)
208
+ scores = []
209
+ for start in range(0, len(candidates), 128):
210
+ block = candidates[start:start+128]
211
+ first = np.zeros(len(block))
212
+ second = np.zeros(len(block))
213
+ cross = np.zeros(len(block))
214
+ for row in range(0, len(z), 2048):
215
+ stop = row+2048
216
+ products = np.prod(z[row:stop, np.asarray(block)], axis=2)
217
+ first += w[row:stop]@products
218
+ second += w[row:stop]@(products*products)
219
+ cross += (w[row:stop]*yc[row:stop])@products
220
+ norms = np.sqrt(np.maximum(second-first*first, 0.))
221
+ scores.extend(np.abs(cross-first*(w@yc))/np.maximum(norms, 1e-12))
222
+ count += len(candidates)
223
+ selected = np.argsort(-np.asarray(scores), kind='stable')[:4]
224
+ beam = [candidates[k] for k in selected]
225
+ for term in beam:
226
+ rest = [int(j) for j in ranked if j not in term]
227
+ proposals.add(tuple((*term, *rest[:max_order-len(term)])))
228
+ best, winner = np.inf, ranked[:max_order]
229
+ effective_n = 1/(w@w)
230
+ for cols in sorted(proposals):
231
+ f = design(z[:, cols])
232
+ gram = f.T@(w[:, None]*f)
233
+ penalty = np.eye(f.shape[1])*.01
234
+ penalty[0, 0] = 1e-8
235
+ coef = np.linalg.solve(gram+penalty, f.T@(w*yc))
236
+ df = np.trace(np.linalg.solve(gram+penalty, gram))
237
+ score = (w@((f@coef-yc)**2))/max(1-df/effective_n, .1)**2
238
+ if score < best:
239
+ best, winner = score, np.asarray(cols)
240
+ return winner, {'screened': True, 'candidates': count,
241
+ 'full_candidates': len(proposals), 'degrees': list(range(1, max_order+1))}
242
+
243
+
244
+ class NewtonUnit:
245
+ """Four-factor unit with a 16-entry multilinear core (64 parameters)."""
246
+
247
+ def fit(self, x, target, weights, owner, seed, warm_cache):
248
+ started = time.process_time()
249
+ self.cols, selection = screened_columns(x, target, weights, seed,
250
+ owner.selection, owner.max_screen_features, owner.max_order)
251
+ self.cache = MomentBasis(x[:, self.cols], weights, owner.anchor_mode,
252
+ owner.tail_quantile, owner.anchor_clip,
253
+ owner.ecdf_reference_, self.cols)
254
+ w = weights/weights.sum()
255
+ self.mean = float(w@target)
256
+ self.scale = max(float(np.sqrt(w@((target-self.mean)**2))), 1e-8)
257
+ key = tuple(self.cols)
258
+ initial = warm_cache.get(key) if owner.solver_warm_start else None
259
+ self.theta, self.core, self.meta = weighted_train(
260
+ self.cache, (target-self.mean)/self.scale, weights, owner.tau,
261
+ owner.order_base, owner.max_iter, owner.gradient_tol, initial)
262
+ if owner.solver_warm_start:
263
+ warm_cache[key] = self.theta.copy()
264
+
265
+ # These O(n*4*12) training tensors are scratch, not model state.
266
+ del self.cache.z_train, self.cache.a_train, self.cache.weights
267
+ self.meta.update(selection=selection, cpu_seconds=time.process_time()-started)
268
+ return self
269
+
270
+ @property
271
+ def reference(self):
272
+ """Compatibility view of the sorted per-column ECDF grids."""
273
+ if hasattr(self.cache, "ecdf"):
274
+ return np.column_stack([self.cache.ecdf.values[j] for j in self.cols])
275
+ return self.cache.reference
276
+
277
+ def factors(self, x):
278
+ z, a = self.cache.transform(x[:, self.cols])
279
+ return z+np.einsum('nqm,qm->nq', a, self.theta[:, 0, :])
280
+
281
+ def predict(self, x):
282
+ return design(self.factors(x))@self.core*self.scale+self.mean
283
+
284
+
285
+ def unit_factors(unit, x):
286
+ if isinstance(unit, NewtonUnit):
287
+ return unit.factors(x)
288
+ xx = x[:, unit.cols]
289
+ z = (xx-unit.xmean)/unit.xscale
290
+ a = unit.splines(xx)-unit.bmean-z[:, :, None]*unit.projection
291
+ return z+np.einsum('nqm,qm->nq', a, unit.theta[:, 0, :])
292
+
293
+
294
+ def majorized_hessian(diagonal):
295
+ # Gershgorin: each row of diag(p)-pp.T has off-diagonal absolute
296
+ # sum equal to its diagonal. Twice the diagonal dominates in PSD order.
297
+ return 2*diagonal if diagonal.ndim == 2 else diagonal
298
+
299
+
300
+ def fit_newton(owner, x, y, weights, validation, seed, classification=False):
301
+ """Damped functional Newton boosting with true-loss backtracking."""
302
+ started = time.process_time()
303
+ owner.ecdf_reference_ = ECDFReference.fit(x, owner.ecdf_max_knots)
304
+ owner.estimators_ = []
305
+ owner.stage_weights_ = []
306
+ owner.train_mse_ = []
307
+ owner.training_loss_ = []
308
+ owner.validation_scores_ = []
309
+ owner.optimization_status_ = []
310
+ owner.attempted_optimization_status_ = []
311
+ w = weights/weights.sum()
312
+ if classification:
313
+ count = len(owner.classes_)
314
+ priors = np.bincount(y.astype(int), weights=w, minlength=count)
315
+ if count == 2:
316
+ initial = float(np.log(priors[1]/priors[0]))
317
+ else:
318
+ initial = np.log(priors)
319
+ initial -= initial.mean()
320
+ else:
321
+ initial = 0.
322
+ owner.initial_prediction_ = initial
323
+ pred = np.broadcast_to(initial, (len(y),)+np.shape(initial)).copy()
324
+ if validation is not None:
325
+ vx, vy, vw = validation
326
+ vp = np.broadcast_to(initial, (len(vy),)+np.shape(initial)).copy()
327
+ warm = [{} for _ in range(pred.shape[1] if pred.ndim == 2 else 1)]
328
+ best, patience_best, best_stage, stale = np.inf, np.inf, -1, 0
329
+ for stage in range(owner.n_estimators):
330
+ values, grad, hess = loss_derivatives(y, pred, owner.loss, owner.huber_delta,
331
+ owner.quantile, owner.quantile_smoothing)
332
+ before = w@values
333
+ floor_hess = np.maximum(majorized_hessian(hess), owner.hessian_floor)
334
+ units = []
335
+ for k in range(len(warm)):
336
+ gk = grad[:, k] if pred.ndim == 2 else grad
337
+ hk = floor_hess[:, k] if pred.ndim == 2 else floor_hess
338
+ target = -gk/hk
339
+ unit = NewtonUnit().fit(x, target, weights*hk, owner,
340
+ (seed+stage*len(warm)+k) % (2**32-1), warm[k])
341
+ units.append(unit)
342
+ direction = (np.column_stack([u.predict(x) for u in units])
343
+ if pred.ndim == 2 else units[0].predict(x))
344
+ if pred.ndim == 2:
345
+ direction -= direction.mean(axis=1, keepdims=True)
346
+ step = 1. if stage == 0 else owner.learning_rate
347
+ accepted = False
348
+ for _ in range(40):
349
+ proposed = pred+step*direction
350
+ after = w@loss_derivatives(y, proposed, owner.loss, owner.huber_delta,
351
+ owner.quantile, owner.quantile_smoothing)[0]
352
+ if np.isfinite(after) and after <= before:
353
+ accepted = True
354
+ break
355
+ step *= .5
356
+ if not accepted:
357
+ step, proposed, after = 0., pred.copy(), before
358
+ pred = proposed
359
+ owner.estimators_.append(units if pred.ndim == 2 else units[0])
360
+ owner.stage_weights_.append(step)
361
+ owner.training_loss_.append(float(after))
362
+ if not classification:
363
+ owner.train_mse_.append(float(w@((pred-y)**2)))
364
+ for k, unit in enumerate(units):
365
+ info = dict(unit.meta, stage=stage, output=k,
366
+ features=tuple(int(c) for c in unit.cols if c < x.shape[1]-1),
367
+ order=len(set(int(c) for c in unit.cols if c < x.shape[1]-1)),
368
+ effective_learning_rate=step, loss_before=float(before), loss_after=float(after))
369
+ owner.optimization_status_.append(info)
370
+ if validation is not None:
371
+ update = (np.column_stack([u.predict(vx) for u in units])
372
+ if pred.ndim == 2 else units[0].predict(vx))
373
+ if pred.ndim == 2:
374
+ update -= update.mean(axis=1, keepdims=True)
375
+ vp += step*update
376
+ score = float(np.average(loss_derivatives(vy, vp, owner.loss, owner.huber_delta,
377
+ owner.quantile, owner.quantile_smoothing)[0], weights=vw))
378
+ if not np.isfinite(score):
379
+ raise FloatingPointError('Nonfinite validation loss; rescale data or enable anchor protection')
380
+ owner.validation_scores_.append(score)
381
+ if score < best:
382
+ best, best_stage = score, stage
383
+ if score < patience_best-owner.early_stopping_tol:
384
+ patience_best, stale = score, 0
385
+ else:
386
+ stale += 1
387
+ if owner.n_iter_no_change is not None and stale >= owner.n_iter_no_change:
388
+ break
389
+ owner.attempted_optimization_status_ = list(owner.optimization_status_)
390
+ owner.best_validation_score_ = float(best) if validation is not None else None
391
+ owner.best_iteration_ = best_stage if validation is not None else len(owner.estimators_)-1
392
+ if validation is not None and owner.n_iter_no_change is not None:
393
+ end = best_stage+1
394
+ owner.estimators_ = owner.estimators_[:end]
395
+ owner.stage_weights_ = owner.stage_weights_[:end]
396
+ owner.training_loss_ = owner.training_loss_[:end]
397
+ owner.train_mse_ = owner.train_mse_[:end]
398
+ owner.optimization_status_ = [v for v in owner.optimization_status_ if v['stage'] < end]
399
+ owner.fit_cpu_ = time.process_time()-started
@@ -0,0 +1,145 @@
1
+ """Subset-indexed product ANOVA and empirical covariance attribution."""
2
+ from itertools import combinations
3
+ import numpy as np
4
+ from ._engine import unit_factors
5
+ from ._basis import ECDFReference, MomentBasis
6
+
7
+
8
+ def decompose(model, reference=None, weights=None, method='product'):
9
+ reference = model.reference_X_ if reference is None else reference
10
+ weights = model.reference_weight_ if weights is None else weights
11
+ positive = weights > 0
12
+ x = model._transform(reference[positive])
13
+ w = weights[positive]/weights[positive].sum()
14
+ root = np.sqrt(w)
15
+ mapping = np.r_[np.arange(model.n_features_in_), model.missing_columns_, -1]
16
+ indicators = {feature: model.n_features_in_+i
17
+ for i, feature in enumerate(model.missing_columns_)}
18
+ outputs = len(model.classes_) if getattr(model, 'n_classes_', 0) > 2 else 1
19
+ means = np.atleast_1d(model.initial_prediction_).astype(float).copy()
20
+ collections = [dict() for _ in range(outputs)]
21
+ bases = {}
22
+ ecdf = getattr(model, 'ecdf_reference_', None)
23
+ training = None
24
+
25
+ def training_data():
26
+ nonlocal training
27
+ if training is None:
28
+ training = model._transform(model.reference_X_)
29
+ return training
30
+
31
+ def coordinates(feature, values, unit, slot):
32
+ nonlocal ecdf
33
+ mean = w@values
34
+ if feature not in bases:
35
+ basis = getattr(unit, 'cache', unit)
36
+ selected = x[:, unit.cols]
37
+ anchor = x[:, feature]
38
+ if unit.cols[slot] == feature:
39
+ spline = basis.splines(selected)[:, slot]
40
+ if hasattr(basis, 'anchor'):
41
+ anchor = basis.anchor(selected)[:, slot]
42
+ else:
43
+ if ecdf is None:
44
+ ecdf = ECDFReference.fit(training_data())
45
+ spline = ecdf.splines(x[:, [feature]], [feature])[:, 0]
46
+ if hasattr(basis, 'anchor'):
47
+ temporary = MomentBasis(training_data()[:, [feature]],
48
+ anchor_mode=basis.anchor_mode,
49
+ tail_quantile=model.tail_quantile,
50
+ anchor_clip=basis.anchor_clip,
51
+ ecdf=ecdf, columns=[feature])
52
+ anchor = temporary.anchor(x[:, [feature]])[:, 0]
53
+ columns = [anchor/max(1., np.max(np.abs(anchor)))]
54
+ columns.extend(spline.T)
55
+ if feature in indicators:
56
+ columns.append(x[:, indicators[feature]])
57
+ matrix = np.column_stack(columns)
58
+ matrix -= w@matrix
59
+ # Drop numerically null directions to avoid arbitrary QR columns
60
+ # spilling into the constant space on small/discrete references.
61
+ u, singular, _ = np.linalg.svd(root[:, None]*matrix, full_matrices=False)
62
+ cutoff = (singular[0] if len(singular) else 0)*max(matrix.shape)*np.finfo(float).eps
63
+ bases[feature] = u[:, singular > cutoff]
64
+ return mean, bases[feature].T@(root*(values-mean))
65
+
66
+ for stage, entry in enumerate(model.estimators_):
67
+ units = entry if isinstance(entry, list) else [entry]
68
+ for output, unit in enumerate(units):
69
+ h = unit_factors(unit, x)
70
+ width = len(unit.cols)
71
+ ids = np.array(np.unravel_index(np.arange(2**width), (2,)*width)).T
72
+ offsets = np.eye(outputs)[output]-1/outputs if outputs > 1 else np.ones(1)
73
+ steps = model.stage_weights_[stage]*offsets
74
+ means += steps*unit.mean
75
+ factor_cache = {}
76
+ for term, core in zip(ids, unit.core):
77
+ coefficient = unit.scale*core
78
+ slots = tuple(np.flatnonzero(term))
79
+ if coefficient == 0 or any(mapping[unit.cols[k]] < 0 for k in slots):
80
+ continue
81
+ groups = {}
82
+ for slot in slots:
83
+ feature = int(mapping[unit.cols[slot]])
84
+ groups.setdefault(feature, []).append(slot)
85
+ features = tuple(sorted(groups))
86
+ moments = {}
87
+ for j, group in groups.items():
88
+ key = tuple(group)
89
+ if key not in factor_cache:
90
+ values = h[:, group].prod(axis=1)
91
+ factor_cache[key] = coordinates(j, values, unit, group[0])
92
+ moments[j] = factor_cache[key]
93
+ means += steps*coefficient*np.prod([moments[j][0] for j in features])
94
+ for degree in range(1, len(features)+1):
95
+ for subset in combinations(features, degree):
96
+ amplitude = coefficient*np.prod([moments[j][0] for j in features
97
+ if j not in subset])
98
+ if amplitude == 0:
99
+ continue
100
+ tensor = np.array(amplitude)
101
+ for j in subset:
102
+ tensor = np.multiply.outer(tensor, moments[j][1])
103
+ for dest, step in enumerate(steps):
104
+ if step != 0:
105
+ bucket = collections[dest]
106
+ if subset not in bucket:
107
+ bucket[subset] = step*tensor
108
+ else:
109
+ bucket[subset] += step*tensor
110
+ variances = {}
111
+ per_output = []
112
+ for components in collections:
113
+ if method == 'product':
114
+ this = {subset: float(np.vdot(tensor, tensor))
115
+ for subset, tensor in components.items()}
116
+ else:
117
+ values = {}
118
+ for subset, tensor in components.items():
119
+ rows = [bases[j]/root[:, None] for j in subset]
120
+ axes = 'abcd'[:len(subset)]
121
+ expression = axes+','+','.join('n'+axis for axis in axes)+'->n'
122
+ values[subset] = np.einsum(expression, tensor, *rows, optimize=True)
123
+ total_prediction = sum(values.values(), np.zeros(len(x)))
124
+ shift = w@total_prediction
125
+ means[len(per_output)] += shift
126
+ centered = total_prediction-shift
127
+ this = {subset: float((w*centered)@value) for subset, value in values.items()}
128
+ for subset, value in this.items():
129
+ variances[subset] = variances.get(subset, 0.)+value
130
+ per_output.append(this)
131
+ total = sum(variances.values())
132
+ interactions = {key: value/total if total > 0 else 0. for key, value in variances.items()}
133
+ feature = np.zeros(model.n_features_in_)
134
+ order = dict.fromkeys(range(1, 5), 0.)
135
+ for subset, value in interactions.items():
136
+ order[len(subset)] += value
137
+ for j in subset:
138
+ feature[j] += value/len(subset)
139
+ return dict(interactions=interactions, feature=feature, order=order,
140
+ variances=variances, total_variance=total, mean=means,
141
+ output_variances=per_output,
142
+ reference=('product of weighted empirical original-feature marginals'
143
+ if method == 'product' else 'weighted empirical joint rows'),
144
+ scale='raw scores', allocation=('equal share of each interaction variance' if method == 'product'
145
+ else 'signed covariance with total prediction, shared equally'))