代码拉取完成,页面将自动刷新
#include "UnitaryLinearRegression.h"
#include <fstream>
#include <sstream>
#include <iostream>
#define _USE_MATH_DEFINES
#define WITHOUT_NUMPY
#include <matplotlibcpp.h>
bool UnitaryLinearRegression::importData(std::string const &path)
{
std::ifstream file(path);
if (!file.is_open())
return false;
std::string line, number;
double x, y;
while (std::getline(file, line))
{
std::stringstream ss(line);
std::getline(ss, number, ',');
x = std::stod(number);
std::getline(ss, number, ',');
y = std::stod(number);
data.push_back(std::make_pair(x, y));
}
std::cout << "Data imported: " << data.size() << std::endl;
return true;
}
void UnitaryLinearRegression::calc()
{
double sumX = 0.0, sumX2 = 0.0, _x = 0.0;
double dx = 0.0;
for (std::pair<double, double> &p : data)
{
sumX += p.first;
sumX2 += p.first * p.first;
}
_x = sumX / data.size();
double part1 = 0.0, part2 = 0.0;
for (std::pair<double, double> &p : data)
part1 += (p.first - _x) * p.second;
part2 = sumX2 - sumX * sumX / data.size();
w = part1 / part2;
for (std::pair<double, double> &p : data)
b += p.second - w * p.first;
b /= data.size();
}
void UnitaryLinearRegression::show()
{
std::cout << "w: " << w << " b: " << b << std::endl;
std::vector<double> realX, realY;
std::vector<double> predictX, predictY;
for (std::pair<double, double> &p : data)
realX.push_back(p.first), realY.push_back(p.second),
predictX.push_back(p.first), predictY.push_back(w * p.first + b);
matplotlibcpp::figure_size(800, 600);
matplotlibcpp::scatter(realX, realY);
matplotlibcpp::plot(predictX, predictY, "orange");
matplotlibcpp::title("Unitary Linear Regression");
matplotlibcpp::show();
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。