Train a tiny model
Cover security and operational gates
Training estimates model parameters from examples, while evaluation asks whether those learned parameters predict rows that were not used for fitting.
Before you start
Why this matters
Before running anything, predict one observable result from the case: a small linear relationship between study hours and score must be fit with one row held out. Write the prediction beside the command or code line that should cause it. This makes the session an experiment rather than a transcription exercise.
1Learn the idea
Read
Operate the chapter step
Operational quality includes safe inputs, predictable resources, and recoverable changes. Record data provenance, package versions, random seeds for stochastic models, and the exact feature order. Do not load untrusted serialized model objects because deserialization can execute code. Review what is written to disk or logs, which dependencies execute, and what another user can alter.
Read every command or statement before running it. The examples deliberately expose intermediate state so a surprising result has somewhere concrete to point.
Read
Run the working example
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
X_train = [[1], [2], [3], [4]]
y_train = [52, 60, 68, 76]
X_test, y_test = [[5]], [84]
model = LinearRegression()
model.fit(X_train, y_train)
prediction = model.predict(X_test)
print(f"slope={model.coef_[0]:.1f}")
print(f"prediction={prediction[0]:.1f}")
print(f"mae={mean_absolute_error(y_test, prediction):.1f}")
Expected evidence:
slope=8.0
prediction=84.0
mae=0.0
The output may include version-specific details such as hashes, paths, fitted thresholds, or final decimal places. Compare the structural facts described here rather than copying placeholders. If the structure differs, stop and inspect the earliest unexpected line.
Read
Read it line by line
- scikit-learn expects
Xas rows by features, so each hour value sits inside a one-item list. fitestimates coefficient and intercept using only training rows.predictapplies frozen parameters to the held-out row.- mean absolute error measures the average magnitude of mistakes in the target's units.
These lines form one chain: training pairs of study hours and observed scores plus one untouched test pair becomes a fitted slope and intercept, one held-out prediction, and an error value. Change only one input first. When several values change together, you cannot tell which change caused the new behavior.
Read
Common errors and fixes
- First failure: a one-dimensional
X_traintriggers an expected-2D-array error; reshape or use nested rows. Re-run the smallest command that proves the repair. - Second failure: calling
predictbeforefitraises a not-fitted error. Preserve the failing input as a test when it represents a realistic mistake. - Misleading success: mixing the held-out row into fitting makes the evaluation optimistic and defeats the test. A clean-looking final line cannot cancel contradictory intermediate evidence.
When debugging, copy the exact error text and inspect names, paths, shapes, types, and versions. Explain the cause in one sentence before changing code. That discipline prevents a guessed repair from creating a second defect.
Read
Evidence for this stage
The input contract is training pairs of study hours and observed scores plus one untouched test pair. The visible result is a fitted slope and intercept, one held-out prediction, and an error value.
For the current operate step, save the smallest useful evidence: the relevant command, its output, and the input that produced it. Do not use a screenshot as the only record when text can be copied and searched. Keep generated artifacts separate from source inputs so rerunning the example does not destroy the evidence it is meant to evaluate.
Use more than one test row for a credible metric, compare against a simple mean baseline, inspect residuals, and repeat with an outlier. Zero error on one manufactured point demonstrates mechanics, not production quality.
Read
Reflect on the result
Return to your opening prediction. Mark it correct or rewrite it with the condition you missed. Then explain the difference between a successful execution and a trustworthy result for this specific example.
Continue learning · glossary & guides
- Which line or command establishes the current step's most important fact?
- What output would reveal that a one-dimensional
X_traintriggers an expected-2D-array error? - Can a new user reproduce a fitted linear regression with a held-out prediction, mean absolute error, and recorded coefficient from the stated setup?