2

我在外部机器上运行一些计算,最后得到 X、Y 对。我想应用线性回归并获得 A、B 和 R2。在这台机器上我不能安装任何东西(它运行 Linux)并且安装了基本的东西,python,bash(当然)等。

我想知道使用脚本(python、bash 等)或程序(我可以编译 C 和 C++)的最佳方法是什么,无需添加外部库(numpy 等)即可获得线性回归系数

4

3 回答 3

3

对于单个、简单、已知的函数(如您的情况:一行),从头开始简单地编写基本的最小二乘例程并不难(但确实需要注意细节)。这是介绍性数值分析课程中非常常见的作业。

所以,在维基百科或数学世界或教科书中查找最小二乘法,然后去城里。

于 2010-02-04T23:53:46.003 回答
1

如何将系数提取到文件中,导入另一台机器,然后使用 Excel/Matlab/其他任何为您执行此操作的程序?

于 2010-02-04T23:53:00.553 回答
1

嗨,这是我从维基百科关于最佳拟合线的文章中获得的解决方案。

#include <iostream>
#include <vector>

// Returns true if linear fit was calculated. False otherwise.
// Algorithm adapted from:
// https://en.wikipedia.org/wiki/Simple_linear_regression#Fitting_the_regression_line
template <typename PairIterator>
bool GetLinearFit(PairIterator begin_it,
                  PairIterator end_it,
                  double* out_slope,
                  double* out_yintercept) {

    if (begin_it == end_it) {
        return false;
    }

    size_t n = 0;
    double x_avg = 0;
    double y_avg = 0;

    for (PairIterator it = begin_it; it != end_it; ++it) {
        x_avg += it->first;
        y_avg += it->second;
        n++;
    }

    x_avg /= n;
    y_avg /= n;

    double numerator = 0;
    double denominator = 0;

    for (PairIterator it = begin_it; it != end_it; ++it) {
        double x_variance = it->first - x_avg;
        double y_variance = it->second - y_avg;
        numerator += (x_variance * y_variance);
        denominator += (x_variance * x_variance);
    }

    double slope = numerator / denominator;
    double yintercept = y_avg - slope*x_avg;

    *out_slope = slope;
    *out_yintercept= yintercept ;

    return true;
}

// Tests the output of GetLinearFit(...).
int main() {
    std::vector<std::pair<int, int> > data;
    for (int i = 0; i < 10; ++i) {
      data.push_back(std::pair<int, int>(i+1, 2*i));
    }

    double slope = 0;
    double y_intercept = 0;
    GetLinearFit(data.begin(), data.end(), &slope, &y_intercept);

    std::cout << "slope: " << slope << "\n";
    std::cout << "y_intercept: " << y_intercept<< "\n";

    return 0;
}
于 2017-01-30T23:13:28.173 回答