c++ - 如何使用 C++ 获得线性回归线的斜率?

标签 c++ math linear-regression

我需要获得线性回归的斜率,类似于以下链接中 Excel 函数的实现方式:

http://office.microsoft.com/en-gb/excel-help/slope-function-HP010342903.aspx

是否有 C++ 库或某人创建的简单编码解决方案可以执行此操作?

我已经根据这个公式实现了代码,但是它并不总是给我正确的结果(取自这里http://easycalculation.com/statistics/learn-regression.php)....

Slope(b) = (NΣXY - (ΣX)(ΣY)) / (NΣX2 - (ΣX)2)
         = ((5)*(1159.7)-(311)*(18.6))/((5)*(19359)-(311)2)
         = (5798.5 - 5784.6)/(96795 - 96721)
         = 13.9/74
         = 0.19 

如果我针对以下 vector 尝试它,我会得到错误的结果(我应该期待 0.305556): x = 6,5,11,7,5,4,4 y = 2,3,9,1,8,7,5

提前致谢。

最佳答案

这是一个 C++11 实现:

#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

double slope(const std::vector<double>& x, const std::vector<double>& y) {
    const auto n    = x.size();
    const auto s_x  = std::accumulate(x.begin(), x.end(), 0.0);
    const auto s_y  = std::accumulate(y.begin(), y.end(), 0.0);
    const auto s_xx = std::inner_product(x.begin(), x.end(), x.begin(), 0.0);
    const auto s_xy = std::inner_product(x.begin(), x.end(), y.begin(), 0.0);
    const auto a    = (n * s_xy - s_x * s_y) / (n * s_xx - s_x * s_x);
    return a;
}

int main() {
    std::vector<double> x{6, 5, 11, 7, 5, 4, 4};
    std::vector<double> y{2, 3, 9, 1, 8, 7, 5};
    std::cout << slope(x, y) << '\n';  // outputs 0.305556
}

您可以为数学要求添加一个测试(x.size() == y.size() 并且 x 不是常量)或者,作为代码以上,假设用户会处理这个问题。

关于c++ - 如何使用 C++ 获得线性回归线的斜率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18939869/

相关文章:

c++ - sha1 函数给出奇怪的输出

c++ - C/C++ : What's faster: a for loop, 或递增指针

PHP使用特殊字符进行计算

javascript旋转翻译函数

angularjs - AngularDart 中的数学函数

r - 预测预测的标准误差

c++ - QT:文件存储在 appdata 下名为 VirtualStore 的文件夹中

c++ - 如何调整 map 以找到最近的较小物体?

python - 为什么 tensorflow 线性回归预测全为0?

python - python中高效的在线线性回归算法