Skip to content
v0.1.4latest release159 skills5 categories7 sub-categories303 tested scripts468 reference docsContact us

item_analysis.py

Helper script for language-placement-test-builder · 101 lines

Languages, Linguistics & Translation / Language Teachingv1.0.0Updated OCT 25 20262 references2 scripts
scripts/item_analysis.py
#!/usr/bin/env python3
"""Classical item analysis for a multiple-choice language test: facility, discrimination, distractors, KR-20.

CSV: first column student id, then one column per item with the option chosen (A, B, C, D; blank = no answer).
One row with id KEY holds the correct options; an optional row with id LEVEL tags items with a CEFR level, so
the script can spot items that are easier than items at a lower level (useful for placement tests).

Checks:
  IA001 high    negative discrimination: weaker students do better (miskeyed or ambiguous item)
  IA002 medium  discrimination below 0.20
  IA003 medium  facility above 0.90 or below 0.20 (item tells you little)
  IA004 low     distractor chosen by under 5% (not working) or chosen more by the top group than the bottom group
  IA005 low     item tagged at a level is easier than the average item one level below

Discrimination = facility in the top 27% minus facility in the bottom 27% (by total score).

Usage:
    python item_analysis.py responses.csv

Exit codes: 0 no high findings, 1 high findings, 2 read error or no KEY row.
"""

import argparse
import csv
import sys

LEVELS = ["A1", "A2", "B1", "B2", "C1", "C2"]


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("csv")
    a = ap.parse_args()
    try:
        with open(a.csv, newline="", encoding="utf-8-sig") as fh:
            rows = [r for r in csv.reader(fh) if r]
        head, body = rows[0], rows[1:]
        key = next(r for r in body if r[0].strip().upper() == "KEY")
    except (OSError, csv.Error, IndexError, StopIteration):
        print("error: need a header row, a KEY row and student rows", file=sys.stderr)
        return 2
    tags = next((r for r in body if r[0].strip().upper() == "LEVEL"), None)
    students = [r for r in body if r[0].strip().upper() not in ("KEY", "LEVEL")]
    items = head[1:]
    if len(students) < 10:
        print(f"note: {len(students)} students; statistics are unstable below about 30", file=sys.stderr)
    ans = [[(r[i + 1].strip().upper() if i + 1 < len(r) else "") for i in range(len(items))] for r in students]
    correct = [[int(x == key[i + 1].strip().upper()) for i, x in enumerate(s)] for s in ans]
    totals = [sum(c) for c in correct]
    order = sorted(range(len(students)), key=lambda i: totals[i])
    g = max(1, round(0.27 * len(students)))
    low, high = order[:g], order[-g:]
    n, k = len(students), len(items)
    f, fac = [], {}
    print("| Item | Key | Facility | Discrimination | Options (% chosen) |\n|------|-----|----------|----------------|--------------------|")
    for i, item in enumerate(items):
        p = sum(c[i] for c in correct) / n
        d = sum(correct[j][i] for j in high) / g - sum(correct[j][i] for j in low) / g
        fac[item] = p
        opts = sorted({x for s in ans for x in [s[i]] if x})
        share = {o: sum(s[i] == o for s in ans) / n for o in opts}
        print(f"| {item} | {key[i + 1]} | {p:.2f} | {d:+.2f} | " + " ".join(f"{o}:{100 * share[o]:.0f}" for o in opts) + " |")
        if d < 0:
            f.append(("IA001", "high", f"{item}: discrimination {d:+.2f}; check the key and look for two right answers"))
        elif d < 0.2:
            f.append(("IA002", "medium", f"{item}: discrimination {d:.2f} is weak"))
        if p > 0.9 or p < 0.2:
            f.append(("IA003", "medium", f"{item}: facility {p:.2f} ({'too easy' if p > 0.9 else 'too hard'})"))
        for o in opts:
            if o == key[i + 1].strip().upper():
                continue
            if share[o] < 0.05:
                f.append(("IA004", "low", f"{item}: distractor {o} chosen by {100 * share[o]:.0f}%; replace it"))
            elif sum(ans[j][i] == o for j in high) > sum(ans[j][i] == o for j in low):
                f.append(("IA004", "low", f"{item}: distractor {o} attracts the top group more than the bottom group"))
    var = sum((t - sum(totals) / n) ** 2 for t in totals) / n
    pq = sum(fac[it] * (1 - fac[it]) for it in items)
    kr20 = k / (k - 1) * (1 - pq / var) if var and k > 1 else 0
    if tags:
        by = {}
        for i, item in enumerate(items):
            lvl = tags[i + 1].strip().upper() if i + 1 < len(tags) else ""
            if lvl in LEVELS:
                by.setdefault(lvl, []).append(item)
        for lvl, its in by.items():
            below = LEVELS[LEVELS.index(lvl) - 1] if LEVELS.index(lvl) else None
            if below in by:
                mean_below = sum(fac[x] for x in by[below]) / len(by[below])
                for it in its:
                    if fac[it] > mean_below:
                        f.append(("IA005", "low", f"{it} ({lvl}) facility {fac[it]:.2f} is above the {below} mean {mean_below:.2f}"))
    print(f"\n{n} students, {k} items, mean {sum(totals) / n:.1f}, KR-20 reliability {kr20:.2f}")
    sev = {"high": 0, "medium": 1, "low": 2}
    for code, s, msg in sorted(f, key=lambda x: (sev[x[1]], x[0])):
        print(f"{code} [{s}] {msg}")
    return 1 if any(x[1] == "high" for x in f) else 0


if __name__ == "__main__":
    sys.exit(main())
More in Language Teaching

academic-english-eap-course-planner

Plan English for Academic Purposes (EAP) courses: pre-sessional, in-sessional, foundation, IELTS preparation and discipline-specific EAP, with syllabus strands (academic reading, lecture listening and note-taking, essay and report writing, paraphrase, summary and synthesis, referencing and plagiarism, seminars and presentations, academic vocabulary, critical thinking), a 10-week pre-sessional outline, exit assessment, IELTS-CEFR alignment and academic style (formality, hedging, cohesion, reporting verbs). Estimates study hours and weeks to close an IELTS gap from overall or per-skill scores (IELTS rounding, minimum per skill, priority skills, feasibility before a deadline), and checks learner texts for contractions, informal words with academic alternatives, unhedged claims, 'you', And/But/So starts, rhetorical questions and missing citations.

actfl-proficiency-curriculum-mapper

Map world language curricula to the ACTFL framework: proficiency levels (Novice, Intermediate, Advanced, Superior, Distinguished with sublevels), functions, contexts, text types and accuracy, proficiency vs performance, the three modes of communication (interpretive, interpersonal, presentational), the 5 Cs World-Readiness Standards, backward-designed thematic units with Integrated Performance Assessments, typical programme targets and FSI time estimates. Looks up approximate ACTFL-CEFR-ILR equivalences with what each level can do, and checks a unit map for missing modes, rehearsed skits mislabelled as interpersonal, translation or word lists as interpretive tasks, and units without an integrated performance assessment.

adult-literacy-esl-lesson-builder

Build lessons for adult ESL learners who are developing literacy (LESLLA learners: pre-literate, non-literate, semi-literate, literate in a non-Roman script): learner profiles and sensitive initial assessment, principles (oral language first, known to new, systematic phonics with adult-relevant text, repetition, classroom skills, respect for experience), a lesson routine (oral warm-up, review, new grapheme, blending, segmenting, decodable text, writing, functional literacy, Language Experience Approach), a phonics sequence for adults, sight words, functional literacy targets (forms, signs, medicine labels) and portfolio assessment. Checks whether a reading text is decodable with the letter-sound patterns and sight words taught so far, catching untaught digraphs, listing non-decodable words with the untaught part, and suggesting the most useful next patterns.

authentic-material-lesson-adapter

Turn authentic material (news articles, podcasts, videos, songs, menus, timetables, adverts, social media posts, forms, infographics) into language lessons by grading the task rather than the text. Selects texts for interest, relevance, exploitability, coverage, cultural load and rights; finds the 4-6 words to pre-teach, words to gloss on the page and words learners can ignore, plus names and cultural references to explain, with reading time by level; and builds a lesson shape (lead-in, pre-teach, gist or scanning, graded detail task, language focus on chunks and register, response) with task ideas per material type and level from A1 to C1. Covers copyright, fair dealing and fair use, Creative Commons and attribution.

can-do-statement-writer

Write and review can-do statements for language courses, units, lessons and learner self-assessment, CEFR or NCSSFL-ACTFL style: action (observable verb) + text or situation + level-specific conditions, learner ('I can') and descriptor ('Can') versions, progressions of one activity from A1 to C1, and coverage of reception, production, interaction and mediation. Includes a verb bank by mode and level and condition and text-type banks. Lints statements for teacher-centred phrasing, knowledge instead of use (learn, know, understand the passive), missing context, two skills in one statement, vague quality words, grammar items as outcomes, overlong statements and missing modes in a set.

cefr-aligned-syllabus-builder

Build language course syllabuses aligned to the CEFR (A1-C2, plus levels, Companion Volume 2020): entry and exit levels, guided learning hours and course length (with an L1-distance adjustment), syllabus type (topic, functional-notional, task-based, skills-based, multi-strand), unit-by-unit can-do outcomes, grammar from a core inventory by level, vocabulary, functions, pronunciation, balance of reception, production, interaction and mediation, recycling and assessment points. Checks a syllabus for units without can-do statements, core grammar for the level not covered, items above the course level, skills missing from most units and units with no vocabulary or functions.