Skip to content

Commit 91eb41c

Browse files
authored
Add Two-Parameter IRT Model with improvements (#6)
1 parent 47ff9af commit 91eb41c

1 file changed

Lines changed: 9 additions & 4 deletions

File tree

lib/irt_ruby/two_parameter_model.rb

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,22 @@
55
module IrtRuby
66
# A class representing the Two-Parameter model for Item Response Theory.
77
class TwoParameterModel
8-
def initialize(data, max_iter: 1000, tolerance: 1e-6)
8+
def initialize(data, max_iter: 1000, tolerance: 1e-6, learning_rate: 0.01)
99
@data = data
1010
@abilities = Array.new(data.row_count) { rand }
1111
@difficulties = Array.new(data.column_count) { rand }
1212
@discriminations = Array.new(data.column_count) { rand }
1313
@max_iter = max_iter
1414
@tolerance = tolerance
15+
@learning_rate = learning_rate
1516
end
1617

18+
# Sigmoid function
1719
def sigmoid(x)
1820
1.0 / (1.0 + Math.exp(-x))
1921
end
2022

23+
# Calculate the log-likelihood of the data given the current parameters
2124
def likelihood
2225
likelihood = 0
2326
@data.row_vectors.each_with_index do |row, i|
@@ -33,16 +36,17 @@ def likelihood
3336
likelihood
3437
end
3538

39+
# Update parameters using gradient ascent
3640
def update_parameters
3741
last_likelihood = likelihood
3842
@max_iter.times do |_iter|
3943
@data.row_vectors.each_with_index do |row, i|
4044
row.to_a.each_with_index do |response, j|
4145
prob = sigmoid(@discriminations[j] * (@abilities[i] - @difficulties[j]))
4246
error = response - prob
43-
@abilities[i] += 0.01 * error * @discriminations[j]
44-
@difficulties[j] -= 0.01 * error * @discriminations[j]
45-
@discriminations[j] += 0.01 * error * (@abilities[i] - @difficulties[j])
47+
@abilities[i] += @learning_rate * error * @discriminations[j]
48+
@difficulties[j] -= @learning_rate * error * @discriminations[j]
49+
@discriminations[j] += @learning_rate * error * (@abilities[i] - @difficulties[j])
4650
end
4751
end
4852
current_likelihood = likelihood
@@ -52,6 +56,7 @@ def update_parameters
5256
end
5357
end
5458

59+
# Fit the model to the data
5560
def fit
5661
update_parameters
5762
{ abilities: @abilities, difficulties: @difficulties, discriminations: @discriminations }

0 commit comments

Comments
 (0)