I was playing around a little with what I've learned from rm-rf.
Here's a small package which encapsulates the White and the Breusch-Pagan test. The math is correct, but I wanted to have a kind of statistical distribution behaviour, where you can query certain properties using a string.
I'd appreciate to have overloaded the LinearModelFit, but decided to do it differently, since I was concerned on creating more trouble.
BeginPackage["FitModel`"];
FitModel::usage = "";
Begin["`Private`"];
FitModel[data_List, coords_List] :=
With[{lm = LinearModelFit[data, coords, coords]},
dispatch[{"BreuschPagan" -> BreuschPagan[data, lm, coords],
"WhitesHeteroskedasticity" -> WhitesHeteroskedasticity[lm, coords]}]
];
dispatch[list_][field_] := field /. list
dispatch[list_]["Properties"] := list /. Rule[field_, _] :> field
dispatch /: ReplaceAll[fields_, dispatch[list_]] := fields /. list
Format[dispatch[list_], StandardForm] :=
HoldForm[dispatch]["<" <> ToString@Length@list <> ">"]
BreuschPagan[data_List, lm_, coords_List] := Module[{lm2},
lm2 = LinearModelFit[Block[{newdata = data},
newdata[[All, -1]] = lm["FitResiduals"]^2; newdata], coords, coords];
With[{sqResids =
lm["FitResiduals"]^2}, (Variance[sqResids] (Length[data] - 1) -
Total[lm2["FitResiduals"]^2]) / 2 / (Total[sqResids]/Length[data])^2]
]
WhitesHeteroskedasticity[lm_, coords_List] :=
Module[{desmat, resids},
{desmat, resids} = lm[{"DesignMatrix", "FitResiduals"}];
With[{inv = Inverse[Transpose[desmat].desmat],
xresid = resids*desmat},
inv.Transpose[xresid].xresid.inv]
]
End[];
EndPackage[];
To test it:
data = Flatten[ Table[{x, y, z, 1.2 x - 3.4 y + 10 z + RandomReal[10]}, {x,
RandomReal[10, 3]}, {y, RandomReal[10, 3]}, {z,
RandomReal[10, 3]}], 2];
f = FitModel[data, {x, y, z}];
f["BreuschPagan"]
=> yields with actual data: 0.264212
f["WhitesHeteroskedasticity"] // MatrixForm
=> yields:
(2.95722 -0.262317 -0.294977 -0.0841742
-0.262317 0.108253 0.022681 -0.0249064
-0.294977 0.022681 0.0542495 -0.0110319
-0.0841742 -0.0249064 -0.0110319 0.0409517)
I really hope this helps.