|
| 1 | +struct LRTestResult{N} |
| 2 | + nobs::Int |
| 3 | + deviance::NTuple{N, Float64} |
| 4 | + dof::NTuple{N, Int} |
| 5 | + pval::NTuple{N, Float64} |
| 6 | +end |
| 7 | + |
| 8 | +_diff(t::NTuple{N}) where {N} = ntuple(i->t[i+1]-t[i], N-1) |
| 9 | + |
| 10 | +""" |
| 11 | + isnested(m1::StatisticalModel, m2::StatisticalModel; atol::Real=0.0) |
| 12 | +
|
| 13 | +Indicate whether model `m1` is nested in model `m2`, i.e. whether |
| 14 | +`m1` can be obtained by constraining some parameters in `m2`. |
| 15 | +Both models must have been fitted on the same data. |
| 16 | +""" |
| 17 | +function isnested end |
| 18 | + |
| 19 | +""" |
| 20 | + lrtest(mods::StatisticalModel...; atol::Real=0.0) |
| 21 | +
|
| 22 | +For each sequential pair of statistical models in `mods...`, perform a likelihood ratio |
| 23 | +test to determine if the first one fits significantly better than the next. |
| 24 | +
|
| 25 | +A table is returned containing degrees of freedom (DOF), |
| 26 | +difference in DOF from the preceding model, deviance, difference in deviance |
| 27 | +from the preceding model, and likelihood ratio and p-value for the comparison |
| 28 | +between the two models. |
| 29 | +
|
| 30 | +Optional keyword argument `atol` controls the numerical tolerance when testing whether |
| 31 | +the models are nested. |
| 32 | +
|
| 33 | +# Examples |
| 34 | +
|
| 35 | +Suppose we want to compare the effects of two or more treatments on some result. |
| 36 | +Our null hypothesis is that `Result ~ 1` fits the data as well as |
| 37 | +`Result ~ 1 + Treatment`. |
| 38 | +
|
| 39 | +```jldoctest |
| 40 | +julia> using DataFrames, GLM |
| 41 | +
|
| 42 | +julia> dat = DataFrame(Result=[1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1], |
| 43 | + Treatment=[1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2], |
| 44 | + Other=categorical([1, 1, 2, 1, 2, 1, 3, 1, 1, 2, 2, 1])); |
| 45 | +
|
| 46 | +julia> nullmodel = glm(@formula(Result ~ 1), dat, Binomial(), LogitLink()); |
| 47 | +
|
| 48 | +julia> model = glm(@formula(Result ~ 1 + Treatment), dat, Binomial(), LogitLink()); |
| 49 | +
|
| 50 | +julia> bigmodel = glm(@formula(Result ~ 1 + Treatment + Other), dat, Binomial(), LogitLink()); |
| 51 | +
|
| 52 | +julia> lrtest(nullmodel, model, bigmodel) |
| 53 | +Likelihood-ratio test: 3 models fitted on 12 observations |
| 54 | +────────────────────────────────────────────── |
| 55 | + DOF ΔDOF Deviance ΔDeviance p(>Chisq) |
| 56 | +────────────────────────────────────────────── |
| 57 | +[1] 1 16.3006 |
| 58 | +[2] 2 1 15.9559 -0.3447 0.5571 |
| 59 | +[3] 4 2 14.0571 -1.8988 0.3870 |
| 60 | +────────────────────────────────────────────── |
| 61 | +
|
| 62 | +julia> lrtest(bigmodel, model, nullmodel) |
| 63 | +Likelihood-ratio test: 3 models fitted on 12 observations |
| 64 | +────────────────────────────────────────────── |
| 65 | + DOF ΔDOF Deviance ΔDeviance p(>Chisq) |
| 66 | +────────────────────────────────────────────── |
| 67 | +[1] 4 14.0571 |
| 68 | +[2] 2 -2 15.9559 1.8988 0.3870 |
| 69 | +[3] 1 -1 16.3006 0.3447 0.5571 |
| 70 | +────────────────────────────────────────────── |
| 71 | +``` |
| 72 | +""" |
| 73 | +function lrtest(mods::StatisticalModel...; atol::Real=0.0) |
| 74 | + if length(mods) < 2 |
| 75 | + throw(ArgumentError("At least two models are needed to perform LR test")) |
| 76 | + end |
| 77 | + T = typeof(mods[1]) |
| 78 | + df = dof.(mods) |
| 79 | + forward = df[1] <= df[2] |
| 80 | + if !all(m -> typeof(m) == T, mods) |
| 81 | + throw(ArgumentError("LR test is only valid for models of the same type")) |
| 82 | + end |
| 83 | + if !all(==(nobs(mods[1])), nobs.(mods)) |
| 84 | + throw(ArgumentError("LR test is only valid for models fitted on the same data, " * |
| 85 | + "but number of observations differ")) |
| 86 | + end |
| 87 | + checknested = hasmethod(isnested, Tuple{T, T}) |
| 88 | + if forward |
| 89 | + for i in 2:length(mods) |
| 90 | + if df[i-1] >= df[i] || |
| 91 | + (checknested && !isnested(mods[i-1], mods[i], atol=atol)) |
| 92 | + throw(ArgumentError("LR test is only valid for nested models")) |
| 93 | + end |
| 94 | + end |
| 95 | + else |
| 96 | + for i in 2:length(mods) |
| 97 | + if df[i] >= df[i-1] || |
| 98 | + (checknested && !isnested(mods[i], mods[i-1], atol=atol)) |
| 99 | + throw(ArgumentError("LR test is only valid for nested models")) |
| 100 | + end |
| 101 | + end |
| 102 | + end |
| 103 | + if !checknested |
| 104 | + @warn "Could not check whether models are nested as model type " * |
| 105 | + "$(nameof(T)) does not implement isnested: results may not be meaningful" |
| 106 | + end |
| 107 | + |
| 108 | + dev = deviance.(mods) |
| 109 | + Δdev = _diff(dev) |
| 110 | + |
| 111 | + Δdf = _diff(df) |
| 112 | + dfr = Int.(dof_residual.(mods)) |
| 113 | + |
| 114 | + if (forward && any(x -> x > 0, Δdev)) || (!forward && any(x -> x < 0, Δdev)) |
| 115 | + throw(ArgumentError("Residual deviance must be strictly lower " * |
| 116 | + "in models with more degrees of freedom")) |
| 117 | + end |
| 118 | + |
| 119 | + pval = (NaN, ccdf.(Chisq.(abs.(Δdf)), abs.(Δdev))...) |
| 120 | + return LRTestResult(Int(nobs(mods[1])), dev, df, pval) |
| 121 | +end |
| 122 | + |
| 123 | +function Base.show(io::IO, lrr::LRTestResult{N}) where N |
| 124 | + Δdf = _diff(lrr.dof) |
| 125 | + Δdev = _diff(lrr.deviance) |
| 126 | + |
| 127 | + nc = 6 |
| 128 | + nr = N |
| 129 | + outrows = Matrix{String}(undef, nr+1, nc) |
| 130 | + |
| 131 | + outrows[1, :] = ["", "DOF", "ΔDOF", "Deviance", "ΔDeviance", "p(>Chisq)"] |
| 132 | + |
| 133 | + outrows[2, :] = ["[1]", @sprintf("%.0d", lrr.dof[1]), " ", |
| 134 | + @sprintf("%.4f", lrr.deviance[1]), " ", " "] |
| 135 | + |
| 136 | + for i in 2:nr |
| 137 | + outrows[i+1, :] = ["[$i]", @sprintf("%.0d", lrr.dof[i]), |
| 138 | + @sprintf("%.0d", Δdf[i-1]), |
| 139 | + @sprintf("%.4f", lrr.deviance[i]), @sprintf("%.4f", Δdev[i-1]), |
| 140 | + string(StatsBase.PValue(lrr.pval[i])) ] |
| 141 | + end |
| 142 | + colwidths = length.(outrows) |
| 143 | + max_colwidths = [maximum(view(colwidths, :, i)) for i in 1:nc] |
| 144 | + totwidth = sum(max_colwidths) + 2*5 |
| 145 | + |
| 146 | + println(io, "Likelihood-ratio test: $N models fitted on $(lrr.nobs) observations") |
| 147 | + println(io, '─'^totwidth) |
| 148 | + |
| 149 | + for r in 1:nr+1 |
| 150 | + for c in 1:nc |
| 151 | + cur_cell = outrows[r, c] |
| 152 | + cur_cell_len = length(cur_cell) |
| 153 | + |
| 154 | + padding = " "^(max_colwidths[c]-cur_cell_len) |
| 155 | + if c > 1 |
| 156 | + padding = " "*padding |
| 157 | + end |
| 158 | + |
| 159 | + print(io, padding) |
| 160 | + print(io, cur_cell) |
| 161 | + end |
| 162 | + print(io, "\n") |
| 163 | + r == 1 && println(io, '─'^totwidth) |
| 164 | + end |
| 165 | + print(io, '─'^totwidth) |
| 166 | +end |
0 commit comments