最小线性回归程序

2 投票
3 回答
2489 浏览
提问于 2025-04-15 18:54

我在一台外部机器上进行一些计算,最后得到了X和Y的配对数据。我想用线性回归来计算出A、B和R2。但在这台机器上我不能安装任何东西(它运行的是Linux),上面只装了一些基本的工具,比如Python、bash等等。

我在想,使用什么样的脚本(比如Python、bash等)或者程序(我可以编译C和C++)能让我得到线性回归的系数,而不需要添加任何外部库(像numpy之类的)呢?

3 个回答

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;
}
1

你可以把这些系数提取到一个文件里,然后把这个文件导入到另一台机器上,再用Excel、Matlab或者其他能处理这些数据的程序来帮你做。

3

对于一个简单且已知的函数(就像你提到的:一条直线),自己从头写一个基本的最小二乘法程序其实并不难(不过需要注意一些细节)。这在初学数值分析的课程中是一个非常常见的作业。

所以,你可以去维基百科、数学世界或者教科书上查查最小二乘法,自己动手试试吧。

撰写回答