55module IrtRuby
66 # A class representing the Rasch model for Item Response Theory.
77 class RaschModel
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 @max_iter = max_iter
1313 @tolerance = tolerance
14+ @learning_rate = learning_rate
1415 end
1516
17+ # Sigmoid function to calculate probability
1618 def sigmoid ( x )
1719 1.0 / ( 1.0 + Math . exp ( -x ) )
1820 end
1921
22+ # Calculate the log-likelihood of the data given the current parameters
2023 def likelihood
2124 likelihood = 0
2225 @data . row_vectors . each_with_index do |row , i |
2326 row . to_a . each_with_index do |response , j |
2427 prob = sigmoid ( @abilities [ i ] - @difficulties [ j ] )
25- if response == 1
26- likelihood += Math . log ( prob )
27- elsif response . zero?
28- likelihood += Math . log ( 1 - prob )
29- end
28+ likelihood += response == 1 ? Math . log ( prob ) : Math . log ( 1 - prob )
3029 end
3130 end
3231 likelihood
3332 end
3433
34+ # Update parameters using gradient ascent
3535 def update_parameters
3636 last_likelihood = likelihood
3737 @max_iter . times do |_iter |
3838 @data . row_vectors . each_with_index do |row , i |
3939 row . to_a . each_with_index do |response , j |
4040 prob = sigmoid ( @abilities [ i ] - @difficulties [ j ] )
4141 error = response - prob
42- @abilities [ i ] += 0.01 * error
43- @difficulties [ j ] -= 0.01 * error
42+ @abilities [ i ] += @learning_rate * error
43+ @difficulties [ j ] -= @learning_rate * error
4444 end
4545 end
4646 current_likelihood = likelihood
@@ -50,6 +50,7 @@ def update_parameters
5050 end
5151 end
5252
53+ # Fit the model to the data
5354 def fit
5455 update_parameters
5556 { abilities : @abilities , difficulties : @difficulties }
0 commit comments