Skip to content

Commit 5a5c0d4

Browse files
authored
Add linear regression (#579)
1 parent 173d856 commit 5a5c0d4

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ pub mod dynamic_programming;
1111
pub mod general;
1212
pub mod geometry;
1313
pub mod graph;
14+
pub mod machine_learning;
1415
pub mod math;
1516
pub mod navigation;
1617
pub mod number_theory;
+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/// Returns the parameters of the line after performing simple linear regression on the input data.
2+
pub fn linear_regression(data_points: Vec<(f64, f64)>) -> Option<(f64, f64)> {
3+
if data_points.is_empty() {
4+
return None;
5+
}
6+
7+
let count = data_points.len() as f64;
8+
let mean_x = data_points.iter().fold(0.0, |sum, y| sum + y.0) / count;
9+
let mean_y = data_points.iter().fold(0.0, |sum, y| sum + y.1) / count;
10+
11+
let mut covariance = 0.0;
12+
let mut std_dev_sqr_x = 0.0;
13+
let mut std_dev_sqr_y = 0.0;
14+
15+
for data_point in data_points {
16+
covariance += (data_point.0 - mean_x) * (data_point.1 - mean_y);
17+
std_dev_sqr_x += (data_point.0 - mean_x).powi(2);
18+
std_dev_sqr_y += (data_point.1 - mean_y).powi(2);
19+
}
20+
21+
let std_dev_x = std_dev_sqr_x.sqrt();
22+
let std_dev_y = std_dev_sqr_y.sqrt();
23+
let std_dev_prod = std_dev_x * std_dev_y;
24+
25+
let pcc = covariance / std_dev_prod; //Pearson's correlation constant
26+
let b = pcc * (std_dev_y / std_dev_x); //Slope of the line
27+
let a = mean_y - b * mean_x; //Y-Intercept of the line
28+
29+
Some((a, b))
30+
}
31+
32+
#[cfg(test)]
33+
mod test {
34+
use super::*;
35+
36+
#[test]
37+
fn test_linear_regression() {
38+
assert_eq!(
39+
linear_regression(vec![(0.0, 0.0), (1.0, 1.0), (2.0, 2.0)]),
40+
Some((2.220446049250313e-16, 0.9999999999999998))
41+
);
42+
}
43+
44+
#[test]
45+
fn test_empty_list_linear_regression() {
46+
assert_eq!(linear_regression(vec![]), None);
47+
}
48+
}

src/machine_learning/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
mod linear_regression;
2+
pub use linear_regression::linear_regression;

0 commit comments

Comments
 (0)