Skip to main content

02 - Adaptive Learning: IRT, BKT and DKT in Production

How to choose between IRT, BKT and DKT to pick the right exercise, with executed code: ability estimation, tracing, calibration and A/B testing.

What do you think about this article?

At a Glance

How to choose between IRT, BKT and DKT to pick the right exercise, with executed code: ability estimation, tracing, calibration and A/B testing.

Which exercise should this student get now?

An adaptive learning system answers a single question, every time a student finishes an exercise: what comes next? Answering it takes two estimates. The first is how good the student is right now, the second is how hard each available exercise is. With the two estimates you can pick an exercise that is neither trivial nor out of reach. This article compares three families of models for obtaining them, Item Response Theory (IRT), Bayesian Knowledge Tracing (BKT) and Deep Knowledge Tracing (DKT), and shows with executed code how to check them once they are in production.

You need Python and an idea of conditional probability; nothing else. If you are coming from the series, in the previous article on Scalable LMS Architecture you will find where student data lives, and in Learning Analytics with xAPI and Kafka how the events that feed these models arrive. Throughout the text the example is a maths course with five exercises, from adding fractions to linear systems: small enough that you can read every number.

IRT: measuring ability and difficulty on the same scale

IRT gives every student one number, theta, and every exercise two: the difficulty b and the discrimination a. In the two-parameter model (2PL) the probability of answering correctly is 1 / (1 + exp(-a · (theta - b))). In words: when theta equals b the probability is exactly 0.5, and the more theta exceeds b the higher it climbs; a decides how steep the climb is. An exercise with a high a sharply separates those who have passed the threshold from those who have not, one with a low a tells them apart very little. The three-parameter model adds the probability of guessing and, as the article on the mirt package describes, it reduces to 1PL or 2PL by fixing some parameters.

The listing does three things. It computes the probability and the Fisher information a² · p · (1 - p), which measures how much an exercise teaches you about theta when the student is at that point; it estimates theta from the answers with Newton's method; and it picks as the next exercise the one with the most information. The estimate is a MAP with a standard normal prior (the line g = -theta is the gradient of the prior): without it, a student who answers everything correctly would have a theta growing without bound, and you will find out on the last line of the code, where six correct answers give 1.29 and not infinity.

Python - IRT 2PL: ability estimation and choice of the next exercise
import math

def p_correct(theta, a, b):
    """2PL model: probability of a correct answer."""
    return 1.0 / (1.0 + math.exp(-a * (theta - b)))

def info(theta, a, b):
    """Fisher information of the item: how much it 'says' about theta at that point."""
    p = p_correct(theta, a, b)
    return a * a * p * (1.0 - p)

def estimate_theta(answers, theta=0.0, steps=20):
    """MAP estimate with an N(0,1) prior, by Newton-Raphson. answers = [(a, b, correct)]."""
    for _ in range(steps):
        g = -theta                     # gradient of the log-prior
        h = -1.0                       # second derivative of the log-prior
        for a, b, x in answers:
            p = p_correct(theta, a, b)
            g += a * (x - p)
            h -= a * a * p * (1.0 - p)
        theta -= g / h
    return theta

bank = {
    "adding fractions":       (1.2, -1.0),
    "multiplying fractions":  (1.0, -0.3),
    "linear equations":       (1.5,  0.2),
    "fractional equations":   (1.1,  0.9),
    "linear systems":         (1.8,  1.5),
}

print("P(correct) when theta = b:", p_correct(0.2, 1.5, 0.2))
print("maximum information = a^2/4:", round(info(0.2, 1.5, 0.2), 4), "versus", 1.5**2 / 4)

theta, answers, used = 0.0, [], set()
true_student = 0.8   # an 'ideal student': answers correctly if true_theta > b
for turn in range(1, 5):
    name = max((n for n in bank if n not in used), key=lambda n: info(theta, *bank[n]))
    a, b = bank[name]
    correct = 1 if true_student > b else 0
    answers.append((a, b, correct)); used.add(name)
    theta = estimate_theta(answers)
    print(f"turn {turn}: {name:<24} b={b:+.1f} outcome={correct} -> theta={theta:+.2f}")

# Without the prior, the estimate for someone who answers everything correctly would go to infinity.
print("six correct answers on items with b=0, theta with prior:", round(estimate_theta([(1.0, 0.0, 1)] * 6), 2))

# Output:
# P(correct) when theta = b: 0.5
# maximum information = a^2/4: 0.5625 versus 0.5625
# turn 1: linear equations         b=+0.2 outcome=1 -> theta=+0.55
# turn 2: linear systems           b=+1.5 outcome=0 -> theta=+0.41
# turn 3: fractional equations     b=+0.9 outcome=0 -> theta=+0.22
# turn 4: multiplying fractions    b=-0.3 outcome=1 -> theta=+0.38
# six correct answers on items with b=0, theta with prior: 1.29

In the output the first two lines verify the theory: at theta = b the probability is 0.5 and the information is a²/4 (0.5625 for a = 1.5), its maximum. That is why the system, starting from theta = 0, proposes first the exercise with the closest b (first-degree equations, b = 0.2) and always chooses what lies at the edge of the student's ability. The "ideal student" of the listing answers correctly when their true theta (0.8) exceeds b: that is why they fail the linear systems and the fractional equations and the estimated theta oscillates instead of approaching 0.8. With four answers the estimate is still provisional, and that is normal: IRT gives you a number, its uncertainty you must compute separately (it is the inverse of the sum of the information).

The limit of IRT is that it photographs a student at one instant and says nothing about whether, after the exercise, they know more. The parameters a and b must then be calibrated on many answers from many students: as long as a question is new, its difficulty is the teacher's hypothesis.

BKT: a probability that changes with every exercise

Bayesian Knowledge Tracing does not measure a level, but follows one skill at a time and asks: does the student possess it now, yes or no? As the article on Deep Knowledge Tracing summarizes, BKT represents knowledge as a binary variable per skill and uses a hidden Markov model to update the probability at every answer. Four numbers describe it.

  • p0: the probability that the student already knows it before starting.
  • learn: the probability of learning it at each new practice opportunity.
  • guess: the probability of answering correctly without knowing, by luck.
  • slip: the probability of answering wrongly while knowing, by distraction.

Of the four, guess and slip are the ones a teacher understands at a glance: in a multiple-choice quiz with four options guess cannot fall much below 0.25. The other two are those the model learns from the data. The original model also assumes that a skill, once learned, is never forgotten (the same source says so), and it is an assumption to keep in mind for skills that are rarely used.

The update step has two moments, and they must be kept apart in the code. First Bayes' rule is applied to the outcome just observed (the line with post): a correct answer makes "knows" more probable in proportion to 1 - slip against guess. Then the chance of having learned in the meantime is added, post + (1 - post) * learn. The function prob_correct uses the current estimate to predict the outcome before seeing it, and it is the only thing you need to evaluate the model. The listing follows the sequence of answers 0, 0, 1, 0, 1, 1, 1, 1, 1.

Python - Bayesian Knowledge Tracing with a trace and an identifiability check
def update(p_know, correct, guess, slip, learn):
    """One BKT step: first the evidence (Bayes), then the chance of having learned."""
    if correct:
        post = p_know * (1 - slip) / (p_know * (1 - slip) + (1 - p_know) * guess)
    else:
        post = p_know * slip / (p_know * slip + (1 - p_know) * (1 - guess))
    return post + (1 - post) * learn

def prob_correct(p_know, guess, slip):
    return p_know * (1 - slip) + (1 - p_know) * guess

def trace(outcomes, p0, learn, guess, slip, threshold=0.95):
    p, mastery = p0, None
    rows = []
    for i, x in enumerate(outcomes, 1):
        prediction = prob_correct(p, guess, slip)
        p = update(p, x, guess, slip, learn)
        if mastery is None and p >= threshold:
            mastery = i
        rows.append((i, x, prediction, p))
    return rows, mastery

if __name__ == "__main__":
    outcomes = [0, 0, 1, 0, 1, 1, 1, 1, 1]
    rows, m = trace(outcomes, p0=0.20, learn=0.15, guess=0.20, slip=0.10)
    print("opp. outcome  predicted P(correct)  P(know) after")
    for i, x, pred, p in rows:
        print(f"{i:>4} {x:>7} {pred:>20.2f} {p:>14.2f}")
    print("mastery (threshold 0.95) at opportunity:", m)

    # Identifiability: with guess + slip = 1 an answer does not move the estimate.
    for g, s in [(0.20, 0.10), (0.50, 0.50)]:
        p = 0.30
        after_correct = p * (1 - s) / (p * (1 - s) + (1 - p) * g)
        print(f"guess={g} slip={s}: P(know)=0.30 -> after a correct answer {after_correct:.2f}")

# Output:
# opp. outcome  predicted P(correct)  P(know) after
#    1       0                 0.34           0.18
#    2       0                 0.32           0.17
#    3       1                 0.32           0.56
#    4       0                 0.59           0.27
#    5       1                 0.39           0.68
#    6       1                 0.67           0.92
#    7       1                 0.84           0.98
#    8       1                 0.89           1.00
#    9       1                 0.90           1.00
# mastery (threshold 0.95) at opportunity: 7
# guess=0.2 slip=0.1: P(know)=0.30 -> after a correct answer 0.66
# guess=0.5 slip=0.5: P(know)=0.30 -> after a correct answer 0.30

The trace reads like this. Two initial errors lower the estimate from 0.20 to 0.17; an isolated correct answer (third row) lifts it to 0.56 because with guess = 0.20 guessing is rare; the next error lowers it again to 0.27, because the model knows that someone who knows can still get it wrong. With three correct answers in a row the estimate passes the mastery threshold of 0.95 at the seventh opportunity. The threshold is a pedagogical choice, not a theorem: 0.95 means "I stop you when I am almost sure", a lower threshold stops earlier and makes more students fail. The last two lines show the trouble with identifiability: with guess = slip = 0.5 a correct answer does not move the estimate (it stays at 0.30), because the model says that knowing and not knowing answer the same way. If calibration on the data returns parameters like these, you do not have a model, you have a random number generator.

DKT: a neural network in place of assumptions

Deep Knowledge Tracing replaces the assumptions of BKT (one skill at a time, never forgotten, four parameters) with a recurrent network, an LSTM, which reads the sequence of the student's answers and outputs the probability of answering each exercise correctly. In table 1 of the original article the AUC (the metric we explain in the section on evaluation) on the Khan Math dataset is 0.85 against 0.68 for standard BKT, and on ASSISTments it is 0.86 against 0.67, or 0.69 for the best BKT variant reported in the literature. These are the authors' results on specific datasets, not a general property.

A note of caution, because it is the point where many articles stop: a later study (Khajah, Lindsey and Mozer, "How deep is knowledge tracing?") argues that, by extending BKT with some already-known variants (recency effects, sequence context, similarity between skills, individual ability differences), its level of performance becomes indistinguishable from that of DKT. In practice the advantage of the neural network on that data lies in the regularities a simple BKT ignores, not in some deep learning magic. So, before adopting DKT, it is worth asking what you need: if it is an accurate prediction, the network may suffice; if it is an explanation a teacher can read ("does not master fractions"), BKT is far more convenient.

There is no DKT listing: it requires a deep learning framework and a training dataset, and a block that cannot be run here would add nothing to the other four. The structure is simple anyway: the input at each step is the (exercise, outcome) pair encoded one-hot, the hidden state of the LSTM summarizes the history, the output is a vector with the probability of success on every exercise. The detail is in the model section of the original article.

Putting the model into production

In production it pays to separate two paths. The online path answers the request "give me the next exercise": it reads the student's current estimate (for BKT that is a few numbers per skill, suited to a fast cache), applies the rule and returns an exercise. The offline path runs at intervals: it recalibrates a and b or the BKT parameters on the accumulated data and publishes the new values. The separation is needed because calibration is expensive and can go wrong, while the answer to the student must always be available; if recalibration produces absurd parameters, the online path continues with the previous ones. On a multi-tenant platform the key of every estimate also contains the customer, for the same reason seen in the opening article.

The most important constraint is not technical: the model proposes, the curriculum disposes. No matter how high the estimated probability is: you do not propose integrals to someone who has not yet tackled derivatives. The algorithm chooses among the exercises that the prerequisite graph makes admissible, and not outside them. For the new student, with no history, the initial estimate is a hypothesis; a short diagnostic test at the start avoids starting from a flat prior and sending them on a pointless path.

Evaluating, and noticing when the model breaks

The most used metric in the literature is the AUC: the probability that, taking a correct and a wrong answer at random, the model gave a higher score to the correct one. It is 0.5 for a predictor that distinguishes nothing and 1 for a perfect one. But AUC measures only the order, not whether "0.8" really means 8 out of 10: for that you need calibration, which groups the predictions into bands and compares the predicted mean with the observed frequency. The listing simulates 2000 students per cohort, each with 20 opportunities, with a true BKT process. Cohort A has the parameters the model knows; in B the probability of guessing rises from 0.20 to 0.40, as would happen if the answers of a quiz had leaked.

Python - AUC and calibration on synthetic data, with a cohort that changes
import random
from bkt import update, prob_correct  # the module of the previous listing

def simulate(n_students, n_opp, p0, learn, guess, slip, seed):
    """Synthetic data from a true BKT process. Returns a list of (model prediction, outcome)."""
    rng = random.Random(seed)
    events = []
    for _ in range(n_students):
        knows = rng.random() < p0
        p = 0.30                               # the model starts from p0 = 0.30
        for _ in range(n_opp):
            outcome = rng.random() < ((1 - slip) if knows else guess)
            events.append((prob_correct(p, 0.20, 0.10), int(outcome)))
            p = update(p, outcome, 0.20, 0.10, 0.12)   # the model's parameters (not the true ones of B)
            if not knows and rng.random() < learn:
                knows = True
    return events

def auc(events):
    """AUC = probability that a correct outcome gets a higher score than a wrong one (ties = 0.5)."""
    ordered = sorted(events)
    rank_sum, i, sum_pos, n_pos = 0.0, 0, 0.0, 0
    while i < len(ordered):
        j = i
        while j < len(ordered) and ordered[j][0] == ordered[i][0]:
            j += 1
        mean_rank = (i + 1 + j) / 2
        for _, y in ordered[i:j]:
            if y:
                sum_pos += mean_rank; n_pos += 1
        i = j
    n_neg = len(ordered) - n_pos
    return (sum_pos - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg)

def calibration(events, buckets=5):
    rows = []
    for k in range(buckets):
        lo, hi = k / buckets, (k + 1) / buckets
        sel = [(p, y) for p, y in events if lo <= p < hi or (k == buckets - 1 and p == 1)]
        if sel:
            rows.append((lo, hi, len(sel), sum(p for p, _ in sel) / len(sel), sum(y for _, y in sel) / len(sel)))
    return rows

A = simulate(2000, 20, 0.30, 0.12, guess=0.20, slip=0.10, seed=7)   # same as the model
B = simulate(2000, 20, 0.30, 0.12, guess=0.40, slip=0.10, seed=8)   # cohort with leaked answers: guess goes up
for name, ev in [("cohort A", A), ("cohort B", B)]:
    marg = sum(y for _, y in ev) / len(ev)
    print(f"{name}: events={len(ev)} model AUC={auc(ev):.3f} marginal AUC={auc([(marg, y) for _, y in ev]):.3f}")
    for lo, hi, n, pm, om in calibration(ev):
        print(f"  pred {lo:.1f}-{hi:.1f}  n={n:>5}  predicted={pm:.2f}  observed={om:.2f}")

# Output:
# cohort A: events=40000 model AUC=0.801 marginal AUC=0.500
#   pred 0.2-0.4  n= 8086  predicted=0.31  observed=0.32
#   pred 0.4-0.6  n= 4809  predicted=0.48  observed=0.48
#   pred 0.6-0.8  n= 3048  predicted=0.72  observed=0.72
#   pred 0.8-1.0  n=24057  predicted=0.89  observed=0.89
# cohort B: events=40000 model AUC=0.736 marginal AUC=0.500
#   pred 0.2-0.4  n= 4985  predicted=0.32  observed=0.48
#   pred 0.4-0.6  n= 4870  predicted=0.48  observed=0.56
#   pred 0.6-0.8  n= 3867  predicted=0.71  observed=0.66
#   pred 0.8-1.0  n=26278  predicted=0.89  observed=0.87

The data are synthetic: they do not prove that BKT works on real students, they prove that the two metrics work. The constant predictor (the global mean) scores 0.500 by construction, because it distinguishes nothing. On cohort A the model scores 0.801 and the bands are calibrated to the hundredth (predicted 0.31 and observed 0.32 in the first, 0.89 and 0.89 in the last). On B the AUC falls to 0.736, but the clearest signal is calibration: in the 0.2-0.4 band the model predicts 0.32 and students answer correctly 48% of the time. It is a calibration drift, and a system that looks only at the average accuracy does not see it. You run it with python3 metrics.py (without -I) in the folder that also contains bkt.py, because it imports it.

When an alert of this kind fires, the useful question is what has changed in the data: new teaching material, the end of the semester, a question circulating in a chat. There is no universal threshold to copy, and that is why the article proposes none: choose yours by observing the normal variation between similar cohorts over a period.

Trying a new algorithm without harming students

A new adaptive algorithm is tried on one group of students, with another group as a control. Two things set it apart from an A/B test on a button. The student must stay in the same arm for the whole experiment (a path that changes method at every session measures nothing), and the result that counts is learning, not time spent. The listing assigns the arm with a hash of the student identifier and the experiment name, so nothing needs to be stored and the same person always falls on the same side.

Python - Stable assignment to the arms of an experiment
import hashlib
from collections import Counter

def arm(student_id: str, experiment: str, weights=(("control", 50), ("adaptive", 50))) -> str:
    """Stable assignment: same student + same experiment = same arm, always."""
    h = hashlib.sha256(f"{experiment}:{student_id}".encode()).digest()
    n = int.from_bytes(h[:8], "big") % sum(p for _, p in weights)
    for name, weight in weights:
        if n < weight:
            return name
        n -= weight

ids = [f"student-{i}" for i in range(10_000)]
print(Counter(arm(i, "irt-v2") for i in ids))
print("same student twice:", arm("student-42", "irt-v2"), arm("student-42", "irt-v2"))
others = sum(arm(i, "irt-v2") != arm(i, "bkt-v3") for i in ids)
print("switch arm when moving to another experiment:", others, "out of", len(ids))

# Output:
# Counter({'control': 5003, 'adaptive': 4997})
# same student twice: adaptive adaptive
# switch arm when moving to another experiment: 5050 out of 10000

The output shows two properties. On 10,000 identifiers the split is 5003 against 4997, close to half without having imposed it. And the assignment depends on the experiment name as well as on the student: moving from irt-v2 to bkt-v3, 5050 students out of 10,000 change arm, about half as you would expect from two independent assignments. Without that prefix, whoever is always in the experimental arm would be so for every future experiment, and the effects would add up. The number of students needed to see a real effect depends on the effect you hope for and on the variability of your data: you compute it with a power analysis before starting, not with a rule found in an article.

What not to optimize, and what to leave to the teacher

The risk that weighs most is optimizing for the wrong metric. A system that maximizes the time spent on the platform or the number of sessions tends to give easy exercises, which satisfy, instead of those that lead to mastery. The success metric is defined in terms of learning (for example performance on a test some time later) before writing the first model. Four more rules, which depend on the context more than on the theory:

  • Explainability: every proposal has a readable sentence ("I suggest this because fractional equations gave you difficulty").
  • Variety: a diversity parameter in the choice function avoids always proposing the same type of exercise.
  • Curriculum constraints: the prerequisite graph delimits what the model can choose.
  • Teacher control: the teacher can replace a proposal and sees how the class is progressing.

The four rules have a common root: the model estimates, the person decides. Explainability lets the student trust, the curriculum constraint lets the teacher answer for what was proposed, variety keeps the student from being locked into a narrow path, and teacher control is the safety net when the first three are not enough. If you must give up only one thing to meet the deadline, give up a more sophisticated model, not one of these.

What you can do now

You can explain what IRT, BKT and DKT estimate and when to choose one or the other, you can read a BKT trace line by line and recognize parameters that make the model unusable. You can evaluate a model with AUC and calibration, notice a drift, and assign students to an experiment without making them change path. The next step is to bring these estimates inside a conversational tutor: you will find it in Personalized Tutoring with LLMs and RAG. To use the student's state also as motivation, see Gamification Engine.

Frequently asked questions

Which is better: IRT, BKT or DKT?

It depends on what you need. IRT gives a level and lets you choose the most informative exercise; BKT follows a skill over time and can be explained to a teacher; DKT may predict better but is harder to interpret. A study following DKT argues that an extended BKT reaches indistinguishable performance.

How much data does it take to calibrate an adaptive model?

There is no number valid for everyone: it depends on the model and on the quality of the data. This article gives none because none was measured. The method is to compare the stability of the parameters across subsets of students, and to distrust parameters that change a lot from one sample to another.

How do you tell that an adaptive model no longer works?

With calibration, in addition to AUC: group the predictions into bands and compare the predicted probability with the observed frequency. In this article's listing a cohort with more lucky guesses leaves the AUC at 0.736 but moves the 0.2-0.4 band from 0.32 predicted to 0.48 observed.

Next in the series: Video Streaming for Education: WebRTC vs HLS vs DASH.

Sources

The four Python listings were run with Python 3 (python3 -I irt.py, python3 -I bkt.py, python3 metrics.py, python3 -I ab.py) and the outputs are the real ones. The data in the metrics listing are synthetic. DKT has no listing: it requires a deep learning framework not available in the verification environment. The Khan Math and ASSISTments AUCs are stated by the authors of the original article, not measured here.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects