Skip to main content

OlsFit

Struct OlsFit 

Source
pub struct OlsFit { /* private fields */ }
Expand description

A fitted ordinary-least-squares model: the shared representation every diagnostic in this crate is computed from.

§Intercept convention

The caller owns the design matrix X, including any intercept column. This crate does not silently prepend a column of ones. There are two constructors, and the choice is explicit at the call site:

  • OlsFit::new fits exactly the columns you pass. If one of them is constant it is auto-detected and treated as the intercept (this drives the centered-vs-uncentered choice, and excludes that column from VIF); if none is constant the model is fit through the origin.
  • OlsFit::with_intercept prepends a ones column for you and marks it as the intercept.

Getting this wrong silently corrupts every downstream diagnostic, so the convention is stated here rather than buried in the implementation.

§What is computed and cached

Construction performs a single QR factorization of X and caches the coefficients, fitted values, residuals, leverage vector diag(H), (XᵀX)⁻¹, the design’s singular values, and the residual variance. Diagnostics read these cached quantities rather than refactorizing.

Coefficients are obtained by a QR solve of X, never by inverting XᵀX — that matters for the multicollinearity diagnostics specifically, since forming XᵀX squares the condition number they exist to measure. Leverage is read from the thin Q factor, so the full n × n hat matrix is never formed.

§Example

use ndarray::{array, Array2};
use regression_diagnostics::OlsFit;

// y = 1 + 2*x exactly; supply the intercept ourselves.
let x = array![[1.0, 0.0], [1.0, 1.0], [1.0, 2.0], [1.0, 3.0]];
let y = array![1.0, 3.0, 5.0, 7.0];
let fit = OlsFit::new(x, y).unwrap();
assert!((fit.coefficients()[0] - 1.0).abs() < 1e-9);
assert!((fit.coefficients()[1] - 2.0).abs() < 1e-9);

Implementations§

Source§

impl OlsFit

Source

pub fn new(x: Array2<f64>, y: Array1<f64>) -> Result<Self>

Fit y ~ X by OLS, using the columns of X exactly as given.

A constant column, if present, is auto-detected as the intercept. See the type-level docs for the full convention.

§Errors
Source

pub fn with_intercept(x: Array2<f64>, y: Array1<f64>) -> Result<Self>

Fit y ~ [1 | X] by OLS, prepending a column of ones as the intercept.

Errors are the same as OlsFit::new, evaluated against the augmented design (so a design with n == p_original + 1 will fail the residual-degrees-of-freedom check).

Source

pub fn n_observations(&self) -> usize

Number of observations n.

Source

pub fn n_parameters(&self) -> usize

Number of model parameters p (design-matrix columns, intercept included if present).

Source

pub fn has_intercept(&self) -> bool

Whether the model includes an intercept (constant) column.

Source

pub fn intercept_column(&self) -> Option<usize>

Index of the intercept column within the design matrix, if any.

Source

pub fn design_matrix(&self) -> ArrayView2<'_, f64>

The design matrix X as fitted (with the intercept column if one was added or detected).

Source

pub fn response(&self) -> ArrayView1<'_, f64>

The response vector y.

Source

pub fn coefficients(&self) -> ArrayView1<'_, f64>

Estimated coefficients, one per design-matrix column.

Source

pub fn fitted_values(&self) -> ArrayView1<'_, f64>

Fitted values ŷ = X β.

Source

pub fn residuals(&self) -> ArrayView1<'_, f64>

Raw residuals e = y − ŷ.

Source

pub fn leverage(&self) -> ArrayView1<'_, f64>

Leverage vector diag(H). Each entry lies in [0, 1] and the vector sums to p (the number of parameters) — a standard identity worth checking as a correctness probe.

Source

pub fn residual_sum_of_squares(&self) -> f64

Residual sum of squares Σ eᵢ².

Source

pub fn df_residual(&self) -> f64

Residual degrees of freedom n − p.

Source

pub fn df_model(&self) -> f64

Model degrees of freedom: p − 1 with an intercept, p without.

Source

pub fn residual_variance(&self) -> f64

Unbiased residual variance estimate s² = RSS / (n − p).

Source

pub fn residual_standard_error(&self) -> f64

Residual standard error s = √(RSS / (n − p)).

Source

pub fn coefficient_standard_errors(&self) -> Array1<f64>

Standard errors of the coefficients: sⱼ = s · √((XᵀX)⁻¹ⱼⱼ).

Source

pub fn singular_values(&self) -> &[f64]

Singular values of the design matrix, in descending order.

Source§

impl OlsFit

Source

pub fn summary(&self) -> Summary

Compute the full Summary for this fit — every statistic in Milestones 2–6 in one call.

use ndarray::array;
use regression_diagnostics::OlsFit;

let x = array![[1.0, 0.0], [1.0, 1.0], [1.0, 2.0], [1.0, 3.0], [1.0, 4.0]];
let y = array![1.0, 3.1, 4.9, 7.0, 9.1];
let fit = OlsFit::new(x, y).unwrap();
let s = fit.summary();
println!("{s}");
assert!(s.r_squared > 0.99);

Trait Implementations§

Source§

impl Clone for OlsFit

Source§

fn clone(&self) -> OlsFit

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 OlsFit

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

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<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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> 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<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