irt_ruby 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +26 -5
- data/README.md +48 -7
- data/benchmarks/convergence_benchmark.rb +25 -65
- data/lib/irt_ruby/estimation.rb +78 -0
- data/lib/irt_ruby/model_options_validator.rb +39 -0
- data/lib/irt_ruby/rasch_model.rb +93 -62
- data/lib/irt_ruby/response_data_validator.rb +59 -0
- data/lib/irt_ruby/response_graph.rb +87 -0
- data/lib/irt_ruby/three_parameter_model.rb +154 -84
- data/lib/irt_ruby/two_parameter_model.rb +103 -66
- data/lib/irt_ruby/version.rb +1 -1
- data/lib/irt_ruby.rb +4 -0
- metadata +19 -16
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 520defda852bedfe0f27ea300cb471b2f9afc6b8fbf32c16cb75fc3569cca5df
|
|
4
|
+
data.tar.gz: 16c98bd94b5d88e1c898be6aab91e987d1db3e957bb1dc921e73af02f61d9377
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 2c7a636273fbccda8bce8c96acb157fbb5a3f0d209cf275e4ddff845d1b5ea139f0389c6b5c9c296dfdf98c01ab7e89ab6080e8ed21940319e05845701853ef7
|
|
7
|
+
data.tar.gz: c8b2d1447884a130e1f25ac82a2cae0ec9198171372023ea48ff8aa57168ff78724becd51e1da040e7c1e7e9f822d9775541baf2bfe77f5d0d4af51d7dc761ff
|
data/CHANGELOG.md
CHANGED
|
@@ -2,7 +2,32 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented in this file.
|
|
4
4
|
|
|
5
|
-
## [0.
|
|
5
|
+
## [0.4.0] - 2026-10-11
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- Fixed 3PL gradients for ability, difficulty, discrimination, and guessing; they now match finite differences of the log-likelihood.
|
|
9
|
+
- Only the largest strongly connected part of the response graph is estimated; other respondents and items are returned as `nil` instead of drifting with `max_iter` or keeping random initial values. This covers all-correct, all-incorrect, and unobserved rows or columns as well as perfectly separated or disconnected groups.
|
|
10
|
+
- 3PL keeps the limiting `log(1 - c)` contribution of excluded respondents who answered every estimated item incorrectly, and keeps guessing gradients finite when the response function underflows.
|
|
11
|
+
- Log-likelihoods are computed with a numerically stable log-sigmoid instead of adding `1e-15` inside `Math.log`, which flattened the objective for badly mispredicted responses.
|
|
12
|
+
- Models copy response data on construction and return fresh arrays from `fit`, so later mutation of either does not change model state.
|
|
13
|
+
- Model constructors validate optimization options and raise `ArgumentError` unless `max_iter` is a positive Integer, `tolerance`, `param_tolerance`, `gradient_tolerance`, and `learning_rate` are positive finite numbers, and `decay_factor` is strictly between 0 and 1.
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
- `fit` reports results on a fixed latent scale: Rasch abilities are centered at 0; 2PL and 3PL abilities are standardized to mean 0 and SD 1 with likelihood-preserving item transformations.
|
|
17
|
+
- `fit` results include `converged:` and `iterations:`. `converged` is true only at a stationary point on the reported scale, controlled by the new `gradient_tolerance:` option (default `1e-3`).
|
|
18
|
+
- The learning rate grows by 10% after each accepted step, so it can recover from earlier decreases.
|
|
19
|
+
- Clarified the gem summary and description to describe implemented capabilities rather than production-readiness claims.
|
|
20
|
+
- Added CI RuboCop and gem package build/install verification, and documented the local quality and packaging commands for contributors. RuboCop is pinned to 1.92.0 for Ruby 2.7 and newer.
|
|
21
|
+
- Clarified that response data must be a `Matrix` or array of arrays containing only integer `0`, integer `1`, or `nil`; floats, strings, booleans, and other values are rejected.
|
|
22
|
+
|
|
23
|
+
### Added
|
|
24
|
+
- Added a `seed:` keyword to all models for reproducible initialization without resetting or consuming Ruby's global random number generator.
|
|
25
|
+
- Added finite-difference gradient, identification, extreme-pattern, and parameter-recovery specs.
|
|
26
|
+
- Added executable specs for README usage examples to keep the documented Rasch, 2PL, 3PL, and missing-data flows aligned with the public API.
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## [0.3.0] - 2025-06-13
|
|
6
31
|
|
|
7
32
|
### Changed
|
|
8
33
|
- **Code Quality**
|
|
@@ -44,7 +69,3 @@ All notable changes to this project are documented in this file.
|
|
|
44
69
|
- This release remains **backward-compatible** with `0.1.x` in terms of existing usage; the default `:ignore` missing-data approach matches prior behavior.
|
|
45
70
|
- If upgrading, simply update your gem and enjoy the new features.
|
|
46
71
|
- For more details, see the updated [README](./README.md) and expanded test suites.
|
|
47
|
-
|
|
48
|
-
---
|
|
49
|
-
|
|
50
|
-
*(If you have older versions below `0.2.0`, you can keep them documented similarly, e.g., `## [0.1.x] ...`, under this new entry.)*
|
data/README.md
CHANGED
|
@@ -46,7 +46,17 @@ result = model.fit
|
|
|
46
46
|
# Output the estimated abilities and difficulties
|
|
47
47
|
puts "Abilities: #{result[:abilities]}"
|
|
48
48
|
puts "Difficulties: #{result[:difficulties]}"
|
|
49
|
+
puts "Converged: #{result[:converged]} after #{result[:iterations]} iterations"
|
|
49
50
|
```
|
|
51
|
+
|
|
52
|
+
The third respondent answered every item correctly, so their ability has no
|
|
53
|
+
finite estimate and is returned as `nil` (see [Estimation Details](#estimation-details)).
|
|
54
|
+
|
|
55
|
+
Response data passed to model constructors must be either a `Matrix` or an
|
|
56
|
+
array of arrays. Each response value must be the integer `0`, the integer `1`,
|
|
57
|
+
or `nil` for missing data; floats such as `0.0`/`1.0`, strings, booleans, and
|
|
58
|
+
other values are rejected.
|
|
59
|
+
|
|
50
60
|
### Using 2PL and 3PL Models
|
|
51
61
|
```ruby
|
|
52
62
|
two_pl_model = IrtRuby::TwoParameterModel.new(data)
|
|
@@ -63,8 +73,12 @@ puts three_pl_result[:discriminations]
|
|
|
63
73
|
puts three_pl_result[:guessings]
|
|
64
74
|
```
|
|
65
75
|
|
|
76
|
+
Three respondents are far too few for 2PL or 3PL: on this matrix `fit` returns
|
|
77
|
+
`converged: false`. Discrimination and guessing estimates need hundreds of
|
|
78
|
+
respondents.
|
|
79
|
+
|
|
66
80
|
## Handling Missing Data
|
|
67
|
-
Real-world data often has missing responses. Each model (Rasch, 2PL, 3PL) accepts a `missing_strategy
|
|
81
|
+
Real-world data often has missing responses. Each model (Rasch, 2PL, 3PL) accepts a `missing_strategy:` option to handle nil entries:
|
|
68
82
|
|
|
69
83
|
- `:ignore` (default): Skip `nil` responses entirely in the log-likelihood and gradient calculations.
|
|
70
84
|
- `:treat_as_incorrect`: Interpret `nil` as `0`.
|
|
@@ -96,16 +110,20 @@ This flexibility helps you handle datasets where missingness might signify a ski
|
|
|
96
110
|
### Adaptive Learning Rate & Convergence
|
|
97
111
|
By default, each model uses a gradient ascent with:
|
|
98
112
|
|
|
99
|
-
- An adaptive learning rate
|
|
100
|
-
-
|
|
113
|
+
- An adaptive learning rate: if log-likelihood decreases, the step is reverted and the rate is multiplied by `decay_factor`; after each accepted step the rate grows by 10%.
|
|
114
|
+
- A stopping rule on the change in log-likelihood and the average parameter update.
|
|
115
|
+
- A stationarity check that decides whether the stopping point is reported as converged.
|
|
101
116
|
|
|
102
117
|
You can customize:
|
|
103
118
|
|
|
104
119
|
- `max_iter`: The maximum number of iterations.
|
|
105
|
-
- `tolerance` and `param_tolerance`:
|
|
120
|
+
- `tolerance` and `param_tolerance`: Stopping thresholds for log-likelihood change and parameter updates.
|
|
121
|
+
- `gradient_tolerance` (default `1e-3`): `fit` reports `converged: true` only if, for every parameter, the gradient averaged over the responses it depends on is below this value.
|
|
106
122
|
- `learning_rate`: Initial learning rate.
|
|
107
123
|
- `decay_factor`: Factor by which the learning rate is reduced on a failed step.
|
|
108
124
|
|
|
125
|
+
`fit` returns `converged: false` when `max_iter` runs out or when the stopping rule fires away from a stationary point, for example because the learning rate became too small to move. Check this flag before using the estimates; a larger `learning_rate` or `max_iter` usually helps.
|
|
126
|
+
|
|
109
127
|
Example:
|
|
110
128
|
```ruby
|
|
111
129
|
IrtRuby::TwoParameterModel.new(
|
|
@@ -117,13 +135,36 @@ IrtRuby::TwoParameterModel.new(
|
|
|
117
135
|
decay_factor: 0.5
|
|
118
136
|
)
|
|
119
137
|
```
|
|
138
|
+
|
|
139
|
+
### Reproducible Initialization
|
|
140
|
+
Each model initializes parameters randomly. By default, constructors use Ruby's global random number generator, preserving the historical behavior and honoring any external `srand` calls. For reproducible model initialization without resetting or consuming global RNG state, pass `seed:`:
|
|
141
|
+
|
|
142
|
+
```ruby
|
|
143
|
+
model_a = IrtRuby::ThreeParameterModel.new(data, seed: 1234)
|
|
144
|
+
model_b = IrtRuby::ThreeParameterModel.new(data, seed: 1234)
|
|
145
|
+
|
|
146
|
+
# Same data, options, and seed produce identical fitted results.
|
|
147
|
+
model_a.fit == model_b.fit #=> true
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
The `seed:` keyword is available for `RaschModel`, `TwoParameterModel`, and `ThreeParameterModel`.
|
|
151
|
+
|
|
120
152
|
### Parameter Clamping
|
|
121
153
|
For 2PL and 3PL:
|
|
122
154
|
|
|
123
|
-
- **Discriminations** (`a`) are clamped between `0.01` and `5.0
|
|
155
|
+
- **Discriminations** (`a`) are clamped between `0.01` and `5.0` during optimization.
|
|
124
156
|
- **Guessings** (`c`, 3PL only) are clamped to `[0.0, 0.35]`.
|
|
125
157
|
|
|
126
|
-
|
|
158
|
+
These bounds are model restrictions: a 3PL item with a true lower asymptote above `0.35` cannot be represented. The bounds apply to the internal optimization scale; returned discriminations are multiplied by the internal ability SD (see below), so they can lie outside `[0.01, 5.0]`.
|
|
159
|
+
|
|
160
|
+
## Estimation Details
|
|
161
|
+
|
|
162
|
+
All models estimate person and item parameters jointly by maximizing the likelihood (joint maximum likelihood, JMLE).
|
|
163
|
+
|
|
164
|
+
- **Which parameters are estimated.** Think of the responses as a directed graph: a correct answer links the item to the respondent, an incorrect answer links the respondent to the item. Finite estimates on a common scale exist only within a strongly connected part of this graph, so IrtRuby estimates the largest such part and returns `nil` for every other respondent and item. This excludes respondents who answered every observed item correctly or every item incorrectly, items that everyone answered correctly or incorrectly, rows and columns with no observed responses, groups that are perfectly separated from the rest (for example, a group of respondents who answered every item of another group correctly), and groups that share no responses with the rest. Missing-data strategies are applied first, so `:treat_as_correct` and `:treat_as_incorrect` can create such patterns. For the Rasch model, and for 2PL with its bounded discriminations, this condition guarantees that finite estimates exist (the optimizer may still need more iterations to reach them). For 3PL it is necessary but not sufficient: fits can drift toward boundary solutions in which an item's difficulty keeps growing while its guessing parameter carries the item. Treat very large difficulties, or results with `converged: false`, as unreliable.
|
|
165
|
+
- **3PL and all-incorrect respondents.** Under 3PL, an excluded respondent who answered every estimated item incorrectly still informs the guessing parameters: as their ability tends to minus infinity each response has probability `1 - c`, and that limiting term stays in the likelihood.
|
|
166
|
+
- **Scale identification.** Results are reported on a fixed scale: Rasch abilities are centered to mean 0; 2PL and 3PL abilities are standardized to mean 0 and standard deviation 1, with difficulties and discriminations transformed so that response probabilities are unchanged. Only estimated respondents enter these statistics. The model keeps its internal parameters, so calling `fit` again continues from where it stopped; convergence is checked on the reported scale.
|
|
167
|
+
- **Known limitations.** JMLE item estimates are biased when tests are short, and the bias does not vanish as the number of respondents grows. 2PL and 3PL JMLE is also slow to converge with plain gradient ascent. For high-stakes calibration, compare against marginal maximum likelihood software such as R's `mirt`.
|
|
127
168
|
|
|
128
169
|
## Performance Benchmarks
|
|
129
170
|
|
|
@@ -151,7 +192,7 @@ See `benchmarks/README.md` for detailed information about interpreting results.
|
|
|
151
192
|
|
|
152
193
|
## Development
|
|
153
194
|
|
|
154
|
-
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec`
|
|
195
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rake spec` for the test suite or `bundle exec rake` for the default local quality gate: the RSpec suite and RuboCop. Before tagging a release, run `bundle exec rake build` to verify the gemspec packages cleanly from the current file list; CI also installs the built gem and smoke-tests `require 'irt_ruby'`. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
|
155
196
|
|
|
156
197
|
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
|
157
198
|
|
|
@@ -5,46 +5,6 @@ require "bundler/setup"
|
|
|
5
5
|
require "irt_ruby"
|
|
6
6
|
require "benchmark"
|
|
7
7
|
|
|
8
|
-
# Enhanced model classes that track iterations and convergence
|
|
9
|
-
class TrackedRaschModel < IrtRuby::RaschModel
|
|
10
|
-
attr_reader :iterations, :final_log_likelihood, :convergence_reason
|
|
11
|
-
|
|
12
|
-
def fit
|
|
13
|
-
@iterations = 0
|
|
14
|
-
prev_ll = log_likelihood
|
|
15
|
-
@final_log_likelihood = prev_ll
|
|
16
|
-
@convergence_reason = :max_iterations
|
|
17
|
-
|
|
18
|
-
@max_iter.times do
|
|
19
|
-
@iterations += 1
|
|
20
|
-
grad_abilities, grad_difficulties = compute_gradient
|
|
21
|
-
|
|
22
|
-
old_a, old_d = apply_gradient_update(grad_abilities, grad_difficulties)
|
|
23
|
-
|
|
24
|
-
current_ll = log_likelihood
|
|
25
|
-
param_delta = average_param_update(old_a, old_d)
|
|
26
|
-
|
|
27
|
-
if current_ll < prev_ll
|
|
28
|
-
@abilities = old_a
|
|
29
|
-
@difficulties = old_d
|
|
30
|
-
@learning_rate *= @decay_factor
|
|
31
|
-
else
|
|
32
|
-
ll_diff = (current_ll - prev_ll).abs
|
|
33
|
-
@final_log_likelihood = current_ll
|
|
34
|
-
|
|
35
|
-
if ll_diff < @tolerance && param_delta < @param_tolerance
|
|
36
|
-
@convergence_reason = :tolerance_reached
|
|
37
|
-
break
|
|
38
|
-
end
|
|
39
|
-
|
|
40
|
-
prev_ll = current_ll
|
|
41
|
-
end
|
|
42
|
-
end
|
|
43
|
-
|
|
44
|
-
{ abilities: @abilities, difficulties: @difficulties }
|
|
45
|
-
end
|
|
46
|
-
end
|
|
47
|
-
|
|
48
8
|
def generate_data(num_people, num_items, difficulty_range: (-2..2), ability_range: (-2..2))
|
|
49
9
|
# Generate realistic IRT data based on known parameters
|
|
50
10
|
true_abilities = Array.new(num_people) { rand(ability_range) }
|
|
@@ -84,27 +44,27 @@ tolerance_configs.each do |config|
|
|
|
84
44
|
|
|
85
45
|
times = []
|
|
86
46
|
iterations = []
|
|
87
|
-
|
|
47
|
+
convergences = []
|
|
88
48
|
|
|
89
49
|
5.times do
|
|
90
50
|
time = Benchmark.measure do
|
|
91
|
-
model =
|
|
51
|
+
model = IrtRuby::RaschModel.new(
|
|
92
52
|
data,
|
|
93
53
|
max_iter: 2000,
|
|
94
54
|
tolerance: config[:tolerance],
|
|
95
55
|
param_tolerance: config[:param_tolerance],
|
|
96
56
|
learning_rate: 0.01
|
|
97
57
|
)
|
|
98
|
-
model.fit
|
|
99
|
-
iterations <<
|
|
100
|
-
|
|
58
|
+
result = model.fit
|
|
59
|
+
iterations << result[:iterations]
|
|
60
|
+
convergences << result[:converged]
|
|
101
61
|
end.real
|
|
102
62
|
times << time
|
|
103
63
|
end
|
|
104
64
|
|
|
105
65
|
avg_time = times.sum / times.size
|
|
106
66
|
avg_iterations = iterations.sum.to_f / iterations.size
|
|
107
|
-
convergence_rate =
|
|
67
|
+
convergence_rate = convergences.count(true) / 5.0
|
|
108
68
|
|
|
109
69
|
printf(" Time: %6.3fs Iterations: %6.1f Convergence Rate: %4.0f%%\n",
|
|
110
70
|
avg_time, avg_iterations, convergence_rate * 100)
|
|
@@ -128,27 +88,27 @@ learning_rate_configs.each do |config|
|
|
|
128
88
|
|
|
129
89
|
times = []
|
|
130
90
|
iterations = []
|
|
131
|
-
|
|
91
|
+
convergences = []
|
|
132
92
|
|
|
133
93
|
5.times do
|
|
134
94
|
time = Benchmark.measure do
|
|
135
|
-
model =
|
|
95
|
+
model = IrtRuby::RaschModel.new(
|
|
136
96
|
data,
|
|
137
97
|
max_iter: 1000,
|
|
138
98
|
tolerance: 1e-5,
|
|
139
99
|
param_tolerance: 1e-5,
|
|
140
100
|
learning_rate: config[:rate]
|
|
141
101
|
)
|
|
142
|
-
model.fit
|
|
143
|
-
iterations <<
|
|
144
|
-
|
|
102
|
+
result = model.fit
|
|
103
|
+
iterations << result[:iterations]
|
|
104
|
+
convergences << result[:converged]
|
|
145
105
|
end.real
|
|
146
106
|
times << time
|
|
147
107
|
end
|
|
148
108
|
|
|
149
109
|
avg_time = times.sum / times.size
|
|
150
110
|
avg_iterations = iterations.sum.to_f / iterations.size
|
|
151
|
-
convergence_rate =
|
|
111
|
+
convergence_rate = convergences.count(true) / 5.0
|
|
152
112
|
|
|
153
113
|
printf(" Time: %6.3fs Iterations: %6.1f Convergence Rate: %4.0f%%\n",
|
|
154
114
|
avg_time, avg_iterations, convergence_rate * 100)
|
|
@@ -171,7 +131,7 @@ dataset_configs.each do |config|
|
|
|
171
131
|
|
|
172
132
|
times = []
|
|
173
133
|
iterations = []
|
|
174
|
-
|
|
134
|
+
convergences = []
|
|
175
135
|
|
|
176
136
|
3.times do
|
|
177
137
|
dataset = generate_data(
|
|
@@ -182,23 +142,23 @@ dataset_configs.each do |config|
|
|
|
182
142
|
)
|
|
183
143
|
|
|
184
144
|
time = Benchmark.measure do
|
|
185
|
-
model =
|
|
145
|
+
model = IrtRuby::RaschModel.new(
|
|
186
146
|
dataset[:data],
|
|
187
147
|
max_iter: 1000,
|
|
188
148
|
tolerance: 1e-5,
|
|
189
149
|
param_tolerance: 1e-5,
|
|
190
150
|
learning_rate: 0.01
|
|
191
151
|
)
|
|
192
|
-
model.fit
|
|
193
|
-
iterations <<
|
|
194
|
-
|
|
152
|
+
result = model.fit
|
|
153
|
+
iterations << result[:iterations]
|
|
154
|
+
convergences << result[:converged]
|
|
195
155
|
end.real
|
|
196
156
|
times << time
|
|
197
157
|
end
|
|
198
158
|
|
|
199
159
|
avg_time = times.sum / times.size
|
|
200
160
|
avg_iterations = iterations.sum.to_f / iterations.size
|
|
201
|
-
convergence_rate =
|
|
161
|
+
convergence_rate = convergences.count(true) / 3.0
|
|
202
162
|
|
|
203
163
|
printf(" Time: %6.3fs Iterations: %6.1f Convergence Rate: %4.0f%%\n",
|
|
204
164
|
avg_time, avg_iterations, convergence_rate * 100)
|
|
@@ -223,7 +183,7 @@ missing_configs.each do |config|
|
|
|
223
183
|
# Generate data with missing values
|
|
224
184
|
base_data = generate_data(100, 50)[:data]
|
|
225
185
|
|
|
226
|
-
data_with_missing = if
|
|
186
|
+
data_with_missing = if config[:rate].positive?
|
|
227
187
|
base_data.map do |row|
|
|
228
188
|
row.map { |resp| rand < config[:rate] ? nil : resp }
|
|
229
189
|
end
|
|
@@ -233,11 +193,11 @@ missing_configs.each do |config|
|
|
|
233
193
|
|
|
234
194
|
times = []
|
|
235
195
|
iterations = []
|
|
236
|
-
|
|
196
|
+
convergences = []
|
|
237
197
|
|
|
238
198
|
3.times do
|
|
239
199
|
time = Benchmark.measure do
|
|
240
|
-
model =
|
|
200
|
+
model = IrtRuby::RaschModel.new(
|
|
241
201
|
data_with_missing,
|
|
242
202
|
max_iter: 1000,
|
|
243
203
|
tolerance: 1e-5,
|
|
@@ -245,16 +205,16 @@ missing_configs.each do |config|
|
|
|
245
205
|
learning_rate: 0.01,
|
|
246
206
|
missing_strategy: config[:strategy]
|
|
247
207
|
)
|
|
248
|
-
model.fit
|
|
249
|
-
iterations <<
|
|
250
|
-
|
|
208
|
+
result = model.fit
|
|
209
|
+
iterations << result[:iterations]
|
|
210
|
+
convergences << result[:converged]
|
|
251
211
|
end.real
|
|
252
212
|
times << time
|
|
253
213
|
end
|
|
254
214
|
|
|
255
215
|
avg_time = times.sum / times.size
|
|
256
216
|
avg_iterations = iterations.sum.to_f / iterations.size
|
|
257
|
-
convergence_rate =
|
|
217
|
+
convergence_rate = convergences.count(true) / 3.0
|
|
258
218
|
|
|
259
219
|
printf(" Time: %6.3fs Iterations: %6.1f Convergence Rate: %4.0f%%\n",
|
|
260
220
|
avg_time, avg_iterations, convergence_rate * 100)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module IrtRuby
|
|
4
|
+
# Numerical helpers shared by IRT model implementations.
|
|
5
|
+
# @api private
|
|
6
|
+
module Estimation
|
|
7
|
+
# Learning-rate multiplier after an accepted step, so the rate can recover from earlier decays.
|
|
8
|
+
LEARNING_RATE_GROWTH = 1.1
|
|
9
|
+
|
|
10
|
+
module_function
|
|
11
|
+
|
|
12
|
+
def log_sigmoid(x)
|
|
13
|
+
x >= 0 ? -Math.log(1.0 + Math.exp(-x)) : x - Math.log(1.0 + Math.exp(x))
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def each_response(responses, persons, items)
|
|
17
|
+
responses.each_with_index do |row, i|
|
|
18
|
+
next unless persons[i]
|
|
19
|
+
|
|
20
|
+
row.each_with_index do |value, j|
|
|
21
|
+
next if value.nil? || !items[j]
|
|
22
|
+
|
|
23
|
+
yield i, j, value
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def response_counts(responses, persons, items)
|
|
29
|
+
person_counts = Array.new(responses.size, 0)
|
|
30
|
+
item_counts = Array.new(responses.first.size, 0)
|
|
31
|
+
each_response(responses, persons, items) do |i, j, _value|
|
|
32
|
+
person_counts[i] += 1
|
|
33
|
+
item_counts[j] += 1
|
|
34
|
+
end
|
|
35
|
+
[person_counts, item_counts]
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# True when every gradient component, averaged over the responses it sums, is below tolerance.
|
|
39
|
+
def stationary?(person_gradient, item_gradients, person_counts, item_counts, tolerance)
|
|
40
|
+
small_residuals?(person_gradient, person_counts, tolerance) &&
|
|
41
|
+
item_gradients.all? { |gradient| small_residuals?(gradient, item_counts, tolerance) }
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def small_residuals?(gradient, counts, tolerance)
|
|
45
|
+
gradient.each_index.all? { |k| counts[k].zero? || (gradient[k] / counts[k]).abs < tolerance }
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Drops gradient components that push a parameter further past the bound it sits on.
|
|
49
|
+
def project(gradient, values, min, max)
|
|
50
|
+
gradient.each_index.map do |k|
|
|
51
|
+
blocked = (values[k] <= min && gradient[k].negative?) || (values[k] >= max && gradient[k].positive?)
|
|
52
|
+
blocked ? 0.0 : gradient[k]
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Location and scale of the estimable abilities, used to report parameters on a fixed scale.
|
|
57
|
+
def scale(abilities, active)
|
|
58
|
+
values = abilities.select.with_index { |_, i| active[i] }
|
|
59
|
+
return [0.0, 1.0] if values.empty?
|
|
60
|
+
|
|
61
|
+
mean, sd = mean_and_sd(values)
|
|
62
|
+
[mean, sd.zero? ? 1.0 : sd]
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def mean_and_sd(values)
|
|
66
|
+
mean = values.sum / values.size
|
|
67
|
+
[mean, Math.sqrt(values.sum { |v| (v - mean)**2 } / values.size)]
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def changes(current, previous, active)
|
|
71
|
+
current.each_index.select { |k| active[k] }.map { |k| (current[k] - previous[k]).abs }
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def estimates(values, active)
|
|
75
|
+
values.each_index.map { |k| active[k] ? values[k] : nil }
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module IrtRuby
|
|
4
|
+
# Validates optimization hyperparameters shared by IRT model implementations.
|
|
5
|
+
module ModelOptionsValidator
|
|
6
|
+
module_function
|
|
7
|
+
|
|
8
|
+
def validate!(max_iter:, tolerance:, param_tolerance:, gradient_tolerance:, learning_rate:, decay_factor:)
|
|
9
|
+
validate_positive_integer!(:max_iter, max_iter)
|
|
10
|
+
validate_positive_finite_numeric!(:tolerance, tolerance)
|
|
11
|
+
validate_positive_finite_numeric!(:param_tolerance, param_tolerance)
|
|
12
|
+
validate_positive_finite_numeric!(:gradient_tolerance, gradient_tolerance)
|
|
13
|
+
validate_positive_finite_numeric!(:learning_rate, learning_rate)
|
|
14
|
+
validate_decay_factor!(decay_factor)
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def validate_positive_integer!(name, value)
|
|
18
|
+
return if value.is_a?(Integer) && value.positive?
|
|
19
|
+
|
|
20
|
+
raise ArgumentError, "#{name} must be a positive Integer"
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def validate_positive_finite_numeric!(name, value)
|
|
24
|
+
return if finite_numeric?(value) && value.positive?
|
|
25
|
+
|
|
26
|
+
raise ArgumentError, "#{name} must be a positive finite Numeric"
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def validate_decay_factor!(value)
|
|
30
|
+
return if finite_numeric?(value) && value.positive? && value < 1
|
|
31
|
+
|
|
32
|
+
raise ArgumentError, "decay_factor must be a finite Numeric strictly between 0 and 1"
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def finite_numeric?(value)
|
|
36
|
+
value.is_a?(Numeric) && !value.is_a?(Complex) && value.finite?
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|