我想使用Excel的名为LINEST()的内置函数在.net中进行回归分析。 我能够使用squred矩阵数组的函数,但是当它不是方形矩阵表示顺序[12,3]时,它会给出错误:
WorksheetFunction类的LinEst方法失败
请帮我解决这个问题,因为完成此代码对我来说非常重要。 这是我的完整代码:
System.Data.DataTable dt = new System.Data.DataTable();
SqlCommand cmd =new SqlCommand("Select QtytoTransfer from DEmo ",con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
List<double> yDatapoints =new List<double>();
foreach (DataRow dr in dt.Rows)
{
yDatapoints.Add(Convert.ToDouble( dr["QtytoTransfer"].ToString()));
}
System.Data.DataTable dt1 = new System.Data.DataTable();
SqlCommand sqlcmd = new SqlCommand("Select CurrentQoh,QtySold,GameTime from DEmo ", con);
SqlDataAdapter adp1 = new SqlDataAdapter(sqlcmd);
adp1.Fill(dt1);
double[,] xAll = new double[dt1.Rows.Count, dt1.Columns.Count];
for (int i = 0; i < dt1.Rows.Count; ++i)
{
for (int j = 0; j < dt1.Columns.Count; ++j)
{
xAll[i, j] = Convert.ToDouble(dt1.Rows[i][j].ToString());
}
}
Microsoft.Office.Interop.Excel.Application xl = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.WorksheetFunction wsf = xl.WorksheetFunction;
object[,] reslut = (object[,])wsf.LinEst(yDatapoints.ToArray(), xAll, missing, true);
答案 0 :(得分:2)
如果您的xAll的维度为[12,3],则您的yDataPoints长度应为3,以便LinEst()正常运行。
using System;
namespace InteropExcel {
class Program {
static void Main(string[] args) {
Random rand = new Random();
double[] yDatapoints = new double[3];
for (int i = 0; i < 3; i++) {
yDatapoints[i]=rand.Next(20, 60);
}
double[,] xAll = new double[12, 3];
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 3; j++) {
xAll[i, j] = rand.Next(2, 100);
}
}
Microsoft.Office.Interop.Excel.Application xl = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.WorksheetFunction wsf = xl.WorksheetFunction;
object[,] result = (object[,])wsf.LinEst(yDatapoints, xAll, Type.Missing, true);
}
}
}
xAll的列大小应该等于yDataPoints数组的长度。请尝试让我知道。
答案 1 :(得分:0)
这是C#中Excel的LINEST()函数的实现。它可能比在Microsoft.Office.Interop.Excel DLL文件上创建依赖项容易。
这将返回给定数据集的斜率,并使用与LINEST()相同的“最小二乘”方法将其标准化:
public static double CalculateLinest(double[] y, double[] x)
{
double linest = 0;
if (y.Length == x.Length)
{
double avgY = y.Average();
double avgX = x.Average();
double[] dividend = new double[y.Length];
double[] divisor = new double[y.Length];
for (int i = 0; i < y.Length; i++)
{
dividend[i] = (x[i] - avgX) * (y[i] - avgY);
divisor[i] = Math.Pow((x[i] - avgX), 2);
}
linest = dividend.Sum() / divisor.Sum();
}
return linest;
}
此外,这是我写的一种获取Excel的LINEST函数生成的“ b”(y轴截距)值的方法。
private double CalculateYIntercept(double[] x, double[] y, double linest)
{
return (y.Average() - linest * x.Average());
}
由于这些方法仅适用于一个数据集,因此,如果您希望生成多组线性回归数据,我建议在循环内调用它们。
此链接帮助我找到了答案:https://agrawalreetesh.blogspot.com/2011/11/how-to-calculate-linest-of-given.html