LinearRegression

Struct LinearRegression 

Source
pub struct LinearRegression<T: RealNumber> { /* private fields */ }
Expand description

Represents a linear regression model.

The LinearRegression struct implements a linear regression model for predicting a target variable based on one or more input features. It uses the least squares method to estimate the weights of the linear model.

§Type Parameters

  • T: The numeric type used for calculations. Must implement the RealNumber trait.

§Fields

  • weights: The weights of the logistic regression model, with the first being the bias weight.

§Examples

use rusty_ai::regression::linear::LinearRegression;
use rusty_ai::data::dataset::Dataset;
use nalgebra::{DMatrix, DVector};

// Create a new linear regression model
let mut model = LinearRegression::<f64>::new();

// Fit the model to a dataset
let x = DMatrix::from_row_slice(3, 2, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
let y = DVector::from_vec(vec![1.5, 2.5, 3.5]);
let dataset = Dataset::new(x, y);
let learning_rate = 0.01;
let max_steps = 1000;
let epsilon = Some(0.001);
let progress = Some(100);
let result = model.fit(&dataset, learning_rate, max_steps, epsilon, progress);

// Make predictions using the trained model
let x_test = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 3.0, 4.0]);
let predictions = model.predict(&x_test);
assert!(predictions.is_ok());

Implementations§

Source§

impl<T: RealNumber> LinearRegression<T>

Source

pub fn new() -> Self

Creates a new LinearRegression model with default weights.

The default weights are initialized to 1.0 for each feature, including the bias weight.

Source

pub fn with_params( dimension: Option<usize>, weights: Option<DVector<T>>, ) -> Result<Self, Box<dyn Error>>

Creates a new LinearRegression model with custom parameters.

§Arguments
  • dimension: The dimension of the input features. If None, the dimension will be inferred from the provided weights.
  • weights: The initial weights for the linear regression model. If None, default weights will be used.
§Returns

A Result containing the LinearRegression model if the parameters are valid, or an error message if the parameters are invalid.

§Errors

An error will be returned if:

  • Both dimension and weights are None.
  • The length of weights is not equal to dimension + 1 to account for the bias weight.
Source

pub fn weights(&self) -> &DVector<T>

A reference to the weights of the linear regression model.

Source

pub fn predict(&self, x_pred: &DMatrix<T>) -> Result<DVector<T>, Box<dyn Error>>

Makes predictions using the trained linear regression model.

§Arguments
  • x_pred: The input features for which to make predictions.
§Returns

A Result containing the predicted target values if successful, or an error message if an error occurs during prediction.

Source

pub fn fit( &mut self, dataset: &Dataset<T, T>, lr: T, max_steps: usize, epsilon: Option<T>, progress: Option<usize>, ) -> Result<String, Box<dyn Error>>

Fits the linear regression model to a dataset.

§Arguments
  • dataset: The dataset containing the input features and target values.
  • lr: The learning rate for gradient descent.
  • max_steps: The maximum number of steps to perform during training.
  • epsilon: The convergence threshold. If the change in weights is below this threshold, training will stop.
  • progress: The number of steps at which to display progress information. If None, no progress information will be displayed.
§Returns

A Result containing a success message if training is successful, or an error message if an error occurs during training.

§Errors

An error will be returned if:

  • The number of steps for progress visualization is 0.
  • The gradient turns to NaN during training.

Trait Implementations§

Source§

impl<T: Clone + RealNumber> Clone for LinearRegression<T>

Source§

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

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T: Debug + RealNumber> Debug for LinearRegression<T>

Source§

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

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

impl<T: RealNumber> Default for LinearRegression<T>

Source§

fn default() -> Self

Creates a new LinearRegression model with default weights.

The default weights are initialized to 1.0 for each feature, including the bias weight.

Source§

impl<T: RealNumber> RegressionMetrics<T> for LinearRegression<T>

Source§

fn mse( &self, y_true: &DVector<T>, y_pred: &DVector<T>, ) -> Result<T, Box<dyn Error>>

Computes the mean squared error (MSE) between the true values and the predicted values. Read more
Source§

fn mae( &self, y_true: &DVector<T>, y_pred: &DVector<T>, ) -> Result<T, Box<dyn Error>>

Computes the mean absolute error (MAE) between the true values and the predicted values. Read more
Source§

fn r2( &self, y_true: &DVector<T>, y_pred: &DVector<T>, ) -> Result<T, Box<dyn Error>>

Computes the coefficient of determination (R^2) between the true values and the predicted values. Read more

Auto Trait Implementations§

§

impl<T> Freeze for LinearRegression<T>

§

impl<T> RefUnwindSafe for LinearRegression<T>
where T: RefUnwindSafe,

§

impl<T> Send for LinearRegression<T>

§

impl<T> Sync for LinearRegression<T>

§

impl<T> Unpin for LinearRegression<T>
where T: Unpin,

§

impl<T> UnwindSafe for LinearRegression<T>
where T: UnwindSafe,

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