Struct LinearRegression

Source
pub struct LinearRegression {
    pub w: Vector,
    pub b: Scalar,
    /* private fields */
}
Expand description

A Linear Regression model that fits the equation y = W.T @ x + b

This model predicts a continuous value output based on input features using a linear relationship where W is the weight vector and b is the bias. Linear regression is one of the most fundamental machine learning algorithms used for predicting numerical values by establishing a linear relationship between the independent variables (features) and the dependent variable (target).

The model minimizes the Mean Squared Error (MSE) between predictions and actual values.

Fields§

§w: Vector

The weights vector (W) for the linear model representing the coefficients for each feature in the input data

§b: Scalar

The bias term (b) for the linear model representing the y-intercept of the linear equation

Implementations§

Source§

impl LinearRegression

Source

pub fn new(n_x: usize) -> Result<Self, ModelError>

Creates a new LinearRegression model with zero-initialized weights and bias

Initializes a linear regression model with all weights set to zero and bias set to zero. This creates an untrained model that can be later optimized using various training algorithms.

§Arguments
  • n_x - Number of input features in the dataset
§Returns
  • Result<Self, ModelError> - A new LinearRegression instance or an error if the initialization fails
Source

pub fn builder() -> LinearRegressionBuilder

Returns a builder for creating a LinearRegression with custom configuration

The builder pattern allows for more flexible initialization of the model with various optional parameters and configurations.

§Returns
  • LinearRegressionBuilder - A builder for LinearRegression with fluent API

Trait Implementations§

Source§

impl BaseModel<ArrayBase<OwnedRepr<f64>, Dim<[usize; 2]>>, ArrayBase<OwnedRepr<f64>, Dim<[usize; 1]>>> for LinearRegression

Source§

fn predict(&self, x: &Matrix) -> Result<Vector, ModelError>

Predicts output values for given input features

Applies the linear regression model to make predictions on new data.

§Arguments
  • x - Input features of shape (n_x, m)
§Returns
  • Result<Vector, ModelError> - Predicted values of shape (m, )
Source§

fn compute_cost(&self, x: &Matrix, y: &Vector) -> Result<f64, ModelError>

Computes the Mean Squared Error cost between predictions and target values

Calculates the cost using the formula: J = (1/2m) * Σ(y_hat - y)² where m is the number of examples

§Arguments
  • x - Input features of shape (n_x, m)
  • y - Target values of shape (m, )
§Returns
  • Result<f64, ModelError> - The computed cost value
Source§

impl Builder<LinearRegression, ArrayBase<OwnedRepr<f64>, Dim<[usize; 2]>>, ArrayBase<OwnedRepr<f64>, Dim<[usize; 1]>>> for LinearRegressionBuilder

Source§

fn build(&self) -> Result<LinearRegression, ModelError>

Builds and returns a new LinearRegression model with the configured parameters.

§Returns
  • Result<LinearRegression, ModelError> - A new LinearRegression instance with the specified number of input features, or an error if construction fails
Source§

impl Debug for LinearRegression

Source§

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

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

impl GradientCollection for LinearRegression

Source§

fn get_gradient<D: Dimension>( &self, key: &str, ) -> Result<ArrayView<'_, f64, D>, ModelError>

Get a reference to a specific gradient with strong typing.
Source§

fn set_gradient<D: Dimension>( &mut self, key: &str, value: ArrayView<'_, f64, D>, ) -> Result<(), ModelError>

Set the value of a gradient.
Source§

impl OptimizableModel<ArrayBase<OwnedRepr<f64>, Dim<[usize; 2]>>, ArrayBase<OwnedRepr<f64>, Dim<[usize; 1]>>> for LinearRegression

Implementation of the OptimizableModel trait for LinearRegression

Source§

fn forward(&self, input: &Matrix) -> Result<Vector, ModelError>

Performs forward propagation to compute predictions

Calculates the linear function y_hat = W.T @ x + b for a batch of examples.

§Arguments
  • input - Input features of shape (n_x, m) where n_x is the number of features and m is the batch size
§Returns
  • Result<Vector, ModelError> - The predicted values as a vector of shape (m, )
Source§

fn backward( &mut self, input: &Matrix, output_grad: &Vector, ) -> Result<(), ModelError>

Performs backward propagation to compute gradients

Calculates the gradients of the cost function with respect to the model parameters (weights and bias). For linear regression with MSE loss, the gradients are: dw = (1/m) * X @ (y_hat - y).T db = (1/m) * sum(y_hat - y)

§Arguments
  • input - Input features of shape (n_x, m)
  • output_grad - Gradient of the cost with respect to the output, typically (y_hat - y)
§Returns
  • Result<(), ModelError> - Success or error status of the operation
Source§

fn compute_output_gradient( &self, x: &Matrix, y: &Vector, ) -> Result<Vector, ModelError>

Computes the gradient of the cost with respect to the output predictions

For Mean Squared Error, the gradient dJ/dy_hat is: (y_hat - y) where y_hat is the model’s prediction and y is the ground truth.

§Arguments
  • x - Input features of shape (n_x, m)
  • y - Target values of shape (m, )
§Returns
  • Result<Vector, ModelError> - The gradient of the cost function with respect to outputs
Source§

impl ParamCollection for LinearRegression

Source§

fn get<D: Dimension>( &self, key: &str, ) -> Result<ArrayView<'_, f64, D>, ModelError>

Get a reference to a specific parameter with strong typing.
Source§

fn get_mut<D: Dimension>( &mut self, key: &str, ) -> Result<ArrayViewMut<'_, f64, D>, ModelError>

Source§

fn set<D: Dimension>( &mut self, key: &str, value: ArrayView<'_, f64, D>, ) -> Result<(), ModelError>

Set the value of a parameter.
Source§

fn param_iter(&self) -> Vec<(&str, ArrayView<'_, f64, IxDyn>)>

Iterate over all parameters.
Source§

impl RegressionModel<ArrayBase<OwnedRepr<f64>, Dim<[usize; 2]>>, ArrayBase<OwnedRepr<f64>, Dim<[usize; 1]>>> for LinearRegression

Source§

fn mse(&self, x: &Matrix, y: &Vector) -> Result<f64, ModelError>

Calculates the Mean Squared Error between predictions and target values

§Arguments
  • x - Input features of shape (n_x, m)
  • y - Target values of shape (m, )
§Returns
  • Result<f64, ModelError> - The MSE value
Source§

fn rmse(&self, x: &Matrix, y: &Vector) -> Result<f64, ModelError>

Calculates the Root Mean Squared Error between predictions and target values

§Arguments
  • x - Input features of shape (n_x, m)
  • y - Target values of shape (m, )
§Returns
  • Result<f64, ModelError> - The RMSE value (square root of MSE)
Source§

fn r2(&self, x: &Matrix, y: &Vector) -> Result<f64, ModelError>

Calculates the R-squared (coefficient of determination) for the model

R² represents the proportion of variance in the dependent variable that is predictable from the independent variables. R² = 1 - (MSE / Variance of y)

§Arguments
  • x - Input features of shape (n_x, m)
  • y - Target values of shape (m, )
§Returns
  • Result<f64, ModelError> - The R² value between 0 and 1
Source§

fn compute_metrics( &self, x: &Matrix, y: &Vector, ) -> Result<RegressionMetrics, ModelError>

Computes a complete set of regression metrics for model evaluation

§Arguments
  • x - Input features of shape (n_x, m)
  • y - Target values of shape (m,)
§Returns
  • Result<RegressionMetrics, ModelError> - Struct containing MSE, RMSE, and R²

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