Last active
May 10, 2024 10:13
-
-
Save vankesteren/4bc1bd1cdc3931a03c62e3859c463b8b to your computer and use it in GitHub Desktop.
Bayesian inference for rank-ordered logit model in Julia's Turing.jl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Turing | |
using LogExpFunctions: logsumexp | |
using DataFrames | |
# The rank ordered logit model in Turing | |
# The rank-ordered logit likelihood | |
function rank_ordered_logit(ordered_skills::Vector{<:Real}) | |
ll = 0.0 | |
for m in 1:(length(ordered_skills) - 1) | |
ll += ordered_skills[m] - logsumexp(ordered_skills[m:end]) | |
end | |
return ll | |
end | |
# Instantiate the model | |
@model function rol_model(results::Vector) | |
K = maximum(maximum(results)) | |
theta ~ MvNormal(ones(K)) | |
for result in results | |
Turing.@addlogprob! rank_ordered_logit(theta[result]) | |
end | |
end | |
# here are some competition results | |
# each number belongs to a certain competitor | |
# sometimes people don't compete, that's fine | |
results = [ | |
[3, 2, 5, 4, 1, 6], | |
[2, 3, 6, 5, 4, 1], | |
[3, 4, 2, 6], | |
[2, 4, 1, 5, 6] | |
] | |
# Sample from the posterior | |
chain = sample(rol_model(results), NUTS(), 5_000) | |
# Create a ranking with estimated abilities | |
theta_posterior = DataFrame(chain)[!,3:8] | |
df = DataFrame( | |
:id => 1:maximum(maximum(results)), | |
:est => [mean(v) for v in eachcol(theta_posterior)], | |
:lwr => [quantile(v, 0.025) for v in eachcol(theta_posterior)], | |
:upr => [quantile(v, 0.975) for v in eachcol(theta_posterior)] | |
); | |
sort(df, :est, rev=true) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The results are reasonable π