用C语言写的线性回归直线方程(转载)
转自:blog.csdn/maozefa/archive/2007/08/03/1725535.aspx
1.先看看一元线性回归函数代码:
// 求线性回归方程:Y = a + bx
// dada[rows*2]数组:X, Y;rows:数据行数;a, b:返回回归系数
// SquarePoor[4]:返回方差分析指标: 回归平方和,剩余平方和,回归平方差,剩余平方差
// 返回值:0求解成功,-1错误
int LinearRegression(double *data, int rows, double *a, double *b, double *SquarePoor)
{
int m;
double *p, Lxx = 0.0, Lxy = 0.0, xa = 0.0, ya = 0.0;
if (data == 0 || a == 0 || b == 0 || rows < 1)
return -1;
for (p = data, m = 0; m < rows; m ++)
{
xa += *p ++;
ya += *p ++;
}
xa /= rows; // X平均值
ya /= rows; // Y平均值
for (p = data, m = 0; m < rows; m ++, p += 2)
{
Lxx += ((*p - xa) * (*p - xa)); // Lxx = Sum((X - Xa)平方)
Lxy += ((*p - xa) * (*(p + 1) - ya)); // Lxy = Sum((X - Xa)(Y - Ya))
}
*b = Lxy / Lxx; // b = Lxy / Lxx
*a = ya - *b * xa; // a = Ya - b*Xa
if (SquarePoor == 0)
return 0;
// 方差分析
SquarePoor[0] = SquarePoor[1] = 0.0;
for (p = data, m = 0; m < rows; m ++, p ++)
{
Lxy = *a + *b * *p ++;
SquarePoor[0] += ((Lxy - ya) * (Lxy - ya)); // U(回归平方和)
SquarePoor[1] += ((*p - Lxy) * (*p - Lxy)); // Q(剩余平方和)
}
SquarePoor[2] = SquarePoor[0]; // 回归方差
SquarePoor[3] = SquarePoor[1] / (rows - 2); // 剩余方差
return 0;
}
2.实例计算:
double data1[12][2] = {
// X Y
{187.1, 25.4},
{179.5, 22.8},
{157.0, 20.6},
{197.0, 21.8},
{239.4, 32.4},
{217.8, 24.4},
{227.1, 29.3},
{233.4, 27.9},
{242.0, 27.8},
{251.9, 34.2},
{230.0, 29.2},
printf函数返回值
{271.8, 30.0}
};
void Display(double *dat, double *Answer, double *SquarePoor, int rows, int cols)
{
double v, *p;
int i, j;
printf("回归方程式: Y = %.5lf", Answer[0]);
for (i = 1; i < cols; i ++)
printf(" + %.5lf*X%d", Answer[i], i);
printf(" ");
printf("回归显著性检验: ");
printf("回归平方和:%12.4lf 回归方差:%12.4lf ", SquarePoor[0], SquarePoor[2]);
printf("剩余平方和:%12.4lf 剩余方差:%12.4lf ", SquarePoor[1], SquarePoor[3]);
printf("离差平方和:%12.4lf 标准误差:%12.4lf ", SquarePoor[0] + SquarePoor[1], sqrt(SquarePoor[3]));
printf("F 检 验:%12.4lf 相关系数:%12.4lf ", SquarePoor[2] /SquarePoor[3],
sqrt(SquarePoor[0] / (SquarePoor[0] + SquarePoor[1])));
printf("剩余分析: ");
printf(" 观察值 估计值 剩余值 剩余平方 ");
for (i = 0, p = dat; i < rows; i ++, p ++)
{
v = Answer[0];
for (j = 1; j < cols; j ++, p ++)
v += *p * Answer[j];
printf("%12.2lf%12.2lf%12.2lf%12.2lf ", *p, v, *p - v, (*p - v) * (*p - v));
}
system("pause");
}
int main()
{
double Answer[2], SquarePoor[4];
if (LinearRegression((double*)data1, 12, &Answer[0], &Answer[1], SquarePoor) == 0)
Display((double*)data1, Answer, SquarePoor, 12, 2);
return 0;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论