API¶
For a coder calling the package. It follows the scikit-learn conventions 12: parameters
stored verbatim, validation in fit, fitted attributes ending in an underscore. Dimension is
arbitrary: d metrics and d - 1 chart coordinates.
LogAffinePreconditioner, a transformer: attributes to larger-is-better metrics, invertible.frontier_in_original_units, a function: the fitted reference surface as a monomial in raw attributes.HyperbolicTradeSpace, a transformer: fits the surface and gives the chart of position and log V. Fitted attributes for every number of terms includeexponents_,cell_,coefficients_,term_share_,loss_(what the solver minimized) andmean_slack_, to compare fits across numbers of terms.select_temperature, a function: chooses the temperature by a target fraction above V = 1 (the path against tau).make_frontier_data, a function: seeded synthetic data with a planted frontier.make_configured_frontier_data, a function: the same with configuration variables.trade_off_report,tension_matrix,design_tensions, functions: contending set and elasticities; the slope of one metric against another.TradeSpaceRegressor, a regressor: metrics, coordinates and novelty from configuration.
Submodules are used by import path:
tradespace.coordinates:helmert_basis,alr_basis,to_frontier_coordinates,from_frontier_coordinates, the chart's bases and its two maps (fitting).tradespace.gaps:knn_gap_scores,find_holes,frontier_targets,orient_by_pca(chart).tradespace.tensions:TradeOffReport,DesignTensions: what the functions return.tradespace.plotting:plot_association,plot_log_plane,plot_frontier_surface_3d,plot_frontier_coordinates,plot_v_by_variable,plot_ternary,ternary_marker_values,cell_labels,plot_temperature_path,temperature_path(the fit temperature).tradespace.estimator:EPS_ZERO_EXPONENT(1e-12). An exponent at or below it is numerically zero, soscore_samplesreads a zero metric there as0 log 0 := 0.PARTICIPATION_THRESHOLD(1e-3). An exponent above it participates. It is the threshold oftrade_off_reportand ofconditioning_.tradespace.solvers: the multi-term solver, theTerminationrecord and the certificate functions (Reading termination).
Reference¶
HyperbolicTradeSpace¶
Bases: TransformerMixin, BaseEstimator
Posynomial invariant form: learn the shape of a design trade space (K monomial terms).
Fits V(m) = prod_j m_j^{w_j} / e^{beta} to strictly positive, larger-is-better metrics so
that V <= 1 is the attainable region and V = 1 the frontier, by minimizing the
entropic soft maximum of w . log m over the simplex. The transform is the invertible chart
[Z | log V] (log-ratio coordinates along the frontier, and the depth below it).
Parameters:
-
temperature(float, default:10.0) –Softness
tauof the soft maximum,tau > 0ornp.inf(an exact LP). Units are 1 / (log-spread of the metrics), so condition the metrics first; useful range 3 to 100. -
min_exponent(float, default:0.0) –Lower bound on each exponent, in
[0, 1/d). -
coordinates(('ilr', 'alr'), default:"ilr") –Chart basis: Helmert (orthonormal rows) or additive log-ratio (invertible, not orthonormal; last metric is the reference).
-
n_terms(int, default:1) –Number of monomial terms
K(K > 1is the posynomial frontier, fitted bysolve_terms;K = 1is the monomial fit). -
term_temperature(float, default:np.inf) –Softness
kappaofPhi_K(u) = (1/kappa) log sum_k exp(kappa (w_k . u - beta_k)),kappa > 0ornp.inf(the exact maximum). Used forn_terms > 1only. The offsetsbeta_kare the supports, somax_k x_k <= Phi_K <= max_k x_k + log K / kappa; the gap is disclosed, not renormalized. A finitekappaalso selects the soft fit (withrefit_step="support"): every design carries the weightssoftmax_k(kappa x_k)on every term, the refit of termkis the supporting hyperplane centred at the weighted mean of the designs, and the fit minimizes the mean slack of the model it reports,-mean_i Phi_K(u_i). At the defaultnp.infevery design has the label of its dominant term, as before. Readkappaon the scale oftemperature: akappafar below it merges terms.refit_step="tangent"ignoreskappain the fit. -
term_aggregation(('sum', 'mean'), default:"sum") –How the K terms are aggregated when
term_temperatureis finite."sum"(the default) is the unnormalized log-sum-exp above, withmax <= Phi_K <= max + log K / kappa; a duplicated term lowers the slack bylog 2 / kappawithout new geometry."mean"is the normalized log-mean-exp,Phi_K - log K / kappa, withmax - log K / kappa <= Phi_K <= max, the same convention astemperature. The two differ by the constantlog K / kappa: the soft weights, the Hessian, the certificate and the fitted terms are the same,score_samplesand the slack shift by exactly that constant. No effect atterm_temperature = inforn_terms = 1. Validated infit. -
tol(float, default:1e-10) –Solver tolerance (SLSQP
ftol); also the threshold of the iteration-cap warning (seemax_iter). -
max_iter(int, default:500) –Maximum SLSQP iterations of each term's fit. The
n_terms > 1alternation has its own cap (50 partition-and-refit rounds,solve_terms'smax_iter). Reaching it means the assignment step was still moving rows, possibly cycling among rows that tie between terms while every term is already stationary on its rows. The fit is kept, with status"iteration_cap"and its gap intermination_;fitwarns only when that gap or the last change of the loss exceedstol. -
penalty((None, 'reweighted_l1'), default:None) –Sparsity option for the exponents (see
solve_slsqp); acts at finitetemperature. -
alpha(float, default:0.0) –Penalty weight,
alpha >= 0; 0 leaves the fit unchanged. -
random_state(int, RandomState instance or None, default:None) –Seed for the term initializations (
n_terms > 1only). -
n_restarts(int, default:5) –Number of seeded initializations of the
n_terms > 1alternation; the lowest mean slack is kept. More restarts help against local optima (see the limitations page). -
refit_step(('support', 'tangent'), default:"support") –Per-term step of the
n_terms > 1alternation (seesolve_terms):"support"is the supporting hyperplane tightest on the term's cell, which keeps the mean slack monotone;"tangent"fits the near-frontier rows' tangent plane, which is not monotone. No effect forn_terms = 1.
Attributes:
-
exponents_(ndarray of shape (n_terms, n_features_in_)) –Fitted exponents
w_kon the simplex. -
log_offset_(ndarray of shape (n_terms,)) –The offsets
beta_k = J_tau(w_k)(forn_terms > 1over all rows: each term is a supporting hyperplane). -
support_weights_(ndarray of shape (n_samples,)) –Softmax weights
pat the solution (LP duals attau = inf); zero for rows with a zero metric. Forn_terms > 1each term's weights on its cell, scaled by its row share (sum 1). -
n_eff_(float) –Effective number of supporting rows,
1 / sum p_i^2. -
frac_above_(float) –Fraction of (non-degenerate) training rows with
V > 1. -
loss_(float) –What the solver minimized:
J_tau(w)at the solution (equalsbeta, a soft maximum) forn_terms = 1; forn_terms > 1the mean slack(1/N) sum_i (beta_k(i) - w_k(i) . u_i)of the partition fit, or, for the soft fit (finiteterm_temperature), the mean slack-mean_i Phi_K(u_i)of the soft model. The two are different quantities: to compare fits acrossn_termsusemean_slack_. -
mean_slack_(float) –The mean slack
mean_i (beta_k(i) - w_k(i) . u_i)over the rows with no zero metric, withk(i)the row's cell (cell_); defined for everyn_terms. Atn_terms = 1it isbeta - mean_i (w . u_i). At a fixedtemperatureit is comparable acrossn_terms(and across restarts);loss_is not. With a finiteterm_temperatureandn_terms > 1it is the slack of the reported model,-mean_i Phi_K(u_i). -
n_iter_(int) –Solver iterations (at least 1; 1 on the LP-only path).
-
basis_(ndarray of shape (n_features_in_ - 1, n_features_in_)) –Chart matrix
B(Z = log(X) @ B.T). Forn_terms > 1the shape is(n_terms, n_features_in_ - 1, n_features_in_): the chart does not depend onw, so the sameBis stackedKtimes andZis the same for every term. -
cell_(ndarray of int, shape (n_samples,)) –argmax_k (w_k . u - beta_k)of each training row (-1for a zero metric); all zeros atn_terms = 1. The dominant term: an analysis of the fitted model, also for the soft fit, which uses weights on every term. -
coefficients_(ndarray of shape (n_terms,)) –Posynomial coefficients
exp(-kappa beta_k)ofexp(kappa Phi_K) = sum_k c_k prod_j m_j^(kappa w_kj); atkappa = infthe conventionkappa = 1givesexp(-beta_k). -
term_share_(ndarray of shape (n_terms,)) –Share of the near-frontier training rows (
|log V| < band,band = 1 / temperature, or 0.1 attau = inf) assigned to each term; zeros if there are none;[1.0]atn_terms = 1. It is also the order of the terms: after the fit converges the terms are permuted once by descending share (ties by cell size, then by the first metric's exponent, ascending), soexponents_,log_offset_,coefficients_,cell_,conditioning_and the per-term entries oftermination_all carry that one order. -
training_log_v_(ndarray of shape (n_samples,)) –log Vof the training rows (-inffor rows with a zero metric on a participating exponent; a zero metric on an exponent at or belowEPS_ZERO_EXPONENTcontributes nothing, see Notes). -
termination_(Termination) –Stopping record of the chosen run:
status("certified","stationary_without_margin","stationary","uncertified","guard_stop","iteration_cap"or"not_applicable"), the first-order gaps, the assignment margin and radius, the Corollary bound and the tolerances (EPS_KKT,EPS_FEAS,GUARD_TOL). Level 3 (conditional local optimality) is forn_terms > 1withrefit_step="support"and no penalty;n_terms = 1and the degenerate shortcuts record"not_applicable"with the gap of the fitted loss, read only. For the soft fit (finiteterm_temperature, finitetemperature)"certified"means the term gaps are withinEPS_KKTand the Hessian of the soft loss is positive definite on the tangent space of the active face (a strict local minimizer of the soft loss);"stationary"means the gaps hold and the curvature is not positive;min_curvatureis the smallest curvature (nanotherwise); the margin, radius and bound arenan. A soft fit attemperature = infis"not_applicable". -
conditioning_(ndarray of shape (n_terms,)) –Smallest eigenvalue of the Hessian of
J_tauat each term's fit,tau (U^T diag(p) U - (U^T p)(U^T p)^T)withpthe softmax weights over the valid rows, restricted to the simplex tangent space and to the participating exponents (w_j > PARTICIPATION_THRESHOLD). Small values flag a nearly flat direction (weak identifiability of the exponents).nanattemperature = inf(the loss is not twice differentiable) and for a term with fewer than two participating exponents. A read-only diagnostic. -
n_features_in_(int) –Number of metrics seen in
fit. -
feature_names_in_(ndarray of shape (n_features_in_,)) –Names of the metrics seen in
fit; defined only for string column names.
See Also
tradespace.make_frontier_data : Synthetic data with a planted frontier.
Notes
Zero metrics are tolerated: log 0 = -inf, the row has support weight 0 and is excluded
from the loss; its Z is nan and it has no inverse. Scoring follows the
continuous extension of a monomial: log V = sum_{j: w_j > EPS_ZERO_EXPONENT} w_j log m_j -
beta with 0 log 0 := 0, so a zero metric on a numerically zero exponent leaves
log V finite and a zero metric on a participating exponent gives V = 0,
log V = -inf (for n_terms > 1 each term's score follows the same rule). Negative
values raise ValueError. Grounding: homogeneity and the invariant form, the offset, gradient
and support weights, convexity, log-mean-exp, the noise offset, elasticities and improvement
factors, and the chart, each derived in the documentation.
For n_terms > 1 the score is log V = Phi_K(u) and the chart [Z | log V] is
inverted in closed form (Phi_K(u + s 1) = Phi_K(u) + s), exactly for every
term_temperature. K > 1 is a local optimum of a partition-and-refit scheme; restarts
are drawn from random_state. Degenerate input (one metric, one valid row, fewer valid
rows than n_terms) repeats the K = 1 fit. A single valid row is a declared
convention: the fitted object does not exist for it (the loss has no minimizer worth
the name), uniform exponents are returned, and fit emits a UserWarning saying so.
Examples:
>>> import numpy as np
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> X, info = make_frontier_data(300, 3, random_state=0)
>>> hts = HyperbolicTradeSpace(temperature=np.inf).fit(X)
>>> np.allclose(hts.exponents_[0], info["exponents"], atol=1e-3)
True
>>> hts.transform(X).shape
(300, 3)
>>> hts.get_feature_names_out().tolist()
['ilr0', 'ilr1', 'log_v']
>>> bool(np.allclose(hts.inverse_transform(hts.transform(X)), X))
True
Three terms:
>>> X, info = make_frontier_data(400, 4, n_terms=3, random_state=0)
>>> est = HyperbolicTradeSpace(
... n_terms=3, temperature=np.inf, random_state=0).fit(X)
>>> est.exponents_.shape, est.basis_.shape
((3, 4), (3, 3, 4))
>>> bool(np.isclose(est.term_share_.sum(), 1.0))
True
>>> bool(np.allclose(
... np.sort(est.exponents_, axis=0),
... np.sort(info["exponents"], axis=0), atol=0.05))
True
fit(X, y=None)
¶
Fit the frontier w, beta and the chart.
Parameters:
-
X(array-like of shape (n_samples, n_features)) –Strictly positive (zeros tolerated) larger-is-better metrics.
-
y(None, default:None) –Ignored.
Returns:
-
self(HyperbolicTradeSpace) –The fitted estimator.
Examples:
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> X, _ = make_frontier_data(100, 2, random_state=1)
>>> HyperbolicTradeSpace().fit(X).exponents_.shape
(1, 2)
transform(X)
¶
Map metrics to the chart [Z | log V].
Parameters:
-
X(array-like of shape (n_samples, n_features)) –Metrics, nonnegative.
Returns:
-
ndarray of shape (n_samples, n_features)–Z(n_features - 1log-ratio coordinates) thenlog V. Rows with a zero metric givenaninZand-infinlog V.
Examples:
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> X, _ = make_frontier_data(50, 3, random_state=0)
>>> HyperbolicTradeSpace().fit(X).transform(X[:2]).shape
(2, 3)
inverse_transform(Xt)
¶
Map chart coordinates [Z | log V] back to metrics.
Parameters:
-
Xt(array-like of shape (n_samples, n_features)) –Chart coordinates as returned by
transform.
Returns:
-
ndarray of shape (n_samples, n_features)–Metrics
exp(u)(the inverse chart). Rows with non-finite coordinates (a zero metric in the original) are not invertible and givenan.
Examples:
>>> import numpy as np
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> X, _ = make_frontier_data(50, 3, random_state=0)
>>> hts = HyperbolicTradeSpace().fit(X)
>>> bool(np.allclose(hts.inverse_transform(hts.transform(X)), X))
True
get_feature_names_out(input_features=None)
¶
Names of the transform columns: ilr0.. (or alr0..) then log_v.
Parameters:
-
input_features(array-like of str or None, default:None) –Checked against
feature_names_in_andn_features_in_when given.
Returns:
-
ndarray of str, shape (n_features_in_,)–Output feature names.
Examples:
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> X, _ = make_frontier_data(30, 2, random_state=0)
>>> hts = HyperbolicTradeSpace(coordinates="alr").fit(X)
>>> hts.get_feature_names_out().tolist()
['alr0', 'log_v']
score_samples(X)
¶
Log invariant value log V(m) = w . log m - beta of each row.
Parameters:
-
X(array-like of shape (n_samples, n_features)) –
Returns:
-
ndarray of shape (n_samples,)–log V;-inffor a zero metric. Positive means beyond the fitted frontier.
Examples:
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> X, _ = make_frontier_data(60, 3, random_state=0)
>>> HyperbolicTradeSpace().fit(X).score_samples(X).shape
(60,)
invariant_value(X)
¶
Invariant value V = exp(log V); V = 1 on the frontier, V < 1 inside.
Parameters:
-
X(array-like of shape (n_samples, n_features)) –
Returns:
-
ndarray of shape (n_samples,)–V; 0 for a zero metric.
Examples:
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> X, _ = make_frontier_data(60, 3, random_state=0)
>>> bool((HyperbolicTradeSpace(temperature=float("inf")).fit(X)
... .invariant_value(X) <= 1 + 1e-9).all())
True
project(X)
¶
Project onto the frontier along the diagonal: m / V (invariant form).
Parameters:
-
X(array-like of shape (n_samples, n_features)) –
Returns:
-
ndarray of shape (n_samples, n_features)–m / V, which hasV = 1(homogeneity);nanrows whereV = 0.
Examples:
>>> import numpy as np
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> X, _ = make_frontier_data(60, 3, random_state=0)
>>> hts = HyperbolicTradeSpace().fit(X)
>>> bool(np.allclose(hts.invariant_value(hts.project(X)), 1.0))
True
assign_cells(X)
¶
Cell of each row: argmax_k (w_k . log m - beta_k).
Parameters:
-
X(array-like of shape (n_samples, n_features)) –Metrics, nonnegative.
Returns:
-
ndarray of int, shape (n_samples,)–Index in
[0, n_terms)of the term that attains the maximum;-1for rows with a zero metric. All zeros whenn_terms = 1.
Examples:
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> X, _ = make_frontier_data(150, 4, n_terms=3, random_state=0)
>>> est = HyperbolicTradeSpace(n_terms=3, random_state=0).fit(X)
>>> bool((est.assign_cells(X) == est.cell_).all())
True
improvement_factors(X)
¶
Per-metric improvement factor V^(-1/w_j) that lands on the frontier.
Parameters:
-
X(array-like of shape (n_samples, n_features)) –
Returns:
-
ndarray of shape (n_samples, n_features)–Entry
(i, j): the factor by which metricjalone must be multiplied to reachV = 1.infwherew_jis below1e-12(numerically zero) orV = 0.
Examples:
>>> import numpy as np
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> X, _ = make_frontier_data(60, 3, random_state=0)
>>> hts = HyperbolicTradeSpace().fit(X)
>>> x = X[:1].copy()
>>> f = hts.improvement_factors(x)[0, 1]
>>> x[0, 1] *= f
>>> round(float(hts.invariant_value(x)[0]), 6)
1.0
novelty_score(X, calibrated=False)
¶
Novelty of each row relative to the fitted frontier.
Parameters:
-
X(array-like of shape (n_samples, n_features)) – -
calibrated(bool, default:False) –If False return
V - 1(the uniform factor by which a frontier design must improve to reach the point, the invariant form). If True return an array whose first column is the fraction of traininglog V(finite ones) that are<=the query's, and whose second istau * log V(log Vitself whentauis infinite).
Returns:
-
ndarray of shape (n_samples,) or (n_samples, 2)–
Notes
Training rows exceed V = 1 by construction at finite tau (frac_above_), so
the calibrated form is the fair comparison. Far from the balanced region V - 1 is
conservative.
Examples:
>>> import numpy as np
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> X, _ = make_frontier_data(80, 3, random_state=0)
>>> hts = HyperbolicTradeSpace().fit(X)
>>> hts.novelty_score(X[:3]).shape, hts.novelty_score(
... X[:3], calibrated=True).shape
((3,), (3, 2))
level_set(Z, value=1.0)
¶
Metric points on the level set {V = value} above chart coordinates Z.
Parameters:
-
Z(array-like of shape (n_points, n_features - 1)) –Log-ratio coordinates (the leading columns of
transform). -
value(float, default:1.0) –Target invariant value
V > 0; 1 is the frontier.
Returns:
-
ndarray of shape (n_points, n_features)–Metrics
mwithV(m) = valuewhose chart coordinates areZ.
Examples:
>>> import numpy as np
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> X, _ = make_frontier_data(60, 3, random_state=0)
>>> hts = HyperbolicTradeSpace().fit(X)
>>> M = hts.level_set(np.zeros((1, 2)), value=0.5)
>>> round(float(hts.invariant_value(M)[0]), 6)
0.5
LogAffinePreconditioner¶
Bases: OneToOneFeatureMixin, TransformerMixin, BaseEstimator
Condition attributes into strictly positive, larger-is-better metrics (log-affine map).
Computes z = o * log(X + shift) per column, fits a scaler on the finite entries of z,
and returns m = exp(scaled z). Entries with X + shift == 0 map to 0 (an infinitely
dominated row for the estimator, whatever the orientation). The map is invertible
(inverse_transform is exact) and affine in log space, which is the conditioning of
attributes.
Parameters:
-
orientation(array-like of {+1, -1}, int, or None, default:None) –+1larger-is-better,-1smaller-is-better, per column; a single+1/-1applies to every column;Nonemeans all+1. -
shift(float or array-like of shape (n_features,), default:0.0) –Offset
s_jadded before the logarithm;X + shiftmust be nonnegative. -
scaler(('standard', 'robust'), default:"standard") –Affine scaler fitted on the finite
zof each column."standard"gives unit log-standard-deviation,"robust"unit log-IQR,Noneno scaling (pure log). An instance must be affine per column (cloned at fit).
Attributes:
-
scaler_(fitted scaler or None) –The fitted scaler (
Nonewhenscaler=None). -
log_offset_(ndarray of shape (n_features_in_,)) –c_j: the log valuez_jthat maps to metric1(the center removed by the scaler); scaledz = (z - log_offset_) / log_scale_. -
log_scale_(ndarray of shape (n_features_in_,)) –k_j: log-units per scaled unit (the standard deviation for"standard"). -
orientation_(ndarray of shape (n_features_in_,)) –Validated orientation, entries
+1or-1. -
shift_(ndarray of shape (n_features_in_,)) –Validated shift.
-
n_features_in_(int) –Number of columns seen in
fit. -
feature_names_in_(ndarray of shape (n_features_in_,)) –Column names seen in
fit(only whenXhas string column names).
See Also
frontier_in_original_units : Pull the fitted frontier back to raw attributes.
Notes
The map is log m_j = alpha_j log(a_j + s_j) + b_j with alpha_j = o_j / log_scale_j,
b_j = -log_offset_j / log_scale_j and a_j = shift_j. Which orientation, shift and
scaling are appropriate is the analyst's decision, not derived. Entries with X + shift == 0
are ignored by the scaler; a column consisting only of such entries gets the identity scaling
(offset 0, scale 1).
Examples:
>>> import numpy as np
>>> from tradespace import LogAffinePreconditioner
>>> X = np.array([[1.0, 10.0], [2.0, 5.0], [4.0, 2.5], [8.0, 1.25]])
>>> pre = LogAffinePreconditioner(orientation=[1, -1]).fit(X)
>>> M = pre.transform(X)
>>> bool(np.allclose(np.log(M).std(axis=0), 1.0))
True
>>> bool(np.allclose(pre.inverse_transform(M), X))
True
fit(X, y=None)
¶
Fit the scaler on the finite log values of each column.
Parameters:
-
X(array-like of shape (n_samples, n_features)) –Raw attributes with
X + shift >= 0. -
y(None, default:None) –Ignored.
Returns:
-
self(LogAffinePreconditioner) –The fitted transformer.
Examples:
>>> import numpy as np
>>> from tradespace import LogAffinePreconditioner
>>> X = np.array([[1.0, 2.0], [2.0, 4.0], [4.0, 8.0]])
>>> LogAffinePreconditioner().fit(X).log_scale_.shape
(2,)
transform(X)
¶
Condition attributes to metrics exp(scaled z); X + shift == 0 gives 0.
Parameters:
-
X(array-like of shape (n_samples, n_features)) –Raw attributes with
X + shift >= 0.
Returns:
-
ndarray of shape (n_samples, n_features)–Strictly positive larger-is-better metrics (zeros where
X + shift == 0).
Examples:
>>> import numpy as np
>>> from tradespace import LogAffinePreconditioner
>>> X = np.array([[0.0, 2.0], [2.0, 4.0], [4.0, 8.0]])
>>> M = LogAffinePreconditioner().fit(X).transform(X)
>>> M[0].tolist()[0]
0.0
inverse_transform(Xt)
¶
Exact inverse of transform (0 maps to X = -shift).
Parameters:
-
Xt(array-like of shape (n_samples, n_features)) –Metrics, nonnegative.
Returns:
-
ndarray of shape (n_samples, n_features)–Raw attributes.
Examples:
>>> import numpy as np
>>> from tradespace import LogAffinePreconditioner
>>> X = np.array([[1.0, 2.0], [2.0, 4.0], [4.0, 8.0]])
>>> pre = LogAffinePreconditioner(shift=0.5).fit(X)
>>> bool(np.allclose(pre.inverse_transform(pre.transform(X)), X))
True
TradeSpaceRegressor¶
Bases: RegressorMixin, BaseEstimator
Predict metrics, chart coordinates and novelty from configuration variables.
Parameters:
-
regressor(estimator) –scikit-learn regressor mapping configuration to chart coordinates
[Z | log V]. It is cloned at fit. Multi-output is required when the number of metrics is above 2 (its target hasdcolumns, or one whend = 1). -
trade_space(estimator) –Fitted on the metrics
Yto define the chart: aHyperbolicTradeSpaceor aPipelinewhose last step is one (for example a preconditioner followed by the estimator). It is cloned at fit.
Attributes:
-
regressor_(estimator) –The fitted clone of
regressor. -
trade_space_(estimator) –The fitted clone of
trade_space. -
n_outputs_(int) –Number of metrics
d. -
n_features_in_(int) –Number of configuration variables seen in
fit. -
feature_names_in_(ndarray of shape (n_features_in_,)) –Configuration names, when
Xhas string column names.
See Also
tradespace.HyperbolicTradeSpace : the chart this regressor composes with. sklearn.compose.TransformedTargetRegressor : the generic pattern this specializes.
Notes
score is the coefficient of determination in coordinate space (uniform average over
the d coordinates Z and log V), not in metric units. Metrics y must be
strictly positive (target tag positive_only); a one-dimensional y is a single metric
(d = 1) and predict then returns a one-dimensional array. The chart is fitted on the
training metrics only, so predictions are per-row and independent of sample order.
Why not TransformedTargetRegressor? It would work for predict (the chart is an
invertible transformer with 2-D support), but it has no predict_coordinates,
predict_novelty or coordinate-space score, which are the point here.
test_predictive.py verifies that the wrapper still composes with this chart.
Examples:
>>> import numpy as np
>>> from sklearn.linear_model import LinearRegression
>>> from tradespace import (
... HyperbolicTradeSpace, TradeSpaceRegressor,
... make_configured_frontier_data)
>>> C, Y, info = make_configured_frontier_data(
... 200, 3, 3, nonlinearity=0.0, random_state=0)
>>> reg = TradeSpaceRegressor(
... LinearRegression(), HyperbolicTradeSpace(np.inf)).fit(C, Y)
>>> reg.predict(C[:2]).shape
(2, 3)
>>> Z, log_v = reg.predict_coordinates(C[:2])
>>> Z.shape, log_v.shape
((2, 2), (2,))
>>> reg.predict_novelty(C[:2]).shape
(2,)
fit(X, y)
¶
Fit the chart on y, then the regressor on X -> chart coordinates.
Parameters:
-
X(array-like of shape (n_samples, n_config)) –Configuration variables.
-
y(array-like of shape (n_samples,) or (n_samples, n_metrics)) –Measured metrics, strictly positive.
Returns:
-
self(TradeSpaceRegressor) –
predict_coordinates(X)
¶
Predicted chart coordinates of configurations.
Parameters:
-
X(array-like of shape (n_samples, n_config)) –
Returns:
-
Z(ndarray of shape (n_samples, n_metrics - 1)) –Position along the frontier (log-ratio coordinates).
-
log_v(ndarray of shape (n_samples,)) –Predicted log V (zero on the frontier, positive beyond it).
predict(X)
¶
Predicted metrics (chart coordinates mapped back by inverse_transform).
Parameters:
-
X(array-like of shape (n_samples, n_config)) –
Returns:
-
ndarray of shape (n_samples,) or (n_samples, n_metrics)–One-dimensional when
ywas one-dimensional infit.
predict_novelty(X)
¶
Predicted novelty V - 1 of configurations (zero on the frontier).
Parameters:
-
X(array-like of shape (n_samples, n_config)) –
Returns:
-
ndarray of shape (n_samples,)–expm1(predicted log V); positive means predicted beyond the frontier.
predict_std(X)
¶
Standard deviation of the predicted metrics, by the delta method.
Available only when the regressor's predict accepts return_std (for example
GaussianProcessRegressor); otherwise accessing it raises AttributeError.
Parameters:
-
X(array-like of shape (n_samples, n_config)) –
Returns:
-
ndarray of shape (n_samples,) or (n_samples, n_metrics)–m_j * sqrt(sum_k J_jk^2 s_k^2)wheres_kis the regressor's standard deviation of coordinatekandJ = d log m / d coordinates(exact: the chart is affine in log-metrics). Coordinates are treated as independent, and a regressor returning one standard deviation per row shares it across coordinates.
score(X, y, sample_weight=None)
¶
R^2 in coordinate space, uniformly averaged over Z and log V.
Parameters:
-
X(array-like of shape (n_samples, n_config)) – -
y(array-like of shape (n_samples,) or (n_samples, n_metrics)) –True metrics (positive); mapped through the fitted chart for comparison.
-
sample_weight(array-like of shape (n_samples,), default:None) –
Returns:
-
float–
design_tensions¶
The tensions at each design's own metric ratios, on the term it belongs to (from the data).
The formula of :func:tension_matrix evaluated at the design's own metrics m instead of a
term's balanced point. The level of the design does not matter: a level set is the surface
scaled (Theorem 1), which leaves the ratios m_j / m_i alone. With the fitted
preconditioner and the designs' raw attributes the tensions are also given in the
attributes' own units, through the conditioning log m_j = alpha_j log(a_j + s_j) + b_j::
d s_j / d s_i = -(w_i alpha_i) / (w_j alpha_j) (a_j + s_j) / (a_i + s_i)
Its sign is minus the sign of alpha_i alpha_j: negative for two attributes of one
orientation, positive for mixed orientation.
Parameters:
-
estimator(HyperbolicTradeSpace) –Fitted estimator.
-
X(array-like of shape (n_samples, n_features)) –The designs' metrics (nonnegative).
-
preconditioner(LogAffinePreconditioner, default:None) –The fitted conditioning that produced
Xfromattributes. -
attributes(array-like of shape (n_samples, n_features), default:None) –The designs' raw attributes, the input of
preconditioner. -
threshold(float, default:1e-3) –Exponents above this carry the metric.
Returns:
-
DesignTensions–
Raises:
-
ValueError–If only one of
preconditionerandattributesis given, or the shapes disagree.
Notes
A tension is a rate along the fitted reference surface with the other metrics held. For metrics that move together in the data (a fleet's cost is the unit cost times its size) it is not a move a design can make, and it is never the effect of changing a design variable.
Examples:
>>> import numpy as np
>>> from tradespace import (
... HyperbolicTradeSpace, design_tensions, make_frontier_data)
>>> X, _ = make_frontier_data(300, 3, random_state=0)
>>> est = HyperbolicTradeSpace(temperature=20.0).fit(X)
>>> dt = design_tensions(est, X[:2])
>>> dt.tensions.shape, dt.term.tolist()
((2, 3, 3), [0, 0])
>>> bool(np.allclose(dt.tensions[:, 0, 1] * dt.tensions[:, 1, 0], 1.0))
True
frontier_in_original_units¶
The fitted frontier as a monomial in the raw attributes.
With log m_j = alpha_j log(a_j + s_j) + b_j and log V = w . log m - beta the frontier
is V = exp(log_const) * prod_j (s_j + shift_j)^(exponents_orig_j) for raw attributes
s_j, where exponents_orig_j = w_j alpha_j and log_const = w . b - beta. A negative
exponent marks a smaller-is-better attribute.
Parameters:
-
estimator(HyperbolicTradeSpace) –Fitted on the preconditioner's output (
n_terms = 1). -
preconditioner(LogAffinePreconditioner) –Fitted preconditioner that produced the estimator's input.
Returns:
-
dict–exponents_orig(ndarray(d,)),log_const(float),shift(ndarray(d,)). Evaluatelog V = log_const + exponents_orig @ log(X + shift).
Examples:
>>> import numpy as np
>>> from tradespace import (
... HyperbolicTradeSpace, LogAffinePreconditioner,
... frontier_in_original_units)
>>> rng = np.random.RandomState(0)
>>> X = np.exp(rng.randn(40, 3))
>>> pre = LogAffinePreconditioner(orientation=[1, -1, 1]).fit(X)
>>> est = HyperbolicTradeSpace().fit(pre.transform(X))
>>> f = frontier_in_original_units(est, pre)
>>> logv = f["log_const"] + np.log(X + f["shift"]) @ f["exponents_orig"]
>>> bool(np.allclose(logv, est.score_samples(pre.transform(X))))
True
make_configured_frontier_data¶
Frontier data whose metrics are a known smooth map of a configuration.
Parameters:
-
n_samples(int) –Rows and metrics
d. -
n_features(int) –Rows and metrics
d. -
n_config(int) –Number of configuration variables,
>= 2. -
exponents–As in
make_frontier_data. -
log_offset–As in
make_frontier_data. -
frontier_fraction–As in
make_frontier_data. -
noise–As in
make_frontier_data. -
random_state–As in
make_frontier_data. -
interior_scale(float, default:1.0) –Depth scale:
log V = -interior_scale * (c . g)^2for a fixed unit vectorg; frontier rows are projected ontoc . g = 0so they lie exactly on the frontier. -
nonlinearity(float, default:0.1) –Amplitude of the nonlinear term in
Z(c) = c A + nonlinearity * sin(c A2).
Returns:
-
X_config(ndarray of shape (n_samples, n_config)) –Configurations
c ~ N(0, I)(frontier rows projected). -
Y_metrics(ndarray of shape (n_samples, n_features)) –Strictly positive metrics
exp(from_frontier_coordinates(Z(c), log V(c) + noise)). -
info(dict) –As in
make_frontier_data(without noise-free redundancy), plusconfig_map: a callablec -> (Z, log_v)giving the noise-free truth for any configuration, andZ,log_vof the training rows (noise included inlog_vfor frontier rows).
Examples:
>>> C, Y, info = make_configured_frontier_data(100, 3, 4, random_state=1)
>>> C.shape, Y.shape, bool((Y > 0).all())
((100, 4), (100, 3), True)
>>> Z, lv = info["config_map"](C)
>>> bool(abs(lv[info["frontier_mask"]]).max() < 1e-12)
True
make_frontier_data¶
Sample metrics around a planted monomial frontier prod m_j^{w_j} = e^{beta}.
Parameters:
-
n_samples(int) –Number of rows.
-
n_features(int) –Number of metrics
d(d = 1gives a single column and noZ). -
exponents(array-like of shape (n_features,) or (n_terms, n_features), default:None) –Planted exponents on the simplex (one row per term for
n_terms > 1). Default forn_terms = 1: a seeded random point with everyw_j >= 0.5/d. Default forn_terms = K > 1: K Dirichlet(1) draws, redrawn (at most 1000 tries, thenValueError) until every pair is at least 0.3 apart in L1. -
log_offset(float, default:0.0) –Planted
beta. -
frontier_fraction(float, default:0.3) –Fraction of rows placed on the frontier (
log Vequal tonoise * N(0,1)). -
interior_scale(float, default:1.0) –Interior rows have
log V = -Exp(interior_scale)(mean depthinterior_scale). -
noise(float, default:0.0) –Standard deviation of the log-V noise of frontier rows.
-
random_state((int, RandomState or None), default:None) –Seed.
-
n_terms(int, default:1) –Number of planted monomials K.
1reproduces the one-term frontier exactly;K > 1plants the envelopePhi(u) = max_k (w_k . u - beta)and putslog V = Phi(u).
Returns:
-
X(ndarray of shape (n_samples, n_features)) –Strictly positive metrics.
-
info(dict) –Keys
exponents(shape(d,)at K = 1,(K, d)otherwise),log_offset,basis(ILR chart),frontier_mask,Z,log_v,noise,interior_scale; forn_terms > 1alsoterm, an integer array of shape(n_samples,)holdingargmax_k w_k . log x(the term each row lies on or under).
Notes
For n_terms > 1 every planted term gets at least n_features + 1 frontier rows
(identifiability: a term with fewer frontier rows than dimensions is not determined by them).
If a term falls short after the draw, further rows of that term, chosen by the seeded
generator, are moved onto the frontier (so the frontier fraction can slightly exceed
frontier_fraction); a term with too few rows overall raises ValueError.
Z ~ N(0, I) and the rows are mapped back through the ILR chart; the frontier is
identifiable when the Z-hull of the frontier rows contains 0. For K > 1 the
rows are u = C Z + s 1 with s = log V + beta - max_k w_k . C Z (the K-term form of
from_frontier_coordinates; sum w_k = 1 makes Phi(u) = log V exact).
Examples:
>>> X, info = make_frontier_data(200, 3, random_state=0)
>>> X.shape, bool((X > 0).all()), round(float(info["exponents"].sum()), 6)
((200, 3), True, 1.0)
>>> X, info = make_frontier_data(200, 4, n_terms=3, random_state=0)
>>> info["exponents"].shape, int(info["term"].max()) < 3
((3, 4), True)
select_temperature¶
Choose the temperature tau whose fit has a target fraction of designs above V = 1.
For tau of about 3 and above, the fitted frac_above_ falls as tau grows (a harder
maximum leaves fewer designs beyond the frontier; the log-mean-exp is within log(n)/tau of
the maximum). It is not monotone for small tau: the log-mean-exp lies between the mean and
the maximum of the scores and tends to the mean as tau -> 0, so frac_above_ can
overshoot 0.5 below tau of about 3 (the project's reading: the soft maximum tends to the
mean of the scores, not the median) before decreasing toward 0 as tau grows. tau below
about 3 is outside the documented useful range. Bisection only needs the target bracketed by the
fractions at the ends of bounds (checked, ValueError otherwise); it returns a tau
with |frac_above_ - target_frac_above| <= tol found in at most 60
iterations on log tau. Keep bounds[0] near or above 3 for a unique answer.
The default bounds[0] = 0.1 is wider than the recommended tau of about 3 or more:
bisection tolerates it because it needs only that the target be bracketed by the ends of
bounds (ValueError otherwise), but below tau of about 3 the frac_above_
response is not monotone, so the returned tau is a root of the bracket search; callers
who need the useful range should pass bounds=(3, ...).
Parameters:
-
X(array-like of shape (n_samples, n_features)) –Strictly positive larger-is-better metrics (already conditioned).
-
target_frac_above(float, default:0.10) –Target fraction of training rows with
V > 1, in(0, 1). -
bounds(tuple of float, default:(1e-1, 1e4)) –(low, high)search interval fortau,0 < low < high. -
tol(float, default:0.01) –Accepted absolute error of
frac_above_. -
**params–Other
HyperbolicTradeSpaceparameters (min_exponent,coordinates, ...);temperatureis not allowed.
Returns:
-
temperature(float) –The selected
tau. Iffrac_above_is a step function and notauis withintol(few samples), the closest one is returned with aUserWarning.
Raises:
-
ValueError–If the target is not bracketed by the fits at
bounds. The message gives the fractions at both ends and what to try (a target within the achieved range, a fixedtemperature, widerbounds). Forn_terms > 1the terms are not supporting planes (rows can lie above them), sofrac_above_levels off above zero astaugrows and the default target 0.10 may be out of reach.
Notes
tau has units of 1 / (log-spread of the metrics), so the answer depends on the
conditioning of X.
Examples:
>>> from tradespace import HyperbolicTradeSpace, make_frontier_data
>>> from tradespace import select_temperature
>>> X, _ = make_frontier_data(300, 3, noise=0.05, random_state=0)
>>> tau = select_temperature(X, 0.10)
>>> est = HyperbolicTradeSpace(temperature=tau).fit(X)
>>> abs(est.frac_above_ - 0.10) <= 0.01
True
tension_matrix¶
The tension matrix of every term, at the term's balanced point (from the fit).
The tension of metric j against metric i on a term is the derivative of m_j with
respect to m_i along the term, the other metrics held, in the conditioned metrics::
T[i, j] = d m_j / d m_i = -(w_i / w_j) (m_j / m_i)
(Definition of tension; derived in derivation/lemma_21_tension.py). The elasticity
-w_i / w_j is its log-log form and is constant on a term; the tension carries the factor
m_j / m_i and so changes along the term. The term's matrix evaluates it at the term's
balanced point, the softmax-weighted mean log-metric of the rows assigned to the term at the
fit temperature. A design's tensions, from the data, are another object
(:func:design_tensions).
Parameters:
-
estimator(HyperbolicTradeSpace) –Fitted estimator.
-
X(array-like of shape (n_samples, n_features)) –Metrics (nonnegative) whose rows locate each term's balanced point; rows with a zero metric are ignored. At
n_terms > 1each row counts for the term it is assigned to (assign_cells). -
threshold(float, default:1e-3) –Exponents above this carry the metric (the package's participation threshold).
Returns:
-
ndarray of shape (n_terms, n_features, n_features)–Entry
[k, i, j]is the tension ofjagainstion termk: negative where both metrics carry an exponent on the term;0.0whereicarries none andjdoes (raisingimoves nothing along the term);nanwherejcarries none (the derivative is undefined, so the cell is blank and not zero) and on the diagonal. Where both entries of a pair are nonzero,T[k, i, j] * T[k, j, i] = 1. A term that owns no row has an all-nanmatrix.
Notes
At n_terms > 1 the surface is the maximum of the terms, so each term has its own matrix;
near a seam the two terms' values differ and neither is the surface's. The tension is a partial
derivative along the fitted reference surface with the other metrics held, not the effect of
changing a design variable.
Examples:
>>> import numpy as np
>>> from tradespace import (
... HyperbolicTradeSpace, make_frontier_data, tension_matrix)
>>> X, _ = make_frontier_data(300, 3, random_state=0)
>>> est = HyperbolicTradeSpace(temperature=20.0).fit(X)
>>> T = tension_matrix(est, X)
>>> T.shape
(1, 3, 3)
>>> bool((T[0][~np.eye(3, dtype=bool)] < 0).all())
True
trade_off_report¶
Report the trade-offs of a fitted trade space (a list of K reports when n_terms = K > 1).
Parameters:
-
estimator(HyperbolicTradeSpace) –Fitted estimator.
-
X(array-like of shape (n_samples, n_features)) –Metrics (nonnegative); rows with a zero metric are ignored. The
tau = infLP is solved on the log of these rows, independent of the fit temperature andmin_exponent. -
band(float, default:None) –Near-frontier rows are those with
|log V| < band. Default1 / taufor finitetauand 0.1 attau = inf. -
min_near_frontier(int, default:10) –Fewer near-frontier rows raises
ValueError. -
threshold(float, default:1e-3) –Exponents above this participate at the fit temperature.
-
association(('pearson', 'spearman'), default:"pearson") –Association measure for the log-metrics of near-frontier rows.
Returns:
-
TradeOffReport or list of TradeOffReport–One report at
n_terms = 1; atn_terms = K > 1a list of K, one per term, each on the rows assigned to that term with the term's exponents, near-frontier rows (|Phi_K| < band), spread directions and loadings (throughbasis_[k]).
Raises:
-
ValueError–If
associationis unknown or fewer thanmin_near_frontierrows are near the frontier; the message gives theband(and the fit temperature that matches it, since the default band is1 / tau) that would holdmin_near_frontierrows; at K > 1 it names the term.
Warns:
-
UserWarning–If
estimator.min_exponent > 0: the working weights are floored, and the contending set (always computed withmin_exponent = 0) can differ from the working support.
Notes
For d = 1 the report is trivial (w = [1], a monolemma, no directions). The report is
deterministic. Part 3 equals orient_by_pca(Z, |log V| < band) on the same rows
(tradespace.gaps.orient_by_pca). The closure effect is stated in
closure_note and in the module docstring.
Examples:
>>> import numpy as np
>>> from tradespace import (
... HyperbolicTradeSpace, make_frontier_data, trade_off_report)
>>> X, _ = make_frontier_data(400, 3, random_state=0)
>>> est = HyperbolicTradeSpace(temperature=np.inf).fit(X)
>>> rep = trade_off_report(est, X)
>>> rep.lemma_name, rep.contending_set.tolist(), rep.spread_directions.shape
('trilemma', [0, 1, 2], (2, 2))
At n_terms = 3 there is one report per term:
>>> W = [[.5, .5, 0, 0], [0, .5, .5, 0], [0, 0, .5, .5]]
>>> X, _ = make_frontier_data(900, 4, exponents=W, n_terms=3, random_state=0)
>>> est = HyperbolicTradeSpace(
... n_terms=3, temperature=20.0, random_state=0).fit(X)
>>> sorted(r.contending_set.tolist() for r in trade_off_report(est, X))
[[0, 1], [1, 2], [2, 3]]
__version__¶
-
Fabian Pedregosa, Gaël Varoquaux, Alexandre Gramfort, Vincent Michel, Bertrand Thirion, Olivier Grisel, Mathieu Blondel, Peter Prettenhofer, Ron Weiss, Vincent Dubourg, Jake Vanderplas, Alexandre Passos, David Cournapeau, Matthieu Brucher, Matthieu Perrot, and Édouard Duchesnay. Scikit-learn: machine learning in Python. Journal of Machine Learning Research, 12:2825–2830, 2011. URL: https://jmlr.org/papers/v12/pedregosa11a.html. ↩
-
Lars Buitinck, Gilles Louppe, Mathieu Blondel, Fabian Pedregosa, Andreas Mueller, Olivier Grisel, Vlad Niculae, Peter Prettenhofer, Alexandre Gramfort, Jaques Grobler, Robert Layton, Jake Vanderplas, Arnaud Joly, Brian Holt, and Gaël Varoquaux. API design for machine learning software: experiences from the scikit-learn project. 2013. arXiv:1309.0238. doi:10.48550/arXiv.1309.0238. ↩