This project demonstrates how to implement Linear Regression, including the Coefficient of Determination (R²) and Mean Squared Error (MSE), using the Rust programming language.
The dataset used in this project represents the monthly water consumption of different families based on the number of family members.
These are the core functions that perform the regression analysis:
-
linear_regression
Validates input and computes the linear regression result (ŷ) for a givenx
. -
coefficient_determination
Computes the Coefficient of Determination (R²), indicating how well the regression model explains the variance in the data. -
mse
Calculates the Mean Squared Error, representing the average of squared differences between actual and predicted values. -
predict_values
Generates predictedy
values based on the regression model and a new set ofx
values.
Below are the supporting functions used to calculate statistical values required for linear regression:
-
std_deviation
Returns the standard deviation for a given vector of numbers. -
correlation
Calculates the Pearson correlation coefficient between two vectors. -
slope
Computes the slope (m) of the linear regression line based on the input vectors. -
intercept
Calculates the y-intercept (b) of the linear regression line.
- Rust
-
Clone the repository to your local machine.
-
Navigate to the directory.
-
Run the program in the terminal.
After running cargo run in the terminal it will display:
📊 Linear Regression Analysis
------------------------------------------------------------
Input (Family Members): [4.0, 7.0, 8.0, 3.0, 11.0]
Input (Water Consumption): [13.0, 21.0, 24.5, 11.0, 34.7] m³
------------------------------------------------------------
==================== Regression Summary ====================
R² (Coefficient of Determination): 0.9927
→ 99.27% of water consumption is explained by family size.
MSE (Mean Squared Error): 0.5337
→ Indicates difference between observed and predicted values.
============================================================
================== Predicted Consumption ===================
Family Size | Predicted Monthly Water Consumption (m³)
------------------------------------------------------------
2 | 7.22
5 | 16.10
13 | 39.79
9 | 27.95
15 | 45.71
============================================================
This project includes automated tests to validate correct input handling.
To run the tests, type cargo test in the terminal.