Python for AI: make an experiment inspectable
AI 中的 Python
Build a validated CSV-to-model-to-JSON experiment, isolate held-out data and record reproducible inputs.
python-aiA score needs a trail back to its inputs
A hypothetical museum workshop measures a device’s vibration as an integer reading. Technicians label each inspection: 1 means maintenance is needed; 0 means it is not. A short Python experiment reports a test error of 25%. Before trusting the number, another engineer asks: Which inspections were tested? Did their labels influence the rule? What happens if the CSV rows arrive in another order? Can the result be saved without losing its meaning?
Python is useful here because one program can connect file parsing, a numerical rule, checks and a readable artifact. The rule can be deliberately small. Our experiment chooses one threshold from three candidates and compares it with a constant prediction. The engineering work is to make every step inspectable.
Follow the data through four boundaries: text becomes validated records; training records become a fitted rule; untouched test records become a score; the entire run becomes JSON. A successful process exit only says execution finished. It does not establish that those boundaries were respected.
Give each function a contract
Text is not yet data
The CSV schema is exactly id,split,x,label. IDs identify records, split is either train or test, the reading is a bounded integer, and the label is 0 or 1. Both splits must be nonempty. A duplicate ID anywhere is an error, including one repeated across train and test. We do not silently remove a malformed record and then report a score on a different dataset.
The standard CSV reader handles quoted fields and returns strings under its ordinary settings. Schema and value checks remain the application’s job. Splitting each line at commas is not an equivalent parser. When reading a file, use UTF-8 explicitly and newline=''; here StringIO supplies the same text-stream boundary.
Row groups named values with a dataclass. Its annotations document the intended types; they do not validate constructor arguments. frozen=True blocks ordinary field reassignment, and all our fields contain strings or integers. This is a guard against accidental mutation, not a security boundary or a promise that every nested object in an arbitrary dataclass is immutable. See the dataclass contract.
A fitted object must depend on training information
Our candidate rule predicts maintenance when the reading reaches a threshold. For a nonempty, predetermined finite set of integer thresholds, minimize training mistakes and break a tie by the smaller threshold:
The argmin uses lexicographic order on the pair. The constant baseline predicts the training majority; a tie selects 0. Neither decision consults test labels. No preprocessing is learned in this example. If a later version learns imputation, scaling or feature selection, those fitted quantities must also come from training data, then be reused at prediction time. The scikit-learn leakage guide explains this separation and why a pipeline helps enforce it.
One useful test is an invariance, not another expected score. With configuration and training rows fixed, replacing valid held-out records must leave the fitted rule unchanged:
This notation describes the separation we require; the implementation never passes either test set into threshold selection. The test score and full-data fingerprint may change. A function can be deterministic and still leak data, so rerunning it twice is not a substitute for this check.
Preserve the denominator and the configuration
We report a confusion vector in the fixed order TN, FP, FN, TP. Rows are actual labels and columns are predictions. Error rate is then derived from integer counts:
A report saying “1 error in 4 records” retains information that a lone 0.25 conceals. It still provides only an observed test result, not a guarantee about future devices.
For provenance, the program sorts parsed records by ID and encodes them as JSON with specified key order, separators and ASCII escaping. It hashes those normalized bytes. CSV quoting, row order and alternate accepted integer spellings therefore do not change this fingerprint. Changing an actual record changes the bytes being hashed. The fit fingerprint covers only training records plus the algorithm version and canonical threshold set; the full-data fingerprint includes test records. These are fingerprints under this convention, not digital signatures or a proof of authentic labels. Keep the source file and source-code revision alongside a real experiment.
A complete experiment with only the standard library
Save the following as experiment.py and run python3.12 experiment.py. Its public entry point is run_csv(text, thresholds). It accepts a string and a nonempty list or tuple of integer thresholds, rejects Boolean thresholds, and returns a fresh JSON-compatible dictionary. Names beginning with _ mark internal helper interfaces; _parse receives and validates raw text.
IDs must match an ASCII letter followed by up to 31 letters, digits, underscores or hyphens. The CSV x field accepts an optional sign and one to seven decimal digits, with absolute value at most 1,000,000; labels must be exactly 0 or 1. Spaces are not silently stripped. Header order, field count, blank records, IDs, labels and split names are checked. A parsing or domain error raises ValueError; ordinary resource and I/O failures are not reclassified as data errors.
The fixture contains six training and four test inspections. Threshold equality predicts 1. Candidate duplicates and input order are discarded because configuration is defined as a set of thresholds.
import csv
from dataclasses import dataclass
from hashlib import sha256
import io
import json
import platform
import re
@dataclass(frozen=True)
class Row:
identity: str
split: str
x: int
label: int
VERSION = 'threshold-audit/1'
DEMO = '''id,split,x,label
a,train,0,0
b,train,1,0
c,train,3,0
d,train,5,1
e,train,7,1
f,train,8,1
g,test,2,0
h,test,4,1
i,test,6,0
j,test,9,1
'''
def _json(value):
return json.dumps(value, sort_keys=True, separators=(',', ':'),
ensure_ascii=True, allow_nan=False)
def _digest(value):
return sha256(_json(value).encode('utf-8')).hexdigest()
def _parse(text):
if type(text) is not str:
raise ValueError('CSV input must be text')
reader = csv.reader(io.StringIO(text, newline=''), strict=True)
rows, seen = [], set()
try:
if next(reader, None) != ['id', 'split', 'x', 'label']:
raise ValueError('expected header id,split,x,label')
for fields in reader:
if len(fields) != 4:
raise ValueError('every record needs four fields')
identity, split, x_text, label = fields
if re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,31}', identity) is None:
raise ValueError('invalid record ID')
if identity in seen:
raise ValueError('record IDs must be unique across both splits')
if split not in ('train', 'test') or label not in ('0', '1'):
raise ValueError('invalid split or label')
if re.fullmatch(r'[+-]?[0-9]{1,7}', x_text) is None:
raise ValueError('x must be a decimal integer')
x = int(x_text)
if abs(x) > 1_000_000:
raise ValueError('x is outside the teaching range')
seen.add(identity)
rows.append(Row(identity, split, x, int(label)))
if not any(r.split == 'train' for r in rows) or not any(r.split == 'test' for r in rows):
raise ValueError('both train and test must be nonempty')
except csv.Error as exc:
raise ValueError('malformed CSV') from exc
return tuple(sorted(rows, key=lambda r: r.identity))
def _metrics(rows, predict):
# Index is 2 * actual_label + predicted_label: TN, FP, FN, TP.
counts = [0, 0, 0, 0]
for row in rows:
counts[2 * row.label + predict(row.x)] += 1
return {'count': len(rows), 'confusion': counts,
'errors': counts[1] + counts[2]}
def run_csv(text, thresholds=(2, 4, 6)):
if type(thresholds) not in (list, tuple) or not thresholds:
raise ValueError('thresholds must be a nonempty list or tuple')
if any(type(t) is not int or abs(t) > 1_000_000 for t in thresholds):
raise ValueError('thresholds must be integers in the teaching range')
thresholds = tuple(sorted(set(thresholds)))
rows = _parse(text)
train = tuple(r for r in rows if r.split == 'train')
test = tuple(r for r in rows if r.split == 'test')
losses = [(sum(int(r.x >= t) != r.label for r in train), t)
for t in thresholds]
threshold = min(losses)[1]
majority = int(2 * sum(r.label for r in train) > len(train))
predict = lambda x: int(x >= threshold)
records = [[r.identity, r.split, r.x, r.label] for r in rows]
training = [row for row in records if row[1] == 'train']
configuration = {'version': VERSION, 'thresholds': list(thresholds)}
return {
'schema': 1, 'configuration': configuration,
'environment': {'implementation': platform.python_implementation(),
'python': platform.python_version()},
'data_sha256': _digest(records),
'fit_sha256': _digest({'configuration': configuration, 'train': training}),
'train_ids': [r.identity for r in train],
'test_ids': [r.identity for r in test],
'candidate_errors': [[t, errors] for errors, t in losses],
'model': {'threshold': threshold, 'baseline_label': majority},
'train': _metrics(train, predict), 'test': _metrics(test, predict),
'baseline_train': _metrics(train, lambda x: majority),
'baseline_test': _metrics(test, lambda x: majority),
}
if __name__ == '__main__':
report = run_csv(DEMO)
print('candidates', report['candidate_errors'])
print('model', report['model'])
print('train', report['train'])
print('test', report['test'])
print('baseline test', report['baseline_test'])
print('data sha256', report['data_sha256'])
print('fit sha256', report['fit_sha256'])
print('JSON round trip', json.loads(_json(report)) == report)
The output is:
candidates [[2, 1], [4, 0], [6, 1]]
model {'threshold': 4, 'baseline_label': 0}
train {'count': 6, 'confusion': [3, 0, 0, 3], 'errors': 0}
test {'count': 4, 'confusion': [1, 1, 0, 2], 'errors': 1}
baseline test {'count': 4, 'confusion': [2, 0, 2, 0], 'errors': 2}
data sha256 4a2eee47775972711683780c7d5ae0175bbd41da82f2140463919792932a07c1
fit sha256 501384826a6994a6b7a55a14b745bcb6080b10da463ae76a8de2b10c72f7002d
JSON round trip True
Threshold 4 makes no training mistakes. On the test set it incorrectly flags reading 6; readings 2, 4 and 9 are correct. The baseline chooses 0 from a tied training class count and misses the two positive test labels. That is why the two error counts are 1 and 2. The eight printed lines summarize the run; report also contains record IDs, all split metrics, canonical configuration and the actual Python implementation and patch version.
To persist the complete artifact, serialize report once with json.dumps(report, sort_keys=True, indent=2, allow_nan=False) and write the resulting text to a chosen UTF-8 file. JSON’s documented options make the formatting explicit; allow_nan=False rejects nonfinite floats if a future metric introduces one. Serialization preserves this report’s lists, string keys and integers. It does not preserve arbitrary Python classes, nor does successful loading validate a report against an application schema.
For cost analysis, let B be input text length, n the record count, M the supplied threshold count and m the number of distinct thresholds. IDs and numeric magnitudes are bounded here. Under unit-cost counters and expected constant-time set operations, parsing, sorting, training, metrics and serialization take:
The threshold scan is the product term. All data and normalized JSON are held in memory. The bound includes text storage and the report, not just the learner. It is an operation model, not a timing claim; arbitrarily large counters also have nonconstant bit cost.
A reproducible mistake is still a mistake
The split is supplied by the caller. Unique record IDs prevent one kind of overlap, but two different IDs might belong to the same physical device. For repeated measurements, choose groups or time boundaries before training according to the deployment question. The program cannot infer those relationships from a single integer feature.
The candidate list must be chosen without consulting the final test result. Editing thresholds until this four-record test looks good turns it into model-selection data. Use a separate validation procedure for that work; see overfitting. The experiment also lacks confidence intervals, cost-sensitive decisions and calibrated probabilities. A threshold classifier is an adequate executable baseline for this lesson, not a maintenance policy.
No random generator is used, so there is no seed to set. Reproducibility here comes from explicit input, tie rules and deterministic transformations. When adding random sampling, record the generator, its state or seed and the split manifest; randomness has its own planned topic. A seed does not record which dataset or code revision you used.
Python code, a notebook and an environment solve different problems. A notebook helps inspect intermediate results; a fresh script run exposes accidental dependence on previously executed cells. An environment records interpreter and dependency choices; it does not repair an incorrect split. For larger numerical workloads, keep these contracts while moving array operations to appropriate libraries. Continue with NumPy arrays, environment management and numerical tests.
Try to break the experiment boundary
- Reverse every CSV data row and call
run_csvwith(6, 4, 2, 4). Which report fields should change?
Answer: None in the same runtime. Sorting by ID restores record order, and canonicalizing the candidate set produces [2, 4, 6]. This includes both hashes and the tie rule. The original file’s raw byte hash would change; this program deliberately reports a normalized-data hash.
- Replace each test label with its complement while retaining every training row. Predict the selected threshold, training errors, test errors and fingerprint behavior.
Answer: Threshold 4 and zero training errors remain. Each binary prediction switches from correct to incorrect or vice versa, so test errors become 3 out of 4. The fit fingerprint stays fixed; the full-data fingerprint changes. This check would catch a selector that secretly included test labels in its objective.
- Pass a file with the ID
aonce in training and again in test. Would dropping the second occurrence make the run valid?
Answer: The declared input is invalid and raises ValueError. Dropping a row silently changes the test set and its denominator. Resolve the identity conflict upstream, document the corrected data and rerun. An empty resulting split would still be invalid.
- Use training rows
(x=0,y=0)and(x=10,y=1)with thresholds(9,1)and one test row(x=5,y=1). What are the model and baseline test errors? May the test result decide the training tie?
Answer: Both thresholds make zero training errors, so the smaller threshold 1 wins. It predicts 1 on the test row and has zero test errors. The training-majority tie gives baseline 0 and one test error. Selecting among tied training candidates by the test score would violate the stated contract even if this particular result looked unchanged.
Read library contracts as carefully as algorithms
The Python references describe the behavior that an experiment depends on: CSV parsing, dataclass-generated methods and JSON serialization. Their boundaries matter: a parser supplies fields, annotations describe a class, and an encoder supplies a representation. None supplies a valid experimental design by itself.
The scikit-learn pitfalls chapter connects those engineering concerns to learned transformations and test contamination. It is useful even when the learner is a dozen lines of standard-library Python. As a next project, replace the threshold selector with another learner while retaining the report schema and held-out-data invariance test. The change should be visible in the algorithm version and configuration, and its improvement should be measured on data reserved for evaluation.
Make a prediction, then check
With training records and threshold candidates fixed, which change may affect the fitted threshold?
Learning objectives
- Trace a score through validated input, training selection, held-out evaluation and a serialized report.
- Test that changing held-out data cannot change a fitted rule.
- Explain what annotations, frozen records, fingerprints and environment records do and do not guarantee.
Prerequisites & connections
This article can be used as an entry point.
Explore related knowledge →References
- csv — CSV File Reading and Writing — Python 3.12
Python Software Foundation and Python contributors - dataclasses — Data Classes — Python 3.12
Python Software Foundation and Python contributors - json — JSON Encoder and Decoder — Python 3.12
Python Software Foundation and Python contributors - Common Pitfalls and Recommended Practices — scikit-learn 1.7
scikit-learn developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Independent AI review clarified that _parse validates raw text and that signed integer syntax applies to the x field, not the exact binary label field. Code is unchanged.
- Six tests passed under CPython 3.12.12 and 3.12.4. Twelve small reports were checked by label-set and threshold-prefix counts, independently of the prediction loop; all four confusion reports and candidate losses match.
- Checked three held-out perturbations, one changed training label, row/candidate permutation, duplicate candidates, quoted CSV and equivalent integer spellings, fresh returned state, frozen rows, schema errors, empty splits and invalid thresholds.
- Original paired program and eight stdout lines; four displays, six anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML passed. Humanizer reread; author AI checks only, written pending independent review. Draft files only; no repository edits.
- Ran all six author tests under Python 3.12.4. An independent in-memory SQLite aggregate evaluates binary squared-error moments y+h−2yh to choose thresholds and reconstruct confusion entries from count, sum(y), sum(h) and sum(yh). Six small reports check candidate errors, tie/majority selection and 24 model/baseline split reports, distinct from the author’s label-set/prefix oracle.
- A separate manual ASCII byte encoder, restricted to the declared ID/split grammar, reconstructs canonical records and fit-configuration objects without json.dumps. Twelve resulting SHA-256 fingerprints match. This audits serialization inputs and order, not cryptographic collision resistance. Author tests additionally verify held-out perturbations, equivalent CSV spellings, malformed data, split nonemptiness and fresh returned state.
- Complete bilingual review identified two wording issues: _parse validates raw text rather than receiving only validated records, and optional signed integer syntax applies to x rather than binary labels. The author corrected both languages and recorded the independent AI correction in metadata; revised paragraphs and final hashes were reread. Algorithm code and tests were unchanged. No remaining defects identified.
- Verified training-only dependence, canonical candidate tie order, observed-error denominators, hash scope, environment-record limits and the stated full pipeline costs. Strict MDX/KaTeX and actual React HTML pass with four displays, six anchors and four answers per language; four math annotations match, and author tests verify the eight stdout lines and identical code. All five SHA values bind the final snapshot and source IDs/URLs match metadata exactly. No author files were edited by this reviewer.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- csv — CSV File Reading and Writing — Python 3.12 · Actually opened the 3.12 page, displayed 3.12.13. Read reader lines 21–24, DictReader 71–76, strict dialect 262–265 and newline/encoding examples 324–353 plus footnote 382. The original example uses reader with explicit schema validation; no source code copied.
- dataclasses — Data Classes — Python 3.12 · Actually read module introduction and decorator contract lines 7–38, FrozenInstanceError 272 and Frozen instances 325–328. Annotations are not runtime type checks; frozen guards ordinary reassignment. Page displayed 3.12.13.
- json — JSON Encoder and Decoder — Python 3.12 · Actually read Basic Usage lines 107–145: text output, ensure_ascii, allow_nan, separators, sort_keys, dumps and string-key coercion. Page displayed 3.12.13. No claim of a universal canonical JSON standard.
- Common Pitfalls and Recommended Practices — scikit-learn 1.7 · Actually read sections 11.1–11.2.2, especially lines 116–137 on training-only fitted preprocessing, and 11.3–11.3.1 on randomness. Version rendered 1.7.2. Original standard-library experiment only; sklearn was not executed.
- csv — CSV File Reading and Writing — Python 3.12 · Actually opened Python /3.12 csv reference rendered 3.12.13. Read reader lines 21–24 for string rows and newline handling; dialect lines 228–265 for quoted fields, whitespace and strict errors; examples 324–353 for explicit encoding/newline handling. Application schema validation is correctly separate from parsing. No claim that splitting on commas is equivalent or that the parser validates domain labels.
- dataclasses — Data Classes — Python 3.12 · Actually read Python /3.12 dataclasses reference rendered 3.12.13: generated constructor and annotations lines 7–38, frozen option 76 and Frozen instances 325–328. The article distinguishes documentary annotations from runtime validation and ordinary assignment guards from deep/security immutability.
- json — JSON Encoder and Decoder — Python 3.12 · Actually read Python /3.12 json reference rendered 3.12.13: Basic Usage 107–145 for text, ensure_ascii, allow_nan=False, separators, sort_keys and string keys. Reviewed the authored specific canonical byte convention; it is not asserted to be a universal canonical JSON standard or an authentication signature.
- Common Pitfalls and Recommended Practices — scikit-learn 1.7 · Actually read fixed /1.7 common-pitfalls page rendered 1.7.2: 98–137 for reusing training-fitted transformations, train/test separation and leakage during feature selection. Did not execute sklearn or audit its source. The chapter independently implements a deterministic standard-library threshold example.
Related topics