Skip to main content

MultinomialSavedModel

Struct MultinomialSavedModel 

Source
pub struct MultinomialSavedModel {
Show 19 fields pub formula: String, pub class_levels: Vec<String>, pub reference_class_index: usize, pub resolved_termspec: TermCollectionSpec, pub coefficients_flat: Vec<f64>, pub p_per_class: usize, pub n_active_classes: usize, pub training_headers: Vec<String>, pub lambdas: Vec<f64>, pub lambdas_per_block: Vec<usize>, pub iterations: usize, pub converged: bool, pub penalized_neg_log_likelihood: f64, pub deviance: f64, pub edf_per_class: Option<Vec<f64>>, pub coefficient_covariance_flat: Option<Vec<f64>>, pub coefficient_influence_flat: Option<Vec<f64>>, pub smooth_term_spans: Vec<MultinomialSmoothTermSpan>, pub lambda_labels: Vec<String>,
}
Expand description

Saved-model payload for a multinomial fit driven by a Wilkinson formula.

This is what the FFI returns to Python. It carries everything the Python MultinomialModel.predict path needs to evaluate softmax(X_new · β) on fresh data using the training basis / penalty structure (no refit on predict, no re-derivation of class levels).

Fields§

§formula: String

The training formula, verbatim. Stored so Python’s summary() and any round-trip persistence path can echo what was fit.

§class_levels: Vec<String>

Names of the training response levels in canonical order. The last entry is the reference class (η = 0); the first K - 1 carry the active linear-predictor blocks. Class permutations are forbidden: this list is fixed at fit time and predictions emit columns in the same order.

§reference_class_index: usize

Index of the reference class within class_levels — currently always class_levels.len() - 1, exposed as a field so future “user-pinned reference” gauges (e.g. family='multinomial', reference='setosa') can land without changing the on-disk shape.

§resolved_termspec: TermCollectionSpec

Resolved term-collection spec used to build X at fit time. Replayed on predict via gam_terms::smooth::build_term_collection_design.

§coefficients_flat: Vec<f64>

Active-class coefficient block, shape (P, K-1). Column a is the coefficient vector for class class_levels[a]. Stored flat in row-major order to keep the serde payload self-describing.

§p_per_class: usize

P — coefficient count per active class. Matches the column count of the design matrix the saved resolved_termspec produces.

§n_active_classes: usize

Number of active classes (K - 1).

§training_headers: Vec<String>

Original training column headers, in dataset-column order. Needed at predict time so the FFI can align a fresh Dataset to the training schema before evaluating the basis.

§lambdas: Vec<f64>

REML/LAML-selected smoothing parameters, one per (active class, smooth term), flattened in block-major order: all of class 0’s per-term λ, then class 1’s, and so on. Per-term penalties (#561) mean each active class block selects an independent λ for every smooth term, so this vector has length Σ_a (#terms in class a) = (K − 1) · #terms. Use MultinomialSavedModel::lambdas_per_block to segment it by class. An unpenalized model (no smooth terms) yields an empty vector.

§lambdas_per_block: Vec<usize>

Number of smoothing parameters (smooth terms) in each active class block, parallel to class_levels[0..K-1]. Segments the flat lambdas vector: class a’s λ are lambdas[Σ_{b<a} lambdas_per_block[b] ..][.. lambdas_per_block[a]]. Every entry is identical in the shared-design architecture (all classes share the same term structure), but it is stored explicitly so consumers never have to assume that.

§iterations: usize

Newton iterations executed; recorded for the summary report.

§converged: bool

true if the inner Newton solver hit the relative-step tolerance.

§penalized_neg_log_likelihood: f64

Penalized negative log-likelihood at the returned β̂.

§deviance: f64

Unpenalized deviance −2 log L(β̂).

§edf_per_class: Option<Vec<f64>>

Per-active-class effective degrees of freedom (hat-matrix trace), length K - 1. Populated when the REML driver reports an inference block; falls back to None for the legacy fixed-λ path.

§coefficient_covariance_flat: Option<Vec<f64>>

Joint posterior coefficient covariance H⁻¹ (#1101), block-ordered to match the stacked active-class coefficient vector β = [β_0; …; β_{K-2}] (class a’s P coefficients occupy rows/cols a·P .. (a+1)·P). This is the Laplace covariance the REML driver already computes from the factored penalized Hessian; storing it gives the predict path delta-method per-class probability standard errors and the summary its Wald smooth-term tests. Flattened row-major over the (P·M)×(P·M) matrix. None for a model fitted before covariance was surfaced.

§coefficient_influence_flat: Option<Vec<f64>>

Joint coefficient-space influence matrix F = H⁻¹ X'WX (#1101), block-ordered identically to Self::coefficient_covariance_flat. Its per-term diagonal block trace is the term’s effective degrees of freedom and its tr(F_jj)²/tr(F_jj²) the Wood reference d.f., feeding the rank-truncated Wald smooth-term test in summary(). Flattened row-major over the (P·M)×(P·M) matrix. None when unavailable.

§smooth_term_spans: Vec<MultinomialSmoothTermSpan>

Per-(active class, smooth term) coefficient column range and unpenalized nullspace dimension within the P-wide class block (#1101). Parallel to the smooth terms the design produced; replicated across classes by the shared-design architecture. Drives the Wald smooth-term table in summary(). Empty for a wholly parametric (no-smooth) model.

§lambda_labels: Vec<String>

One descriptive label per penalty component within a single active-class block, parallel to that block’s λ slice (i.e. length lambdas_per_block[0]). The Marra–Wood double penalty (and tensor / operator smooths) emit more than one penalty component — hence more than one λ — per smooth term, so this is NOT 1:1 with Self::smooth_term_spans: a single s(x) term contributes a primary wiggliness λ labelled s(x) and a null-space shrinkage λ labelled s(x) [null space]. The summary renderer pairs lambdas with these labels component-for-component so no λ is ever dropped (#1544). Built from the per-component term name + penalty role at fit time; empty for a wholly parametric model or a model serialized before this field existed.

Implementations§

Source§

impl MultinomialSavedModel

Source

pub fn coefficients_active(&self) -> Array2<f64>

Active-class coefficient block as an (P, K-1) ndarray view.

Source

pub fn predict_probabilities(&self, x_new: ArrayView2<'_, f64>) -> Array2<f64>

Evaluate softmax(X · β) at fresh data rows. X_new must have self.p_per_class columns (i.e. it was built from the same resolved_termspec as fit time). Returns an (N_new, K) matrix with rows summing to 1; column order matches self.class_levels.

Source

pub fn coefficient_covariance(&self) -> Option<Array2<f64>>

Reconstruct the joint posterior covariance H⁻¹ as a (P·M)×(P·M) ndarray, block-ordered to match the stacked coefficient vector θ[a·P + i] = β[i, a] (#1101). None when the model was fitted before covariance was surfaced (legacy payload).

Source

pub fn coefficient_influence(&self) -> Option<Array2<f64>>

Reconstruct the joint influence matrix F = H⁻¹ X'WX as a (P·M)×(P·M) ndarray, block-ordered like Self::coefficient_covariance (#1101). None when unavailable.

Source

pub fn predict_probabilities_with_se( &self, x_new: ArrayView2<'_, f64>, ) -> (Array2<f64>, Option<Array2<f64>>)

Evaluate softmax(X·β) AND its delta-method per-class probability standard error at fresh data rows (#1101).

For active classes b ∈ 0..M the softmax Jacobian is ∂p_c/∂η_b = p_c (δ_{cb} − p_b), and ∂η_b/∂β[i,a] = X[i]·δ_{ab}, so the gradient of class-c probability w.r.t. the block-ordered coefficient vector is g_c[a·P + i] = X[i]·p_c (δ_{ca} − p_a) (active a; the reference class M contributes p_c(0 − p_a) via every active block). The delta-method variance is Var(p_c) = g_cᵀ Σ g_c with Σ = H⁻¹ the joint posterior covariance, and SE(p_c) = √Var(p_c). Returns (probs (N,K), prob_se (N,K)); prob_se is None when no covariance is stored. The simplex [0,1] clamp is applied by the interval consumer, not here (the SE itself is unclamped).

Source

pub fn smooth_significance(&self) -> Vec<MultinomialSmoothSignificance>

Wood (2013) rank-truncated Wald smooth-significance test per (active class, smooth term) (#1101), reusing the exact scalar-summary kernel gam_terms::inference::smooth_test::wood_smooth_test. For active class a and term span [c0, c1) within the class block, the global coefficient range is a·P + c0 .. a·P + c1; the joint covariance and influence are sliced there. The term EDF is the influence-block trace tr(F_jj) (when present) and the reference d.f. uses tr(F_jj)²/tr(F_jj²), exactly as the scalar path. The multinomial softmax is a known-dispersion family, so the χ²_{ref_df} branch applies. Returns one row per (class label, term label, edf, ref_df, statistic, p_value); empty when no covariance/smooth terms are available.

Trait Implementations§

Source§

impl Clone for MultinomialSavedModel

Source§

fn clone(&self) -> MultinomialSavedModel

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for MultinomialSavedModel

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for MultinomialSavedModel

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for MultinomialSavedModel

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Allocation for T
where T: RefUnwindSafe + Send + Sync,

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ByRef<T> for T

Source§

fn by_ref(&self) -> &T

Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> DistributionExt for T
where T: ?Sized,

Source§

fn rand<T>(&self, rng: &mut (impl Rng + ?Sized)) -> T
where Self: Distribution<T>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Imply<T> for U
where T: ?Sized, U: ?Sized,

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V