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
|
#include "LinearRegression.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <string>
struct Data { double x, y; };
std::vector<Data> LinearRegression::transform(const std::vector<OrderBookEntry>& ordersX, const std::vector<OrderBookEntry>& ordersY) {
std::vector<Data> result(ordersX.size());
for (int i = 0; i < ordersX.size(); ++i) {
result[i] = { ordersX[i].price, ordersY[i].price };
}
return result;
}
void LinearRegression::regression(const std::vector<Data>& data, double& m, double& c)
{
int N = data.size();
double Sx = 0, Sy = 0, Sxx = 0, Sxy = 0, Syy = 0;
for (Data d : data)
{
double x = d.x, y = d.y;
Sx += x;
Sy += y;
Sxx += x * x;
Sxy += x * y;
Syy += y * y;
}
m = (N * Sxy - Sx * Sy) / (N * Sxx - Sx * Sx);
c = (Sy - m * Sx) / N;
}
void LinearRegression::training(const std::vector<Data>& data, double& m, double& c, double alpha, int passes)
{
m = c = 0.0;
while (passes--)
{
for (Data d : data)
{
double error = m * d.x + c - d.y;
c -= alpha * error;
m -= alpha * error * d.x;
}
}
}
void LinearRegression::write(const std::vector<Data>& data, double m, double c)
{
#define fmt << std::setw( 20 ) <<
std::cout << "Regression line is y = " << m << "x + " << c << "\n\n";
std::cout << std::fixed << std::setprecision(6);
std::cout << "For comparison (x, y, ypred):\n";
for (Data d : data) std::cout fmt d.x fmt d.y fmt m* d.x + c << '\n';
}
void LinearRegression::gradientDescent(std::vector<OrderBookEntry>& ordersX, std::vector<OrderBookEntry>& ordersY)
{
double m, c;
std::vector<Data> data = transform(ordersX, ordersY);
regression(data, m, c);
write(data, m, c);
}
|