I was able to code up the LR & Wald tests.
I need help w/ the score test. Does anyone know how to obtain the loglik functions after glm
?
using DataFrames, GLM, Distributions
n=7; k=1; X=randn(n,k); β=[2 ;-4]; σ_e = 10.1;
Y= [ones(n) X]*β + σ_e*randn(n);
d = DataFrame(X1= X[:,1], Y=Y);
#d = DataFrame(X1= X[:,1], X2= X[:,2], Y=Y);
#
f0 = @formula(Y ~ 1)
fA = @formula(Y ~ 1 + X1)
#
mH0 = lm(f0, d)
mHA = lm(fA, d)
#
mH0 = glm(f0, d, Normal())
mHA = glm(fA, d, Normal())
# Likelihood Ratio Test
function HT_LR(mH0, mHA)
LR = 2.0*(loglikelihood(mHA) - loglikelihood(mH0)) |> abs
df = dof_residual(mH0) - dof_residual(mHA) |> abs
pv = 1 - cdf(Chisq(df), LR)
return LR, pv, df
end
#
HT_LR(mH0, mHA) #better practice
HT_LR(mHA, mH0)
# Wald Test
"https://en.wikipedia.org/wiki/Wald_test"
"H0: R*θ = r"
"HA: R*θ ≂̸ r"
#
function HT_Wald(mHA, R, r, V)
θ̂ = coef(mHA)
A = (R*θ̂ - r)
#V = vcov(mHA) #[2,2]
n = size(mHA.mm.m,1)
W = A' * inv(R*V*R') * A #V/n
df = size(R,1)
pv = 1 - cdf(Chisq(df), W)
return W, pv, df
end
R = [0 1]
r = [0]
HT_Wald(mHA, R, r, vcov(mHA))
"LM aka Score test Matlab code"
G = gradp(@nll_lin,theta_r_full,datamat,1);
H_r = HessMp(@nll_lin,theta_r_full,datamat,1);
V_r = inv(H_r);
LM = G*V_r*G';
LM_p = 1-chi2cdf(LM,2);