AlgoPlus v0.1.0
Loading...
Searching...
No Matches
lin_reg.h
1#ifndef LIN_REG_H
2#define LIN_REG_H
3
4#ifdef __cplusplus
5#include <cmath>
6#include <iostream>
7#include <vector>
8#endif
9
14 private:
15 std::vector<std::vector<double>> data;
16 // for y = a + b*x
17 double a, b;
18 double Sxy, Sxx;
19 double x_mean, y_mean;
20
21 public:
26 explicit linear_regression(std::vector<std::vector<double>> points) {
27 try {
28 if (!points.empty()) {
29 this->data = points;
30 Sxy = 0.0;
31 Sxx = 0.0;
32 a = 0;
33 b = 0;
34 x_mean = 0;
35 y_mean = 0;
36 } else {
37 throw std::logic_error("Data array is empty!");
38 }
39 } catch (std::logic_error& e) {
40 std::cerr << e.what() << '\n';
41 }
42 }
43
49 inline std::pair<double, double> get_results() {
50 int64_t n = this->data.size();
51 for (auto& x : data) {
52 x_mean += x[0];
53 y_mean += x[1];
54 }
55 x_mean /= n;
56 y_mean /= n;
57 for (auto& x : data) {
58 Sxy += (x[0] - this->x_mean) * (x[1] - this->y_mean);
59 Sxx += std::pow((x[0] - this->x_mean), 2);
60 }
61 b = Sxy / Sxx;
62 a = y_mean - b * x_mean;
63 return std::make_pair(a, b);
64 }
65
71 inline double predict(double x) {
72 if (Sxx == 0.0 || Sxy == 0.0) {
74 }
75 return a + b * x;
76 }
77};
78
79#endif
std::pair< double, double > get_results()
get_results function
Definition lin_reg.h:49
linear_regression(std::vector< std::vector< double > > points)
Constructor for linear regression class.
Definition lin_reg.h:26
double predict(double x)
predict function
Definition lin_reg.h:71