-
Notifications
You must be signed in to change notification settings - Fork 2
/
LinearRegression.h
88 lines (73 loc) · 2.62 KB
/
LinearRegression.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//
// Created by Ryan.Zurrin001 on 12/16/2021.
//
#ifndef PHYSICSFORMULA_LINEARREGRESSION_H
#define PHYSICSFORMULA_LINEARREGRESSION_H
//α=224,ß=225,π=227,Σ=228,σ=229,µ=230,τ=231,Φ=232,Θ=233
//Ω=234,δ=235,∞=236,φ=237,ε=238,∩=239,≡=240,Γ=226,γ, σ, ϑ, Å, Ώ, λ, γ
#include <iostream>
#include "ETL.h"
/**
* @class LinearRegression
* @details
* dateBuilt 5/26/2021
* lastEdit 5/26/2021
*/
template <typename T>
class LinearRegression
{
public:
LinearRegression()
{}
/// <summary>
/// Ordinary least squares (OLS) used to find the slope m of a data set
/// </summary>
/// <param name="X_">The x.</param>
/// <param name="y">The y.</param>
/// <param name="theta">The theta.</param>
/// <returns></returns>
float OLS_Cost(MatrixND<T> X, MatrixND<T> y, MatrixND<T> theta)const;
std::tuple<VectorND<T>,std::vector<float>>
GradientDescent(MatrixND<T> X, MatrixND<T> y,
VectorND<T> theta, float alpha, int iters)const;
float RSquared(MatrixND<T> y, MatrixND<T> y_hat)const;
};
#endif //LinearRegression_h
template <typename T>
inline float LinearRegression<T>::OLS_Cost(MatrixND<T> X, MatrixND<T> y, MatrixND<T> theta)const
{
MatrixND<T> inner = pow(((X*theta)-y).array(),2);
return static_cast<float>( inner.sum()/(2*X.rows()));
}
template <typename T>
inline std::tuple<VectorND<T>,std::vector<float>>
LinearRegression<T>::GradientDescent(MatrixND<T> X, MatrixND<T> y,
VectorND<T> theta, float alpha, int iters)const
{
MatrixND<T> temp = theta;
const int parameters = static_cast<int>( theta.rows());
std::vector<float> cost;
cost.push_back(OLS_Cost(X,y,theta));
for(int i=0; i<iters; ++i){
MatrixND<T> error = X*theta - y;
for(int j=0; j<parameters; ++j){
MatrixND<T> X_i = X.col(j);
MatrixND<T> term = error.cwiseProduct(X_i);
temp(j,0) = theta(j,0) - ((alpha/X.rows())*term.sum());
}
theta = temp;
cost.push_back(OLS_Cost(X,y,theta));
}
return std::make_tuple(theta,cost);
}
template <typename T>
inline float LinearRegression<T>::RSquared(MatrixND<T> y, MatrixND<T> y_hat)const
{
std::cout << "in Rsq - y:" << y << std::endl;
std::cout << "in Rsq - yhat: " << y_hat << std::endl;
auto num = pow((y-y_hat).array(),2).sum();
std::cout << "in Rsq num: " << num << std::endl;
auto den = pow(y.array()-y.mean(),2).sum();
std::cout << "in Rsq den: " << den << std::endl;
return static_cast<float>( 1 - num/den);
}