一个不需要复杂功能的简单算法可以用于任何语言的编码。
y 数据已导入。
y = {11.56999969, 14.47999954, ... , 340.730011, 202.1699982, 4054.949951};
线性回归系数a和b是通过求解正规方程得到的。 (有关推导,请参见下面的注释)。一旦计算出来,它们就可以在不需要求解器的情况下重复使用。
Clear[a, b, n, Σx, Σy, Σxy, Σx2]
Column[{a, b} = Simplify[First[{a, b} /. Solve[{
(* Normal equations for straight line *)
Σy == n a + b Σx,
Σxy == a Σx + b Σx2},
{a, b}]]]]
(Σx Σxy - Σx2 Σy)/(Σx^2 - n Σx2)
(-n Σxy + Σx Σy)/(Σx^2 - n Σx2)
X 根据模型线性化为x。
n = Length[y]
1267
X = Range[n];
x = Map[1/(2 n - #)^100 &, X];
计算数量:
Σx = Sum[x[[i]], {i, n}];
Σy = Sum[y[[i]], {i, n}];
Σxy = Sum[x[[i]]*y[[i]], {i, n}];
Σx2 = Sum[x[[i]]^2, {i, n}];
实现系数公式:
a = (Σx Σxy - Σx2 Σy)/(Σx^2 - n Σx2)
b = (Σx Σy - n Σxy)/(Σx^2 - n Σx2)
16.65767846718208
4.213538401691473*10^313
在线性化数据上绘制回归线(带缩放)。
scaled = 10^340;
Show[ListPlot[Transpose[{x scaled, y}],
PlotRange -> {Automatic, {0, 30}}],
ListPlot[Transpose[{x scaled, Table[a + b i, {i, x}]}],
PlotRange -> All, PlotStyle -> Red]]
重新应用模型,最小二乘拟合为:a + b/(2 n - X)^100
Show[ListPlot[Transpose[{X, y}],
PlotRange -> {Automatic, {0, 400}}],
Plot[a + b/(2 n - X)^100, {X, 0, n},
PlotRange -> {Automatic, {0, 400}}, PlotStyle -> Red]]
这与 Mathematica 的内置解决方案相匹配,如下所示。
还计算 R 平方。
(* Least-squares regression of y on x *)
Array[(Y[#] = a + b x[[#]]) &, n];
Array[(e[#] = y[[#]] - Y[#]) &, n];
(* Residual or unexplained sum of squares *)
RSS = Sum[e[i]^2, {i, n}];
(* Total sum of squares in the dependent variable, measured about its mean *)
TSS = (y - Mean[y]).(y - Mean[y]);
(* Coefficient of determination, R^2 *)
R2 = 1 - RSS/TSS
0.230676
检查 Mathematica 的内置功能。
Clear[x]
lm = LinearModelFit[y, 1/(2 n - x)^100, x];
lm["BestFit"]
lm["RSquared"]
0.230676
关于正规方程的注意事项
来源:Econometric Methods