Maestro 0.2.11
Unified interface for quantum circuit simulation
Loading...
Searching...
No Matches
SimpleLinearRegression.h
Go to the documentation of this file.
1
11
12#pragma once
13
14#ifndef __SIMPLE_LINEAR_REGRESSION_H__
15#define __SIMPLE_LINEAR_REGRESSION_H__
16
17#include <vector>
18
19namespace Utils {
20
21 // WARNING: it doesn't let it go lower than the minimum value, if the prediction is lower, the min value is returned!
22 // set "TrueLinearRegression" to true if you want to use the real linear regression
23 template<typename T1 = size_t, typename T2 = double> class SimpleLinearRegression {
24 public:
25 void SetSamples(const std::vector<T1>& x, const std::vector<T2>& y)
26 {
27 assert(x.size() == y.size());
28 assert(!x.empty());
29
30 if (x.empty() || y.empty())
31 return;
32
33 T2 sumX = 0;
34 T2 sumY = 0;
35 T2 sumXY = 0;
36 T2 sumX2 = 0;
37
38 const size_t cnt = std::min(x.size(), y.size());
39 for (size_t i = 0; i < cnt; ++i)
40 {
41 sumX += x[i];
42 sumY += y[i];
43 sumXY += x[i] * y[i];
44 sumX2 += x[i] * x[i];
45 }
46
47 W = (cnt * sumXY - sumX * sumY) / (cnt * sumX2 - sumX * sumX);
48 b = (sumY - W * sumX) / cnt;
49 }
50
51 void SetSamplesSingleRegressor(const std::vector<T1>& x, const std::vector<T2>& y)
52 {
53 assert(x.size() == y.size());
54
55 b = 0;
56
57 T2 sumXY = 0;
58 T2 sumX2 = 0;
59
60 const size_t cnt = std::min(x.size(), y.size());
61 for (size_t i = 0; i < cnt; ++i)
62 {
63 sumXY += x[i] * y[i];
64 sumX2 += x[i] * x[i];
65 }
66
67 W = sumXY / sumX2;
68 }
69
70 T2 Predict(T1 x) const
71 {
72 const auto val = W * x + b;
73
74 if (trueLinearRegression)
75 return val;
76
77 const auto m = 1E-12;
78 if (val < m)
79 return m;
80
81 return val;
82 }
83
85 {
86 trueLinearRegression = reg;
87 }
88
89 T2 GetW() const
90 {
91 return W;
92 }
93
94 T2 GetB() const
95 {
96 return b;
97 }
98
99 private:
100 T2 W = 0;
101 T2 b = 0;
102
103 bool trueLinearRegression = false;
104 };
105
106}
107
108#endif // __SIMPLE_LINEAR_REGRESSION_H__
void SetSamples(const std::vector< T1 > &x, const std::vector< T2 > &y)
void SetSamplesSingleRegressor(const std::vector< T1 > &x, const std::vector< T2 > &y)
Definition Alias.h:22