Training and evaluation¶
Training fine-tunes one of the two released classifiers on annotated or corpus-derived records. Evaluation scores a human spot-check against a model answer key, or compares two model runs on the same corpus.
Data contracts¶
Training input is JSONL, one record per line, with the task’s canonical text column and an integer label:
Task |
Text column |
Label |
|---|---|---|
|
|
|
|
|
integer |
Annotation exports and corpus records are more flexible; use
cc4q.train.normalize_training_records() to convert them first.
Training¶
- cc4q.train.normalize_training_records(rows, task)[source]¶
Convert flexible annotation/corpus rows into canonical training dicts.
Accepts rows with
comment/text/comment_textand label fields inlabel/human_label/quantum_related/quantum_category(including the human_* variants written by the annotation UI). Rows without usable text or a valid label are skipped.- Parameters:
rows – Iterable of mappings (annotation exports, corpus records, …).
task –
"quantum_related"(2 classes) or"quantum_category"(6 classes).
- Returns:
A list of
{text_col: str, "label": int}records, wheretext_colis"comment"for Task 1 and"text"for Task 2.- Raises:
ValueError – If
taskis unknown, or no valid rows remain.
- cc4q.train.resolve_base_model(base_model, task)[source]¶
Resolve model aliases and local caches to a loadable model path.
base_model="released"(or"cc4q-released"/"released-checkpoint") means “warm-start from the released CC4Q classifier for this task”. If that checkpoint is not present locally, the function falls back tobert-base-uncased.base_model="bert-base-uncased"resolves to the locally cached copy when one was fetched viacc4q download-models --with-base(or baked into the Docker image), so cold-start fine-tuning also works offline; otherwise the Hugging Face id is returned andtransformersdownloads the weights on first use.- Parameters:
base_model – Hugging Face model id/path, or a released alias.
task – Axis name whose released checkpoint should be used.
- Returns:
A model id/path accepted by
transformers.
- cc4q.train.train(task, data, output_dir, base_model='bert-base-uncased', batch_size=32, epochs=30, learning_rate=2e-5, max_length=256, test_size=0.2, val_size=0.1, seed=42, max_samples=None, callbacks=None)[source]¶
Fine-tune one CC4Q classifier.
The input is a JSONL file that already honors the task’s data contract:
comment+ intlabelforquantum_related, ortext+ intlabelforquantum_category. Usenormalize_training_records()to convert annotation/corpus exports first. The data is split into train/validation/test sets; the checkpoint with the best validation F1 is restored before the final test evaluation.- Parameters:
task –
"quantum_related"(2 classes) or"quantum_category"(6 classes).data – Path to a JSONL training file.
output_dir – Directory for the fine-tuned model and tokenizer.
base_model – Hugging Face model id/path, or
"released"to warm-start from the released checkpoint.batch_size – Per-device train/eval batch size.
epochs – Number of training epochs.
learning_rate – Optimizer learning rate.
max_length – Tokenizer truncation length.
test_size – Fraction held out for the final test split.
val_size – Fraction of the remaining data used for validation.
seed – Random seed for splitting and training.
max_samples – Optional cap on the number of training records.
callbacks – Optional list of Hugging Face
TrainerCallbackinstances (the Workbench uses this for live progress).
- Returns:
A dict with
trainer,test_results(eval_*metrics on the test split),output_dir, andtrain_rows/val_rows/test_rowscounts.- Raises:
ValueError – If
taskis unknown or the data file violates the contract.
Example¶
from cc4q.train import normalize_training_records, train
rows = [{"comment_text": r["comment_text"],
"human_label": r["label"]} for r in annotated]
normalized = normalize_training_records(rows, "quantum_related")
# write normalized to JSONL, then:
result = train("quantum_related", "train.jsonl", "out/qr",
base_model="released", epochs=10)
print(result["test_results"])
Evaluation¶
- cc4q.evaluate.evaluate(human_labels, model_labels)[source]¶
Compare aligned human and model labels.
- Parameters:
human_labels – A sequence of labels, or a mapping
id -> label.model_labels – A sequence aligned with
human_labels, or a mappingid -> label(only shared ids are compared).
- Returns:
A dict with
n,agreement,kappa,precision,recall,f1,wilson95((low, high)),confusion(tp/fp/fn/tn),labels, and the rawpairs. The positive class is"quantum"when present, otherwise the first sorted label. Metrics arenanwhen undefined.
- cc4q.evaluate.evaluate_files(csv_path=None, jsonl_path=None, key_path=None, id_join='no', contaminated=None, human_values=('quantum', 'non-quantum'))[source]¶
Evaluate a human spot-check export against a model answer key.
The annotation file needs a human label column (
human_labelby default), a join key (id_join), and optionallyrepo,comment_type,code_entity_type, andcomment_textfields. The key file is JSONL with the same join key and amodel_label(orlabel) field.- Parameters:
csv_path – Annotation CSV (preferred when it exists).
jsonl_path – Annotation JSONL, used when
csv_pathis absent.key_path – Model answer-key JSONL. Required.
id_join – Column used to join annotations and key (default
"no").contaminated – Optional iterable of ids to exclude (for example units that appeared in training data).
human_values – Accepted normalized human labels; other rows are counted as
skipped.
- Returns:
The
evaluate()result plusby_repo(per-repository metrics),disagreements,skipped, andexcludedcounts.- Raises:
ValueError – If
key_pathor an annotation path is missing, or the key is empty.
- cc4q.evaluate.cohen_kappa(pairs)[source]¶
Compute Cohen’s kappa over aligned label pairs.
- Parameters:
pairs – Iterable of
(label_a, label_b)pairs.- Returns:
Cohen’s kappa, or
nanfor no pairs and1.0when both raters used a single identical label (expected agreement is 1).
- cc4q.evaluate.wilson_ci(k, n, z=1.96)[source]¶
Wilson score confidence interval for a binomial proportion.
- Parameters:
k – Number of successes (agreements).
n – Number of trials.
z – Normal quantile;
1.96gives a 95% interval.
- Returns:
A
(low, high)pair. Forn == 0both bounds arenan.
Evaluation output¶
evaluate() returns n, agreement, kappa,
precision, recall, f1, wilson95, confusion (tp /
fp / fn / tn), labels, and the raw pairs.
evaluate_files() adds the same metrics per repository
under by_repo plus a disagreements list and skipped /
excluded counts.
from cc4q.evaluate import evaluate_files
result = evaluate_files(
csv_path="ann/annotations.csv",
key_path="out/key.jsonl",
id_join="no",
)
print(f"{100 * result['agreement']:.1f}% "
f"(95% CI {result['wilson95'][0]:.3f}-{result['wilson95'][1]:.3f})")