|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "matrix" |
| 4 | + |
| 5 | +module IrtRuby |
| 6 | + # A class representing the Three-Parameter model for Item Response Theory. |
| 7 | + class ThreeParameterModel |
| 8 | + def initialize(data) |
| 9 | + @data = data |
| 10 | + @abilities = Array.new(data.row_count) { rand } |
| 11 | + @difficulties = Array.new(data.column_count) { rand } |
| 12 | + @discriminations = Array.new(data.column_count) { rand } |
| 13 | + @guessings = Array.new(data.column_count) { rand * 0.3 } |
| 14 | + @max_iter = 1000 |
| 15 | + @tolerance = 1e-6 |
| 16 | + end |
| 17 | + |
| 18 | + def sigmoid(x) |
| 19 | + 1.0 / (1.0 + Math.exp(-x)) |
| 20 | + end |
| 21 | + |
| 22 | + def probability(theta, a, b, c) |
| 23 | + c + (1 - c) * sigmoid(a * (theta - b)) |
| 24 | + end |
| 25 | + |
| 26 | + def likelihood |
| 27 | + likelihood = 0 |
| 28 | + @data.row_vectors.each_with_index do |row, i| |
| 29 | + row.to_a.each_with_index do |response, j| |
| 30 | + prob = probability(@abilities[i], @discriminations[j], @difficulties[j], @guessings[j]) |
| 31 | + if response == 1 |
| 32 | + likelihood += Math.log(prob) |
| 33 | + elsif response.zero? |
| 34 | + likelihood += Math.log(1 - prob) |
| 35 | + end |
| 36 | + end |
| 37 | + end |
| 38 | + likelihood |
| 39 | + end |
| 40 | + |
| 41 | + def update_parameters |
| 42 | + last_likelihood = likelihood |
| 43 | + @max_iter.times do |_iter| |
| 44 | + @data.row_vectors.each_with_index do |row, i| |
| 45 | + row.to_a.each_with_index do |response, j| |
| 46 | + prob = probability(@abilities[i], @discriminations[j], @difficulties[j], @guessings[j]) |
| 47 | + error = response - prob |
| 48 | + @abilities[i] += 0.01 * error * @discriminations[j] |
| 49 | + @difficulties[j] -= 0.01 * error * @discriminations[j] |
| 50 | + @discriminations[j] += 0.01 * error * (@abilities[i] - @difficulties[j]) |
| 51 | + @guessings[j] += 0.01 * error * (1 - prob) |
| 52 | + end |
| 53 | + end |
| 54 | + current_likelihood = likelihood |
| 55 | + break if (last_likelihood - current_likelihood).abs < @tolerance |
| 56 | + |
| 57 | + last_likelihood = current_likelihood |
| 58 | + end |
| 59 | + end |
| 60 | + |
| 61 | + def fit |
| 62 | + update_parameters |
| 63 | + { |
| 64 | + abilities: @abilities, |
| 65 | + difficulties: @difficulties, |
| 66 | + discriminations: @discriminations, |
| 67 | + guessings: @guessings |
| 68 | + } |
| 69 | + end |
| 70 | + end |
| 71 | +end |
0 commit comments