MultipleLinearRegression

Struct MultipleLinearRegression 

Source
pub struct MultipleLinearRegression<T = f64>
where T: Float + Debug + Default + Serialize,
{ pub coefficients: Vec<T>, pub r_squared: T, pub adjusted_r_squared: T, pub standard_error: T, pub n: usize, pub p: usize, }
Expand description

Multiple linear regression model that fits a hyperplane to multivariate data points.

Fields§

§coefficients: Vec<T>

Regression coefficients, including intercept as the first element

§r_squared: T

Coefficient of determination (R²) - goodness of fit

§adjusted_r_squared: T

Adjusted R² which accounts for the number of predictors

§standard_error: T

Standard error of the estimate

§n: usize

Number of data points used for regression

§p: usize

Number of predictor variables (excluding intercept)

Implementations§

Source§

impl<T> MultipleLinearRegression<T>
where T: Float + Debug + Default + NumCast + Serialize + for<'de> Deserialize<'de>,

Source

pub fn new() -> Self

Create a new multiple linear regression model without fitting any data

Source

pub fn fit<U, V>( &mut self, x_values: &[Vec<U>], y_values: &[V], ) -> StatsResult<()>
where U: NumCast + Copy, V: NumCast + Copy,

Fit a multiple linear regression model to the provided data

§Arguments
  • x_values - 2D array where each row is an observation and each column is a predictor
  • y_values - Dependent variable values (observations)
§Returns
  • StatsResult<()> - Ok if successful, Err with StatsError if the inputs are invalid
§Errors

Returns StatsError::EmptyData if input arrays are empty. Returns StatsError::DimensionMismatch if X and Y arrays have different lengths. Returns StatsError::InvalidInput if rows in X have inconsistent lengths. Returns StatsError::ConversionError if value conversion fails. Returns StatsError::MathematicalError if the linear system cannot be solved.

Source

pub fn predict<U>(&self, x: &[U]) -> StatsResult<T>
where U: NumCast + Copy,

Predict y value for a given set of x values using the fitted model

§Arguments
  • x - Vector of x values for prediction (must match the number of features used during fitting)
§Returns
  • StatsResult<T> - The predicted y value
§Errors

Returns StatsError::NotFitted if the model has not been fitted (coefficients is empty). Returns StatsError::DimensionMismatch if the number of features doesn’t match the model (x.len() != p). Returns StatsError::ConversionError if type conversion fails.

§Examples
use rs_stats::regression::multiple_linear_regression::MultipleLinearRegression;

let mut model = MultipleLinearRegression::<f64>::new();
let x = vec![
    vec![1.0, 2.0],
    vec![2.0, 1.0],
    vec![3.0, 3.0],
    vec![4.0, 2.0],
];
let y = vec![5.0, 4.0, 9.0, 8.0];
model.fit(&x, &y).unwrap();

let prediction = model.predict(&[3.0, 4.0]).unwrap();
Source

pub fn predict_many<U>(&self, x_values: &[Vec<U>]) -> StatsResult<Vec<T>>
where U: NumCast + Copy,

Calculate predictions for multiple observations

§Arguments
  • x_values - 2D array of feature values for prediction
§Returns
  • StatsResult<Vec<T>> - Vector of predicted y values
§Errors

Returns StatsError::NotFitted if the model has not been fitted. Returns an error if any prediction fails (dimension mismatch or conversion error).

§Examples
use rs_stats::regression::multiple_linear_regression::MultipleLinearRegression;

let mut model = MultipleLinearRegression::<f64>::new();
let x = vec![
    vec![1.0, 2.0],
    vec![2.0, 1.0],
    vec![3.0, 3.0],
    vec![4.0, 2.0],
];
let y = vec![5.0, 4.0, 9.0, 8.0];
model.fit(&x, &y).unwrap();

let predictions = model.predict_many(&[vec![3.0, 4.0], vec![5.0, 6.0]]).unwrap();
assert_eq!(predictions.len(), 2);
Source

pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<(), Error>

Save the model to a file

§Arguments
  • path - Path where to save the model
§Returns
  • Result<(), io::Error> - Ok if successful, Err with IO error if saving fails
Source

pub fn save_binary<P: AsRef<Path>>(&self, path: P) -> Result<(), Error>

Save the model in binary format

§Arguments
  • path - Path where to save the model
§Returns
  • Result<(), io::Error> - Ok if successful, Err with IO error if saving fails
Source

pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, Error>

Load a model from a file

§Arguments
  • path - Path to the saved model file
§Returns
  • Result<Self, io::Error> - Loaded model or IO error
Source

pub fn load_binary<P: AsRef<Path>>(path: P) -> Result<Self, Error>

Load a model from a binary file

§Arguments
  • path - Path to the saved model file
§Returns
  • Result<Self, io::Error> - Loaded model or IO error
Source

pub fn to_json(&self) -> Result<String, String>

Save the model to a string in JSON format

§Returns
  • Result<String, String> - JSON string representation or error message
Source

pub fn from_json(json: &str) -> Result<Self, String>

Load a model from a JSON string

§Arguments
  • json - JSON string containing the model data
§Returns
  • Result<Self, String> - Loaded model or error message

Trait Implementations§

Source§

impl<T> Clone for MultipleLinearRegression<T>
where T: Float + Debug + Default + Serialize + Clone,

Source§

fn clone(&self) -> MultipleLinearRegression<T>

Returns a duplicate of the value. Read more
1.0.0§

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

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for MultipleLinearRegression<T>
where T: Float + Debug + Default + Serialize + Debug,

Source§

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

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

impl<T> Default for MultipleLinearRegression<T>
where T: Float + Debug + Default + NumCast + Serialize + for<'de> Deserialize<'de>,

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de, T> Deserialize<'de> for MultipleLinearRegression<T>
where T: Float + Debug + Default + Serialize + Deserialize<'de>,

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<T> Serialize for MultipleLinearRegression<T>

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§

§

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

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

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

§

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

Mutably borrows from an owned value. Read more
§

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

§

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
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

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

§

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
§

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

§

type Owned = T

The resulting type after obtaining ownership.
§

fn to_owned(&self) -> T

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

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

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

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

§

type Error = Infallible

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

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

Performs the conversion.
§

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

§

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

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

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

Performs the conversion.
Source§

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