Welcome to the reference implementation for Where the Wild Features Are! If you're just getting started, we recommend reading the problem description and about page first.
In this challenge, you'll predict each kindergartener's end-of-year reading score from their beginning-of-year literacy screener: the audio of their responses, plus how they scored. The competition has two phases. In Phase 1, you'll build a model and submit predictions to the leaderboard. In Phase 2, the top 15 teams will be invited to submit a write-up explaining their approach and which features of the children's speech carry signal beyond the screening scores.
This post will:
- Load and explore the data
- Build two simple models: one that uses only the screening scores and student metadata, and one that also uses a children's speech model to measure how each child's answers sound
- Make a submission for each
This post walks through a basic approach to the central question of this challenge: which features of a child's speech tell us something about their end-of-year reading that the screening scores don't?
Background¶
The data in this challenge come from the Reach Every Reader screener, which kindergarteners took at the start of the school year. A trained adult gave each task on a tablet and scored each response right or wrong. There are three tasks:
- Blending: combine a word's separate sounds and say the word
- Deletion: say a word with part of it removed
- Sentence repetition: repeat a sentence word for word
Each student was tested on a task until they stopped answering correctly, so the number of clips varies by student. Along with item scores (right or wrong for each clip), each student has a task-level ability estimate called a theta. We'll refer to the item scores and thetas together as the screening scores.
The target is each child's end-of-year score on a standardized letter-word reading assessment. Students took one of two assessments, KTEA-3 or WJ IV, and their scores are pooled into a single target.
A right-or-wrong score says whether a child got the answer, but not how they said it. That's where the audio comes in. A few things to keep in mind:
- The clips can include background noise, the voice of the adult giving the test, or no child speech at all.
- To protect the children's privacy, every clip was denoised and then anonymized with voice conversion, which replaces the voices in a clip with one of about 50 target child voices. This keeps much of what was said, but it can introduce distortions.
Prizes are decided by judged write-ups, not by leaderboard rank, so as you build, keep track of which features help and why.
Step 0: Set up¶
We'll use a few standard data science packages, plus PyTorch and Hugging Face Transformers to run a speech model on the audio, and eng_to_ipa to look up how words are pronounced. With uv, you can install everything with:
uv pip install eng-to-ipa matplotlib numpy pandas scikit-learn soundfile torch tqdm transformers
import difflib
from pathlib import Path
import tarfile
import eng_to_ipa
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.linear_model import RidgeCV
from sklearn.model_selection import RepeatedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import soundfile as sf
import torch
from tqdm.auto import tqdm
from transformers import AutoProcessor, WavLMForCTC
Step 1: Load and explore the data¶
If you're setting up a project from scratch, we recommend Cookiecutter Data Science for a project structure that's easy to navigate.
Download all of the files on the data download page. We keep the downloads untouched in raw, write anything derived from them (like extracted audio and cached transcriptions) to interim, and save submissions to final:
data/reference_implementation
├── raw
│ ├── submission_format.csv
│ ├── test_audio.tar
│ ├── test_clip_metadata.csv
│ ├── test_student_metadata.csv
│ ├── train_audio.tar
│ ├── train_clip_metadata.csv
│ ├── train_labels.csv
│ └── train_student_metadata.csv
├── interim
└── final
# files from the data download page
DATA_DIR = Path("../data/reference_implementation/raw")
# extracted audio and cached transcriptions
INTERIM_DIR = Path("../data/reference_implementation/interim")
# submissions
FINAL_DIR = Path("../data/reference_implementation/final")
for directory in [INTERIM_DIR, FINAL_DIR]:
directory.mkdir(parents=True, exist_ok=True)
TASKS = ["blending", "deletion", "sentence_repetition"]
SEED = 42
The audio comes as two tar archives, one per split. Extracting them gives train_audio/ and test_audio/ folders with one .flac file per clip.
# extract each split's audio once; each archive holds a train_audio/ or test_audio/ folder
for split in ["train", "test"]:
if not (INTERIM_DIR / f"{split}_audio").exists():
with tarfile.open(DATA_DIR / f"{split}_audio.tar") as tar:
tar.extractall(INTERIM_DIR, filter="data")
The metadata¶
The training data has three tables: train_clip_metadata.csv has one row per audio clip, and train_student_metadata.csv and train_labels.csv have one row per student. They link through subject_id, a unique student identifier. See the problem description for more details.
The test tables have the same columns, except score_status and school_id, so our models don't use those two.
train_clips = pd.read_csv(DATA_DIR / "train_clip_metadata.csv")
train_students = pd.read_csv(
DATA_DIR / "train_student_metadata.csv", index_col="subject_id"
)
train_labels = pd.read_csv(DATA_DIR / "train_labels.csv", index_col="subject_id")
test_clips = pd.read_csv(DATA_DIR / "test_clip_metadata.csv")
test_students = pd.read_csv(
DATA_DIR / "test_student_metadata.csv", index_col="subject_id"
)
submission_format = pd.read_csv(
DATA_DIR / "submission_format.csv", index_col="subject_id"
)
print(f"train: {len(train_students):,} students, {len(train_clips):,} clips")
print(f"test: {len(test_students):,} students, {len(test_clips):,} clips")
We have 541 students in the training set and 361 in the test set, with about 25,000 clips between them. That's a small number of students, which will shape how we validate our models.
Here's the first row of each training table:
train_clips.head(1).T
train_students.head(1).T
train_labels.head(1).T
Let's make sure every clip in the metadata has an audio file.
for split, clips in [("train", train_clips), ("test", test_clips)]:
audio_dir = INTERIM_DIR / f"{split}_audio"
has_file = clips.filename.map(lambda f: (audio_dir / f).exists())
assert has_file.all(), f"{(~has_file).sum()} {split} clips have no audio file"
How many clips does each student have?¶
clips_per_task = train_clips.groupby(["subject_id", "task"]).size().unstack("task")
print(f"{len(train_students)} training students")
clips_per_task.count().rename("students with clips")
Not every student took every task: 521 of the 541 training students have blending clips, 515 have sentence repetition, and 334 have deletion.
fig, axes = plt.subplots(1, 3, figsize=(12, 3), sharey=True)
bins = range(0, int(clips_per_task.max().max()) + 2)
for ax, task in zip(axes, TASKS):
ax.hist(clips_per_task[task].dropna(), bins=bins)
ax.set_title(task)
ax.set_xlabel("clips per student")
axes[0].set_ylabel("students")
fig.suptitle("Clips per student, by task")
plt.tight_layout()
Most students have about 7 to 15 clips per task, but blending has a long tail, up to 47. A student with more clips likely kept answering correctly for longer.
What does the target look like?¶
outcomes = train_labels.join(train_students.instrument)
fig, ax = plt.subplots(figsize=(6, 3))
for instrument, scores in outcomes.groupby("instrument").outcome_score:
ax.hist(scores, bins=range(40, 161, 4), alpha=0.6, label=instrument)
ax.set_xlabel("end-of-year outcome score")
ax.set_ylabel("students")
ax.set_title("End-of-year scores, by assessment")
ax.legend(title="instrument")
outcomes.groupby("instrument").outcome_score.describe().round(1)
Both assessments give standard scores centered near 100, with similar averages (about 99 for KTEA-3 and 97 for WJ IV). WJ IV scores reach lower (a minimum of 64 vs 74), and KTEA-3 scores are a bit more spread out. We give the models instrument as a feature so they can account for differences like these.
Step 2: Build the models¶
We'll build two models and compare them on the same validation folds:
- Metadata-only model: the screening scores and student metadata, with no audio
- Audio + metadata model: the same features, plus one audio feature per task: how close a child's answers sound to the expected pronunciation
If the audio + metadata model scores better, the audio is telling us something the screening scores don't.
The metadata-only model¶
The thetas and student metadata are already one row per student, so we just summarize the clip metadata for each task:
pct_correct: the share of scored items the student got rightn_clips: how many clips the student has, which may track how far they got before they stopped answering correctlymean_duration: the average clip length
We also turn instrument and original_sample_rate into 0/1 flags.
def metadata_features(clips, students):
"""One row per student: task thetas, per-task item score summaries, and metadata."""
per_task = (
clips.groupby(["subject_id", "task"])
.agg(
pct_correct=("item_score", "mean"),
n_clips=("filename", "size"),
mean_duration=("duration_sec", "mean"),
)
.unstack("task")
)
per_task.columns = [f"{task}_{stat}" for stat, task in per_task.columns]
features = students[[f"{task}_theta" for task in TASKS]].join(per_task)
# a task the student didn't take has no clips
counts = [f"{task}_n_clips" for task in TASKS]
features[counts] = features[counts].fillna(0)
features["is_wj4"] = (students.instrument == "wj4").astype(int)
features["is_11khz"] = (students.original_sample_rate == 11025).astype(int)
return features
X_train_metadata = metadata_features(train_clips, train_students)
y_train = train_labels.loc[X_train_metadata.index, "outcome_score"]
X_train_metadata.head()
We use ridge regression, a linear model with a penalty that shrinks its weights toward zero. Many of our features overlap (a task's theta and its percent correct measure much the same thing), and the penalty helps keep the model from overfitting. scikit-learn's RidgeCV picks the penalty strength with its own internal cross-validation.
The pipeline has two steps before the regression:
SimpleImputerfills in missing values, like a task the student didn't take, with the median.add_indicator=Trueadds a 0/1 column flagging what was missing.StandardScalerputs every feature on the same scale, so the penalty treats them equally.
def make_model():
"""Median imputation with missing flags, then standardized ridge regression."""
return make_pipeline(
SimpleImputer(strategy="median", add_indicator=True),
StandardScaler(),
RidgeCV(alphas=np.logspace(-2, 5, 50)),
)
To validate, we use 5-fold cross-validation repeated 10 times. A single split gives a noisy score; averaging over 50 folds gives a steadier estimate and shows how much the score varies.
We score with R², the competition metric. An R² of 0 is what you'd get by always predicting the average score, and 1 is perfect.
# both models use these exact folds, so we can compare them fold by fold
cv = RepeatedKFold(n_splits=5, n_repeats=10, random_state=SEED)
folds = list(cv.split(X_train_metadata))
scores_metadata = cross_val_score(
make_model(), X_train_metadata, y_train, cv=folds, scoring="r2"
)
print(
f"Metadata-only model R²: {scores_metadata.mean():.3f} ± {scores_metadata.std():.3f}"
)
The metadata-only model explains a bit under a fifth of the variation in end-of-year scores. R² also varies by about ±0.04 from fold to fold, depending only on which students land in the validation set.
The audio + metadata model¶
Our idea: how a child says an answer may tell us something beyond whether they got it right.
To measure that, we use pasketti-phonetic, one of the Pasketti children's speech models, which transcribes children's speech into phones, the individual sounds of speech. For each item, we look up how the expected text is pronounced in a dictionary, and calculate the edit distance from each child's transcription.
We load the full model, including its phone-prediction head, and read its output with the tokenizer's standard decoding. Each clip's transcription is cached to its own text file, so if the run stops partway, rerunning picks up where it left off.
MODEL_ID = "drivendata/pasketti-phonetic"
if torch.backends.mps.is_available():
DEVICE = "mps"
elif torch.cuda.is_available():
DEVICE = "cuda"
else:
DEVICE = "cpu"
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = WavLMForCTC.from_pretrained(MODEL_ID).to(DEVICE).eval()
def transcribe_clip(path):
"""The model's phonetic transcription of one clip."""
audio, sample_rate = sf.read(path, dtype="float32")
inputs = processor(audio, sampling_rate=sample_rate, return_tensors="pt")
with torch.no_grad():
logits = model(inputs.input_values.to(DEVICE)).logits[0]
# the most likely token for each 20 ms frame, decoded into phones
return " ".join(processor.decode(logits.argmax(dim=-1).cpu()).split())
def clip_transcriptions(clips, audio_dir, cache_dir):
"""One transcription per clip, cached one text file per clip so reruns skip finished
clips."""
cache_dir.mkdir(parents=True, exist_ok=True)
for filename in tqdm(clips.filename):
cache_path = cache_dir / f"{Path(filename).stem}.txt"
if not cache_path.exists():
cache_path.write_text(transcribe_clip(audio_dir / filename))
texts = [(cache_dir / f"{Path(f).stem}.txt").read_text() for f in clips.filename]
return pd.Series(texts, index=clips.filename)
TRANSCRIPTION_DIR = INTERIM_DIR / "transcriptions"
train_transcriptions = clip_transcriptions(
train_clips, INTERIM_DIR / "train_audio", TRANSCRIPTION_DIR / "train"
)
test_transcriptions = clip_transcriptions(
test_clips, INTERIM_DIR / "test_audio", TRANSCRIPTION_DIR / "test"
)
# a few answers next to the expected answer
(
train_clips.assign(transcription=train_clips.filename.map(train_transcriptions))[
["expected_text", "item_score", "transcription"]
].head()
)
To build each item's reference, we look up the expected text in the CMU Pronouncing Dictionary with eng_to_ipa, which converts the text to phonetic symbols like the ones the speech model outputs. We drop the dictionary's stress marks and punctuation, which the speech model never outputs. However, the two still write some sounds with different IPA symbols, and we didn't try to align those for this post. Any word that isn't in the dictionary stays spelled out rather than phonetically transcribed.
items = pd.concat([train_clips, test_clips]).expected_text.unique()
refs = {
item: eng_to_ipa.convert(item, stress_marks=False, keep_punct=False) for item in items
}
# one example item per task
examples = train_clips.drop_duplicates("task")[["task", "expected_text"]]
examples.assign(reference=examples.expected_text.map(refs))
We compare each transcription with its reference as plain strings of characters using difflib. difflib finds the longest runs of characters the two strings share and scores their similarity as twice the number of matching characters divided by the total length of both. The distance is one minus that score: 0 for identical strings and 1 for strings with nothing in common.
As a sanity check, correct answers should sound closer to the reference than incorrect ones. Here's the median distance for each task, split by how the answer was scored:
def distance(a, b):
"""0 when two transcriptions match, up to 1 when they have nothing in common."""
a, b = a.replace(" ", ""), b.replace(" ", "")
return 1 - difflib.SequenceMatcher(None, a, b, autojunk=False).ratio()
def clip_distances(clips, transcriptions):
"""Each scored, non-empty answer's distance from its item's reference."""
scored = clips[clips.item_score.notna()].copy()
scored["transcription"] = scored.filename.map(transcriptions)
scored = scored[scored.transcription != ""]
scored["distance"] = [
distance(text, refs[item])
for text, item in zip(scored.transcription, scored.expected_text)
]
return scored
train_scored = clip_distances(train_clips, train_transcriptions)
(
train_scored.assign(
answer=train_scored.item_score.map({1.0: "correct", 0.0: "incorrect"})
)
.groupby(["task", "answer"])
.distance.median()
.unstack()
.round(2)
)
In every task, correct answers sit closer to the reference. For sentence repetition, for example, the median distance is 0.39 for correct answers vs 0.62 for incorrect ones. So the distance does pick up whether a child said the expected sounds.
For the audio + metadata model, each student gets one new column per task: their average distance over their scored answers. Otherwise it's the same make_model() pipeline as the metadata-only model, so a student with no usable answers in a task gets the median, plus a flag.
def student_distances(clips, transcriptions):
"""Each student's average distance in each task, one column per task."""
return (
clip_distances(clips, transcriptions)
.groupby(["subject_id", "task"])
.distance.mean()
.unstack("task")
.reindex(columns=TASKS)
.add_suffix("_distance")
)
X_train_audio = X_train_metadata.join(
student_distances(train_clips, train_transcriptions)
)
X_train_audio.filter(like="_distance").head()
Now we score the audio + metadata model on the same 50 folds and compare it with the metadata-only model fold by fold.
scores_audio = cross_val_score(
make_model(), X_train_audio, y_train, cv=folds, scoring="r2"
)
gain = scores_audio - scores_metadata
pd.DataFrame(
{
"mean R²": [scores_metadata.mean(), scores_audio.mean(), gain.mean()],
"sd": [scores_metadata.std(), scores_audio.std(), gain.std()],
},
index=["Metadata-only model", "Audio + metadata model", "Difference (same folds)"],
).round(3)
print(
"The audio + metadata model beats the metadata-only model in "
f"{(gain > 0).mean():.0%} of folds"
)
Adding the distances has little impact on the model. The audio + metadata model scores 0.193, the same as the metadata-only model, and does better in only about half (52%) of the 50 folds.
Does any single task's audio help?¶
We add one task's distance at a time to the metadata-only model and compare on the same folds.
gain_by_task = {}
for task in TASKS:
X = X_train_metadata.join(X_train_audio[f"{task}_distance"])
scores = cross_val_score(make_model(), X, y_train, cv=folds, scoring="r2")
gain_by_task[task] = scores - scores_metadata
pd.DataFrame(
{
"mean R² gain": {task: g.mean() for task, g in gain_by_task.items()},
"sd": {task: g.std() for task, g in gain_by_task.items()},
"share of folds improved": {
task: (g > 0).mean() for task, g in gain_by_task.items()
},
}
).round(3)
Each task's distance on its own improves 54% to 60% of folds, and sentence repetition varies the least from fold to fold, but no single task stands out.
What this does and doesn't tell us¶
The distance picks up something real about how a child answered: correct answers sound closer to the reference than incorrect ones. But on top of the screening scores, it doesn't seem to help our model much in this simple form. A few possible reasons:
- Much of it overlaps with the screening scores. A child whose answers sound closer to the expected pronunciation also tends to get more items right, which the metadata-only model already knows.
- The transcriptions are noisy. Clips can include the adult's voice, background noise and silence, and voice conversion changes the audio, so some of the distance reflects the recording rather than the child.
- Small sample sizes are challenging. With 541 students and a handful of answers per child per task, a subtle effect is hard to see.
How closely a child's answers match the expected pronunciation is easy to explain, and better ways of isolating the child's response, comparing sounds, and pooling results could improve the model.
Ideas to try¶
We used one simple measure per task, in a linear model. That's just the tip of the iceberg. A few directions you might explore:
- Isolate the child's response with voice activity detection or speaker diarization.
- Penalize similar sounds less when comparing transcriptions.
- Use the model's confidence in each sound instead of only its best guess.
- Try the speech model's embeddings instead of its transcriptions.
- Build named features like speaking rate and pause length.
Step 3: Make your submission¶
We build the test features the same way as the training features, then line them up with submission_format.csv, which has one row per test student in the order the platform expects.
X_test_metadata = metadata_features(test_clips, test_students)
X_test_audio = X_test_metadata.join(student_distances(test_clips, test_transcriptions))
# one row per test student, in submission format order, with the training columns
X_test_metadata = X_test_metadata.reindex(submission_format.index)[
X_train_metadata.columns
]
X_test_audio = X_test_audio.reindex(submission_format.index)[X_train_audio.columns]
For each model, we fit on all of the training data, predict the test set, check the format, and save a CSV.
def make_submission(model, X_train, X_test, path):
"""Fit on all of train, predict test, check the format, and save."""
model.fit(X_train, y_train)
submission = submission_format.copy()
submission["outcome_score"] = model.predict(X_test)
assert submission.index.equals(submission_format.index)
assert submission.outcome_score.notna().all()
submission.to_csv(path)
return submission
submission_metadata = make_submission(
make_model(), X_train_metadata, X_test_metadata, FINAL_DIR / "submission_metadata.csv"
)
submission_audio = make_submission(
make_model(), X_train_audio, X_test_audio, FINAL_DIR / "submission_audio.csv"
)
Here's what the files look like:
pd.read_csv(FINAL_DIR / "submission_audio.csv").head()
pd.read_csv(FINAL_DIR / "submission_metadata.csv").head()
Before you upload, check your file against the submission format:
Do:
- Include exactly one row for every student in
submission_format.csv, in the same order - Keep the same two columns,
subject_idandoutcome_score - Make sure every prediction is numeric, with no missing values
Don't:
- Add or drop rows, or change the student IDs
- Use the test data to train your model, including through pseudo-labeling
To submit, click "Submit" in the sidebar of the competition page, then "Make new submission," and upload your CSV. You can make up to 3 submissions per day.
We submitted both files.
The metadata-only model scored 0.2888 on the public leaderboard.
The audio + metadata model scored 0.3003, slightly higher than the metadata-only model.
Good luck!¶
That's it! You now have a working pipeline from the raw downloads to a scored submission, and a first look at the question this challenge is asking. There's a lot in these recordings to explore, and we're excited to see what you find.
If you have questions or want to share what you're finding, head over to the competition forum. Good luck!