c# - C#/.Net 中的高效多元线性回归

标签 c# .net linear-regression

有谁知道在 C# 中执行多元线性回归的有效方法,其中联立方程的数量可能有 1000 个(具有 3 或 4 个不同的输入)。看完this article在多元线性回归上,我尝试用矩阵方程来实现它:

Matrix y = new Matrix(
    new double[,]{{745},
                  {895},
                  {442},
                  {440},
                  {1598}});

Matrix x = new Matrix(
     new double[,]{{1, 36, 66},
                 {1, 37, 68},
                 {1, 47, 64},
                 {1, 32, 53},
                 {1, 1, 101}});

Matrix b = (x.Transpose() * x).Inverse() * x.Transpose() * y;

for (int i = 0; i < b.Rows; i++)
{
  Trace.WriteLine("INFO: " + b[i, 0].ToDouble());
}

但是,由于矩阵求逆运算,它不能很好地扩展到 1000 方程的规模。我可以调用 R 语言并使用它,但我希望有一个纯 .Net 解决方案可以扩展到这些大型集合。

有什么建议吗?

编辑#1:

我暂时决定使用 R。通过使用 statconn(已下载 here),我发现使用此方法既快速又相对容易。 IE。这是一个小代码片段,使用 R statconn 库的代码真的不多(注意:这不是全部代码!)。

_StatConn.EvaluateNoReturn(string.Format("output <- lm({0})", equation));
object intercept = _StatConn.Evaluate("coefficients(output)['(Intercept)']");
parameters[0] = (double)intercept;
for (int i = 0; i < xColCount; i++)
{
  object parameter = _StatConn.Evaluate(string.Format("coefficients(output)['x{0}']", i));
  parameters[i + 1] = (double)parameter;
}

最佳答案

为了记录,我最近找到了 ALGLIB库,虽然没有太多文档,但有一些非常有用的功能,例如 linear regression这是我追求的目标之一。

示例代码(这是旧的且未经验证的,只是我如何使用它的一个基本示例)。我在时间序列上使用线性回归,有 3 个条目(称为 3 分钟/2 分钟/1 分钟),然后是结束值(最终)。

public void Foo(List<Sample> samples)
{
  int nAttributes = 3; // 3min, 2min, 1min
  int nSamples = samples.Count;
  double[,] tsData = new double[nSamples, nAttributes];
  double[] resultData = new double[nSamples];

  for (int i = 0; i < samples.Count; i++)
  {
    tsData[i, 0] = samples[i].Tminus1min;
    tsData[i, 1] = samples[i].Tminus2min;
    tsData[i, 2] = samples[i].Tminus3min;

    resultData[i] = samples[i].Final;
  }

  double[] weights = null;
  int fitResult = 0;
  alglib.lsfit.lsfitreport rep = new alglib.lsfit.lsfitreport();
  alglib.lsfit.lsfitlinear(resultData, tsData, nSamples, nAttributes, ref fitResult, ref weights, rep);

  Dictionary<string, double> labelsAndWeights = new Dictionary<string, double>();
  labelsAndWeights.Add("1min", weights[0]);
  labelsAndWeights.Add("2min", weights[1]);
  labelsAndWeights.Add("3min", weights[2]);
}

关于c# - C#/.Net 中的高效多元线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2910361/

相关文章:

c# - 简单的 SQL 命令不适用于特定参数

c# - NHibernate:为 Postgres 添加 DbTypes

c# - 如何在没有 oracle 客户端或 tnsname 的情况下连接到 ORACLE DB

objective-c - Objective-C 中的线性回归

c# - SerialPort.BaseStream.ReadAsync 缺少第一个字节

c# - 有选择地阻止调试器在第一次出现异常时停止

c# - 为什么我们不能使用密封类作为通用约束?

.net - 在 Wcf REST 中,是返回请求较少的较大模型更好,还是返回请求较多的较小模型更好

R:具有 N 个特征的线性回归

python - 使用 Theano 进行线性回归 - 维度不匹配