Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,28 @@ All notable changes to this project are documented in this file.

## [Unreleased]

### Added
- Added executable specs for README usage examples to keep the documented Rasch, 2PL, 3PL, and missing-data flows aligned with the public API.
### Fixed
- Fixed 3PL gradients for ability, difficulty, discrimination, and guessing; they now match finite differences of the log-likelihood.
- 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.
- 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.
- 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.
- Models copy response data on construction and return fresh arrays from `fit`, so later mutation of either does not change model state.

### Changed
- `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.
- `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`).
- The learning rate grows by 10% after each accepted step, so it can recover from earlier decreases.
- Clarified the gem summary and description to describe implemented capabilities rather than production-readiness claims.
- Added CI RuboCop and gem package build/install verification, and documented the local quality and packaging commands for contributors.
- 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.

### Added
- Added finite-difference gradient, identification, extreme-pattern, and parameter-recovery specs.
- Added executable specs for README usage examples to keep the documented Rasch, 2PL, 3PL, and missing-data flows aligned with the public API.

---

## [0.3.0] - 2025-01-14
## [0.3.0] - 2025-06-13

### Changed
- **Code Quality**
Expand Down
4 changes: 3 additions & 1 deletion Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ gem "rake", "~> 13.0"

gem "rspec", "~> 3.0"

gem "rubocop", "~> 1.21"
# Exact pin: NewCops is enabled, so any RuboCop release can add offenses.
# This version needs Ruby >= 2.7; the Ruby 2.6 CI job only runs the specs.
gem "rubocop", "1.92.0", require: false if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("2.7")

# Performance benchmarking
gem "benchmark-ips", "~> 2.0"
Expand Down
31 changes: 26 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,12 @@ result = model.fit
# Output the estimated abilities and difficulties
puts "Abilities: #{result[:abilities]}"
puts "Difficulties: #{result[:difficulties]}"
puts "Converged: #{result[:converged]} after #{result[:iterations]} iterations"
```

The third respondent answered every item correctly, so their ability has no
finite estimate and is returned as `nil` (see [Estimation Details](#estimation-details)).

Response data passed to model constructors must be either a `Matrix` or an
array of arrays. Each response value must be the integer `0`, the integer `1`,
or `nil` for missing data; floats such as `0.0`/`1.0`, strings, booleans, and
Expand All @@ -69,6 +73,10 @@ puts three_pl_result[:discriminations]
puts three_pl_result[:guessings]
```

Three respondents are far too few for 2PL or 3PL: on this matrix `fit` returns
`converged: false`. Discrimination and guessing estimates need hundreds of
respondents.

## Handling Missing Data
Real-world data often has missing responses. Each model (Rasch, 2PL, 3PL) accepts a `missing_strategy:` option to handle nil entries:

Expand Down Expand Up @@ -102,16 +110,20 @@ This flexibility helps you handle datasets where missingness might signify a ski
### Adaptive Learning Rate & Convergence
By default, each model uses a gradient ascent with:

- An adaptive learning rate (if log-likelihood decreases, it reverts the step and reduces the rate).
- Multiple convergence checks (change in log-likelihood and average parameter updates).
- 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%.
- A stopping rule on the change in log-likelihood and the average parameter update.
- A stationarity check that decides whether the stopping point is reported as converged.

You can customize:

- `max_iter`: The maximum number of iterations.
- `tolerance` and `param_tolerance`: Convergence thresholds for log-likelihood change and parameter updates.
- `tolerance` and `param_tolerance`: Stopping thresholds for log-likelihood change and parameter updates.
- `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.
- `learning_rate`: Initial learning rate.
- `decay_factor`: Factor by which the learning rate is reduced on a failed step.

`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.

Example:
```ruby
IrtRuby::TwoParameterModel.new(
Expand Down Expand Up @@ -140,10 +152,19 @@ The `seed:` keyword is available for `RaschModel`, `TwoParameterModel`, and `Thr
### Parameter Clamping
For 2PL and 3PL:

- **Discriminations** (`a`) are clamped between `0.01` and `5.0`.
- **Discriminations** (`a`) are clamped between `0.01` and `5.0` during optimization.
- **Guessings** (`c`, 3PL only) are clamped to `[0.0, 0.35]`.

This prevents extreme or invalid parameter estimates.
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]`.

## Estimation Details

All models estimate person and item parameters jointly by maximizing the likelihood (joint maximum likelihood, JMLE).

- **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.
- **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.
- **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.
- **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`.

## Performance Benchmarks

Expand Down
88 changes: 24 additions & 64 deletions benchmarks/convergence_benchmark.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,46 +5,6 @@
require "irt_ruby"
require "benchmark"

# Enhanced model classes that track iterations and convergence
class TrackedRaschModel < IrtRuby::RaschModel
attr_reader :iterations, :final_log_likelihood, :convergence_reason

def fit
@iterations = 0
prev_ll = log_likelihood
@final_log_likelihood = prev_ll
@convergence_reason = :max_iterations

@max_iter.times do
@iterations += 1
grad_abilities, grad_difficulties = compute_gradient

old_a, old_d = apply_gradient_update(grad_abilities, grad_difficulties)

current_ll = log_likelihood
param_delta = average_param_update(old_a, old_d)

if current_ll < prev_ll
@abilities = old_a
@difficulties = old_d
@learning_rate *= @decay_factor
else
ll_diff = (current_ll - prev_ll).abs
@final_log_likelihood = current_ll

if ll_diff < @tolerance && param_delta < @param_tolerance
@convergence_reason = :tolerance_reached
break
end

prev_ll = current_ll
end
end

{ abilities: @abilities, difficulties: @difficulties }
end
end

def generate_data(num_people, num_items, difficulty_range: (-2..2), ability_range: (-2..2))
# Generate realistic IRT data based on known parameters
true_abilities = Array.new(num_people) { rand(ability_range) }
Expand Down Expand Up @@ -84,27 +44,27 @@ def generate_data(num_people, num_items, difficulty_range: (-2..2), ability_rang

times = []
iterations = []
convergence_reasons = []
convergences = []

5.times do
time = Benchmark.measure do
model = TrackedRaschModel.new(
model = IrtRuby::RaschModel.new(
data,
max_iter: 2000,
tolerance: config[:tolerance],
param_tolerance: config[:param_tolerance],
learning_rate: 0.01
)
model.fit
iterations << model.iterations
convergence_reasons << model.convergence_reason
result = model.fit
iterations << result[:iterations]
convergences << result[:converged]
end.real
times << time
end

avg_time = times.sum / times.size
avg_iterations = iterations.sum.to_f / iterations.size
convergence_rate = convergence_reasons.count(:tolerance_reached) / 5.0
convergence_rate = convergences.count(true) / 5.0

printf(" Time: %6.3fs Iterations: %6.1f Convergence Rate: %4.0f%%\n",
avg_time, avg_iterations, convergence_rate * 100)
Expand All @@ -128,27 +88,27 @@ def generate_data(num_people, num_items, difficulty_range: (-2..2), ability_rang

times = []
iterations = []
convergence_reasons = []
convergences = []

5.times do
time = Benchmark.measure do
model = TrackedRaschModel.new(
model = IrtRuby::RaschModel.new(
data,
max_iter: 1000,
tolerance: 1e-5,
param_tolerance: 1e-5,
learning_rate: config[:rate]
)
model.fit
iterations << model.iterations
convergence_reasons << model.convergence_reason
result = model.fit
iterations << result[:iterations]
convergences << result[:converged]
end.real
times << time
end

avg_time = times.sum / times.size
avg_iterations = iterations.sum.to_f / iterations.size
convergence_rate = convergence_reasons.count(:tolerance_reached) / 5.0
convergence_rate = convergences.count(true) / 5.0

printf(" Time: %6.3fs Iterations: %6.1f Convergence Rate: %4.0f%%\n",
avg_time, avg_iterations, convergence_rate * 100)
Expand All @@ -171,7 +131,7 @@ def generate_data(num_people, num_items, difficulty_range: (-2..2), ability_rang

times = []
iterations = []
convergence_reasons = []
convergences = []

3.times do
dataset = generate_data(
Expand All @@ -182,23 +142,23 @@ def generate_data(num_people, num_items, difficulty_range: (-2..2), ability_rang
)

time = Benchmark.measure do
model = TrackedRaschModel.new(
model = IrtRuby::RaschModel.new(
dataset[:data],
max_iter: 1000,
tolerance: 1e-5,
param_tolerance: 1e-5,
learning_rate: 0.01
)
model.fit
iterations << model.iterations
convergence_reasons << model.convergence_reason
result = model.fit
iterations << result[:iterations]
convergences << result[:converged]
end.real
times << time
end

avg_time = times.sum / times.size
avg_iterations = iterations.sum.to_f / iterations.size
convergence_rate = convergence_reasons.count(:tolerance_reached) / 3.0
convergence_rate = convergences.count(true) / 3.0

printf(" Time: %6.3fs Iterations: %6.1f Convergence Rate: %4.0f%%\n",
avg_time, avg_iterations, convergence_rate * 100)
Expand Down Expand Up @@ -233,28 +193,28 @@ def generate_data(num_people, num_items, difficulty_range: (-2..2), ability_rang

times = []
iterations = []
convergence_reasons = []
convergences = []

3.times do
time = Benchmark.measure do
model = TrackedRaschModel.new(
model = IrtRuby::RaschModel.new(
data_with_missing,
max_iter: 1000,
tolerance: 1e-5,
param_tolerance: 1e-5,
learning_rate: 0.01,
missing_strategy: config[:strategy]
)
model.fit
iterations << model.iterations
convergence_reasons << model.convergence_reason
result = model.fit
iterations << result[:iterations]
convergences << result[:converged]
end.real
times << time
end

avg_time = times.sum / times.size
avg_iterations = iterations.sum.to_f / iterations.size
convergence_rate = convergence_reasons.count(:tolerance_reached) / 3.0
convergence_rate = convergences.count(true) / 3.0

printf(" Time: %6.3fs Iterations: %6.1f Convergence Rate: %4.0f%%\n",
avg_time, avg_iterations, convergence_rate * 100)
Expand Down
15 changes: 7 additions & 8 deletions irt_ruby.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ Gem::Specification.new do |spec|
spec.authors = ["Alex Kholodniak"]
spec.email = ["alexandrkholodniak@gmail.com"]

spec.summary = "Production-ready Item Response Theory (IRT) models with comprehensive performance benchmarking and adaptive optimization."
spec.summary = "Rasch, 2PL, and 3PL Item Response Theory (IRT) models estimated by joint maximum likelihood."
spec.description = <<~DESC
IrtRuby is a comprehensive Ruby library for Item Response Theory (IRT) analysis,#{" "}
IrtRuby is a Ruby library for Item Response Theory (IRT) analysis,#{" "}
commonly used in educational assessment, psychological testing, and survey research.

Features three core IRT models:
Expand All @@ -19,13 +19,12 @@ Gem::Specification.new do |spec|
• Three-Parameter Model (3PL) - Includes guessing parameter

Key capabilities:
• Robust gradient ascent optimization with adaptive learning rates
• Flexible missing data strategies (ignore, treat as incorrect/correct)
• Comprehensive performance benchmarking suite
• Memory-efficient implementation with excellent scaling
• Production-ready with extensive test coverage
• Joint maximum likelihood by gradient ascent with an adaptive learning rate
• Convergence reporting, scale identification, and exclusion of extreme response patterns
• Missing data strategies (ignore, treat as incorrect/correct)
• Performance and convergence benchmark scripts

Perfect for researchers, data scientists, and developers working with#{" "}
Intended for researchers, data scientists, and developers working with#{" "}
educational assessments, psychological measurements, or any binary response data
where item and person parameters need to be estimated simultaneously.
DESC
Expand Down
2 changes: 2 additions & 0 deletions lib/irt_ruby.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
require "matrix"
require "irt_ruby/model_options_validator"
require "irt_ruby/response_data_validator"
require "irt_ruby/estimation"
require "irt_ruby/response_graph"
require "irt_ruby/rasch_model"
require "irt_ruby/two_parameter_model"
require "irt_ruby/three_parameter_model"
Expand Down
Loading
Loading