How to Build a Student Grade Prediction Model Using Python

A student has just learned Python and wants to build a first machine-learning project. They find a spreadsheet containing study-time categories, earlier assessment grades and a final Mathematics grade. The exciting question is whether a computer can estimate the final grade before it becomes known. But building a model is not simply clicking “Train.” Which information would actually exist at the prediction date? What happens if earlier grades are added only after they are recorded? And how can the student tell whether a sophisticated algorithm beats a simple average? These questions turn a coding exercise into responsible data science.

This student grade prediction using Python tutorial teaches the complete workflow: define a prediction stage, verify the source, inspect and prepare data, isolate an untouched test set, train a mean baseline, build Ridge and Random Forest regression Pipelines, compare candidates through five-fold cross-validation, interpret MAE, MSE, RMSE and R², examine residual plots and write an accountable model report. It also explains fairness, privacy, uncertainty, generalization and why model importance is not causal proof. We use the official UCI Student Performance dataset as the intended historical source and original fictional records for an executed numerical demonstration.

Research integrity and data status (25 November 2026): The official UCI dataset description, citation and 0–20 grading system were verified. However, this working environment could not download its original student-mat.csv, so no numerical results in this article are represented as actual UCI model performance. The executable demo was tested on 180 deliberately fictional records; its charts, cross-validation and held-out metrics are visibly labelled synthetic. The downloadable source script separately supports the official 395-record UCI file when students download it themselves. These models are educational demonstrations only and must not rank students or determine school opportunities.

The research sequence is Question → Prediction time → Source → Data quality → Target → Available features → Train/test split → Training-only preprocessing → Baseline → Cross-validation → Select model → Final held-out test → Explain limitations. A high score cannot justify including information from the future, nor does any predicted grade define someone’s ability or potential. Students worldwide can learn from this historical Portuguese benchmark without assuming its grading scale, demographic context or school conditions apply to their own education systems.

Figure 1. Define the question, verify the source, select features, split, validate and report responsibly.
Figure 1. Define the question, verify the source, select features, split, validate and report responsibly.

What is machine learning, and why is this a regression problem?

Machine learning refers to computational methods that learn statistical patterns from examples instead of relying entirely on handwritten rules. In supervised learning, each historical training observation contains a set of inputs and a known target. The algorithm fits a mapping and later produces estimates for unseen inputs. A feature is an input column; a target is the outcome; a prediction is the model’s numerical estimate; and generalization means the method performs usefully beyond its fitted observations. Learning a pattern does not mean understanding a person’s life or discovering a cause.

We choose regression because the target is a numerical final grade G3 on a historical 0–20 scale. A prediction such as 12.5 is an estimate, even though recorded grades may be integers. Classification would instead assign a predefined category, for example a locally specified band. Pass thresholds vary across systems, so the benchmark should not quietly adopt a universal worldwide “pass” definition. The tutorial focuses on predicting numerical G3 and judging error in grade points, not predicting intelligence or personal worth.

Figure 2. Regression predicts a numeric grade; classification predicts a specifically defined category.
Figure 2. Regression predicts a numeric grade; classification predicts a specifically defined category.

Verify the UCI Student Performance dataset before using it

The official UCI repository entry (dataset 320) attributes the dataset to Paulo Cortez, with an associated study by Cortez and Silva (2008), Using Data Mining to Predict Secondary School Student Performance. The source describes historical school-report and questionnaire data from two Portuguese secondary schools and supplies separate Mathematics (student-mat.csv) and Portuguese-language (student-por.csv) files. The Mathematics file is documented as containing 395 rows and 33 columns, with a semicolon delimiter. Its final Mathematics outcome G3 uses grades from 0 through 20. UCI marks the dataset CC BY 4.0; cite the creators and repository and check the current terms before redistributing original files. DOI: 10.24432/C5TG7T.

Do not combine the 395-row Mathematics file with the roughly 649-row Portuguese file simply to increase the sample: the two represent different subjects, and some people may occur in both. Combining them would introduce questions about repeated learners, target definition and grouped evaluation. The source itself states that final G3 is strongly related to earlier G1 and G2 and that prediction without those grades is more difficult. The records are historical, geographically narrow and socially contextual; they cannot support a claim that the resulting model will predict present-day grades accurately in every school. You should download the official archive directly and preserve the source files unchanged.

Understand G1, G2 and G3—and the prediction date

VariableRoleMeaning in UCIWhen it might be available
G1Earlier measured gradeFirst-period grade (0–20)After first grading period
G2Earlier measured gradeSecond-period grade (0–20)After second grading period
G3TargetFinal grade (0–20)After final assessment; never use as feature
studytimeInput categoryOrdinal weekly study-time code 1–4Collection timing not fully established
failuresInput codeRecorded previous class-failure categoryCollection timing must be checked
schoolsup / famsupInput categoriesSchool / family educational support, yes/noCollection timing must be checked

Prediction timing changes the legitimate information set. Before period one, neither G1 nor G2 exists as an observed grade. After period one, G1 may be available and G2 is still unavailable. After period two, both earlier grades may be available. The dataset lacks collection timestamps for every explanatory field, so the reduced-feature scenario is explicitly a retrospective modelling exercise, not a validated early-warning intervention. Adding later grades can improve predictive information while answering a different, later question. Never include G3 itself among G3 predictors.

Figure 3. Reduced educational features feed a numerical G3 target; timing governs additional grades.
Figure 3. Reduced educational features feed a numerical G3 target; timing governs additional grades.

Build a reproducible Python environment

Use a current supported Python version in Jupyter, VS Code or another trusted development environment. Install Pandas, NumPy, Scikit-Learn and Matplotlib into the same interpreter your notebook uses. The packaged teaching run was executed with Python 3.13.5, Scikit-Learn 1.8.0, Pandas 2.2.3 and NumPy 2.3.5. Because Scikit-Learn’s API evolves, verify support for root_mean_squared_error and OneHotEncoder(sparse_output=False); recent versions support both. Save dependency versions alongside the project, and avoid confusing a successful installation in one environment with a notebook kernel using another.

python -m pip install pandas numpy scikit-learn matplotlib notebook
# Run only from a trusted environment with needed permissions.
# Place official UCI student-mat.csv in data/raw/

Load and inspect the official Mathematics CSV

The UCI Mathematics CSV is semicolon-delimited, so Pandas must use sep=";". If you forget that option, the entire first row may appear as one unusually long column. Check the shape, names, missingness, grade bounds and data types before selecting predictors. Do not discard a repeated row merely because it matches another row in all observed fields: without a unique learner ID, two people may happen to share the same attributes. For the original source, check that the expected 395 records loaded and that G3 falls within the documented 0–20 scale. Any unexpected results should stop the workflow for investigation.

import pandas as pd
from pathlib import Path
path=Path('data/raw/student-mat.csv')
if not path.exists():
    raise FileNotFoundError('Download official student-mat.csv from UCI first')
df=pd.read_csv(path,sep=';')
print(df.shape,df.columns.tolist())
print(df.isna().sum().sort_values(ascending=False).head())
print(df[['G1','G2','G3']].describe())
assert len(df)==395 and 'G3' in df
assert pd.to_numeric(df.G3,errors='raise').between(0,20).all()

The original UCI documentation reports no missing values, but you should still run the check on the copy you obtain; it catches corrupted downloads, changed versions and import mistakes. Inspect the target histogram and count each grade. Zero is a valid score on the recorded scale; it must not be converted to missing simply because it may be undesirable. Extreme low and high results can be genuine. Our accompanying offline dataset contains 180 entirely synthetic observations and is only a sandbox for learning the pipeline; its distribution and model scores are not evidence about the historical UCI participants.

Figure 4. Synthetic G3 grade distribution of 180 fictional observations; not the UCI Mathematics dataset.
Figure 4. Synthetic G3 grade distribution of 180 fictional observations; not the UCI Mathematics dataset.

Avoid target leakage, future information and accidental duplication

Leakage occurs when a model gains information that would not legitimately be available at prediction time or that improperly leaks across evaluation boundaries. Four cases matter here. Target leakage: including G3 among predictors for G3. Timing leakage: including second-period G2 in a model claiming to predict before that period. Preprocessing leakage: learning a median or scaling statistics from all rows before splitting or cross-validation. Student-group leakage: placing records from the same person in both train and test sets when the goal is generalization to new people. An ordinary train/test split cannot solve unavailable identifiers or missing timestamp evidence; these limitations must be disclosed, not silently assumed away.

Figure 5. Define prediction time, exclude the target, split first and fit learned preprocessing only within training folds.
Figure 5. Define prediction time, exclude the target, split first and fit learned preprocessing only within training folds.

Reserve the test set before fitting anything

The main teaching strategy reserves 80% for training and training-fold validation, with 20% untouched for final testing. If all 395 UCI Mathematics records are retained, the expected integer split is 316 training and 79 test rows. Cross-validation is performed only inside the training partition to compare candidates; the held-out test is used once after selection. A stable random_state makes the demonstration reproducible, but it cannot fix poor population coverage. If data involve repeated learners, multiple schools with institutional clustering, or genuinely temporal prediction, consider group-aware or time-aware validation rather than assuming random K-fold is universally appropriate.

Figure 6. Eighty/twenty partition: synthetic 144 train and 36 test; official 395 rows would yield 316 and 79.
Figure 6. Eighty/twenty partition: synthetic 144 train and 36 test; official 395 rows would yield 316 and 79.

Create a baseline before training sophisticated algorithms

A baseline answers: what performance do we get from a simple strategy? The mean DummyRegressor predicts the average training-target G3 for every test record. If a complex model does not improve on the mean baseline by an amount meaningful to the intended study, complexity is hard to justify. Crucially, the baseline mean must be fitted from training targets alone. Using the full sample’s target mean would inspect held-out answers. The baseline is evaluated with exactly the same final test observations and metric definitions as the chosen model.

Prepare numerical and categorical features safely

Our reduced-feature tutorial treats studytime and failures as coded numeric variables and schoolsup/famsup as yes/no categorical variables. The first pair is not unbounded continuous real-world quantities: studytime=3 represents a range of weekly study hours, not exactly three hours. Numeric preprocessing uses a median imputer and standard scaling, while categorical preprocessing uses a most-frequent imputer and one-hot encoding with unknown-category handling. ColumnTransformer applies separate rules to the two types; Pipeline makes the fitted transformations part of each cross-validation fold. No sensitive demographic columns are needed for this reduced example.

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler,OneHotEncoder

numeric=['studytime','failures']
categorical=['schoolsup','famsup']
features=numeric+categorical
X=df[features].copy(); y=df['G3'].copy()
num_pipe=Pipeline([('impute',SimpleImputer(strategy='median')),
                   ('scale',StandardScaler())])
cat_pipe=Pipeline([('impute',SimpleImputer(strategy='most_frequent')),
                   ('encode',OneHotEncoder(handle_unknown='ignore',
                                           sparse_output=False))])
preprocess=ColumnTransformer([('num',num_pipe,numeric),
                              ('cat',cat_pipe,categorical)])

Train Ridge and Random Forest candidates

Ridge regression is a linear model with L2 regularization, which penalizes large coefficient magnitudes and can be useful for stable learning with several encoded inputs. It predicts a weighted sum plus an intercept; coefficients are not causal effects. A Random Forest regressor averages many decision-tree predictions and can represent nonlinear patterns and interactions. It may overfit, requires suitable hyperparameters and is not guaranteed to beat Ridge. Scaling can matter for regularized linear models but is generally less important for trees; our consistent preprocessing makes the beginner comparison easier to reproduce without implying a universal scaling rule.

from sklearn.linear_model import Ridge
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split,KFold,cross_val_score
from sklearn.dummy import DummyRegressor

X_train,X_test,y_train,y_test=train_test_split(
    X,y,test_size=.20,random_state=86)
candidates={
 'Ridge': Pipeline([('preprocess',preprocess),('model',Ridge(alpha=1.0))]),
 'Random Forest': Pipeline([('preprocess',preprocess),
   ('model',RandomForestRegressor(n_estimators=200,
                  min_samples_leaf=3,random_state=86))])
}
cv=KFold(n_splits=5,shuffle=True,random_state=86)
cv_mae={name:-cross_val_score(model,X_train,y_train,
        scoring='neg_mean_absolute_error',cv=cv).mean()
        for name,model in candidates.items()}
best_name=min(cv_mae,key=cv_mae.get)
best_model=candidates[best_name].fit(X_train,y_train)
baseline=DummyRegressor(strategy='mean').fit(X_train,y_train)
print('Training-only CV:',cv_mae,'selected',best_name)

The full downloadable src/grade_project.py implements this selection, validation checks, staged alternatives and export of results. Students should run it against their own officially downloaded UCI CSV; this page does not insert fictional MAEs into the UCI example. Cross-validation scores measure validation performance inside the training set. They are not final test-set results, and a small difference between candidates may reflect sampling variability rather than an objectively superior universal algorithm.

Evaluate the selected model once on held-out records

After the training-fold comparison determines which reduced-feature candidate to use, fit that candidate on all available training rows and predict the held-out test rows. Evaluate the training-mean baseline on those same test targets. The project reports Mean Absolute Error (MAE), Mean Squared Error (MSE), Root Mean Squared Error (RMSE) and R-squared, which answer different questions about numerical error. A lower average error on one historical split is not a guarantee for a different school or cohort. If the scores appear implausibly perfect, investigate whether G3, future grades or test-derived preprocessing leaked into the model.

from sklearn.metrics import (mean_absolute_error,
    mean_squared_error,root_mean_squared_error,r2_score)

def report_scores(y_true,estimator):
    estimate=estimator.predict(X_test)
    return {
      'MAE':mean_absolute_error(y_true,estimate),
      'MSE':mean_squared_error(y_true,estimate),
      'RMSE':root_mean_squared_error(y_true,estimate),
      'R2':r2_score(y_true,estimate),
    }
print('Baseline held-out:',report_scores(y_test,baseline))
print('Selected held-out:',report_scores(y_test,best_model))
# Outputs must be computed from YOUR successfully loaded dataset.

Actual tested outputs: synthetic records only

To verify that the code genuinely runs without pretending to have downloaded the UCI file, we generated 180 fictional records with a declared random seed 86086. The selected training/test split uses random state 86 and produces 144 training rows and 36 held-out test rows. Five-fold training CV gave Ridge a mean MAE of 3.237 grade points and Random Forest a mean MAE of 3.221 points. Under the predeclared lower-CV-MAE selection rule, Random Forest was chosen by a small margin. These figures are reproducible results of the synthetic generator, not estimates of performance on actual Portuguese Mathematics students.

Figure 7. Actual five-fold CV MAE calculated on fictional training data: Ridge 3.237; Random Forest 3.221. Not UCI results.
Figure 7. Actual five-fold CV MAE calculated on fictional training data: Ridge 3.237; Random Forest 3.221. Not UCI results.

The training-mean baseline’s held-out MAE on this particular fictional split was 3.291, compared with 2.958 for the selected Random Forest. The selected model’s held-out RMSE was 3.615 points and R² was approximately 0.170. Such modest performance should not be presented as a reliable real-world prediction service. The synthetic generating process embeds patterns chosen for an educational demonstration; if those rules change, the metrics change too. A legitimate study using the UCI data must download it, rerun every check and report its entirely separate computed outcomes.

Synthetic demonstrationEvaluation stageMAE (points)Interpretation
RidgeFive-fold TRAINING CV3.237Candidate selection only
Random ForestFive-fold TRAINING CV3.221Candidate selection only
Training-mean baselineUntouched TEST (36 rows)3.291Simple reference
Selected Random ForestUntouched TEST (36 rows)2.958Final synthetic test MAE

Do not make a bar chart that mixes a baseline’s test MAE with candidates’ training CV MAE and then label them a controlled three-model ranking. The CV scores and test metrics reflect different evaluation procedures. The table deliberately labels each stage; the matched comparison is baseline versus selected model on the same held-out rows. The chart above deliberately displays only the two candidates’ CV scores, keeping unlike evaluation measurements separate.

Work through MAE, MSE, RMSE and R² by hand

Before trusting Python’s metrics, verify an explicitly fictional five-student arithmetic example. Suppose actual grades are 8, 10, 12, 14, 16 and supplied predictions are 9, 9, 13, 12, 17. These are constructed numbers, not the output of Ridge or a real student’s performance record. The absolute errors are 1, 1, 1, 2 and 1 grade points. Their sum is six, so MAE=6/5=1.2 grade points. MAE reports the mean magnitude of an error, without allowing positive and negative errors to cancel.

Squaring each difference gives 1, 1, 1, 4 and 1, for a sum of eight. Hence MSE=8/5=1.6 squared grade points. Taking the square root returns to the original target units: RMSE=√1.6≈1.2649 grade points. RMSE gives relatively greater weight to larger individual errors and is not automatically the “best” metric. Choose measures that fit the research purpose and error consequences. The predicted values are not guaranteed to match integers; a regression algorithm can return decimal estimates or even mathematically return values outside the allowed 0–20 range.

For R², the actual grades’ mean is 12. Their total squared deviation from 12 is SST=40, while the squared prediction errors sum to SSE=8. Therefore R²=1−8/40=0.80. This is a dimensionless comparison with a mean-based reference on the evaluated observations, not “80% chance the model is correct” and not a classification accuracy percentage. Test-set R² can be negative when a model performs worse than the reference. In our five-number illustration, a constant prediction of 12 has absolute errors 4, 2, 0, 2, 4 and a baseline MAE of 2.4 points. None of these five-number results is evidence of UCI model performance.

Figure 8. Five entirely fictional actual and predicted grades used to verify MAE 1.2, RMSE approximately 1.265 and R² 0.80.
Figure 8. Five entirely fictional actual and predicted grades used to verify MAE 1.2, RMSE approximately 1.265 and R² 0.80.

Actual versus predicted: what does the scatter plot show?

An actual-versus-predicted chart places each held-out record’s actual grade on the horizontal axis and its estimate on the vertical axis. The diagonal line prediction=actual represents perfect agreement; points above it are overpredicted and points below it are underpredicted. The distance from this line reveals error patterns that a single MAE can hide. The plot shown here is based on the 36 actual computed predictions from the fictional test set, not an idealized diagram or a claim about UCI results. The full 0–20 scale makes the spread of errors visible rather than hiding weaker predictions by zooming excessively.

Figure 9. Genuine computed test predictions from a synthetic 180-row experiment, not UCI records.
Figure 9. Genuine computed test predictions from a synthetic 180-row experiment, not UCI records.

Residual analysis: examine what the summary misses

For our sign convention, a residual = actual grade − predicted grade. Positive residuals mean the model underpredicted, and negative residuals mean it overpredicted. Plotting residuals against predictions can reveal systematic patterns: a curved shape may suggest misspecification, groups with wider spread suggest nonconstant error variance, and clusters can indicate unmodelled subpopulations. However, a pattern does not prove its cause; it invites further investigation with appropriate domain evidence. Evaluate both numerical diagnostics and the consequences of unusually large errors. A few extreme residuals can matter even when the average seems tolerable.

Figure 10. Residual = actual minus predicted for fictional held-out records; not UCI model evaluation.
Figure 10. Residual = actual minus predicted for fictional held-out records; not UCI model evaluation.

Overfitting, underfitting and sensible hyperparameters

Overfitting means the model learns training-specific noise or patterns that do not generalize. It is not defined merely by having a high training score: what matters is the comparison with reliable validation or test evidence. Underfitting occurs when the model or available features are too limited to learn the relevant structure even within training. For forests, too-deep trees or tiny leaves can increase complexity; larger min_samples_leaf and sensible depth controls may help. Ridge’s alpha sets regularization strength. Hyperparameter search should be performed through training-only CV, not by repeatedly checking the final test until a pleasing result appears. With few historical schools, even careful validation leaves external generalization uncertain.

Three retrospective prediction stages

A valuable experiment compares the same outcome at distinct information stages, keeping the population and training splits consistent. Stage A uses reduced study/support features alone. Stage B adds G1 after the first grading period. Stage C adds both G1 and G2 after the second period. The later models answer a later prediction question, not the original early-stage question more accurately by magic. Because exact timestamps for every survey feature are not established, all three are retrospective demonstrations. To avoid test-set tuning, their relative results below are computed using five-fold CV only inside the synthetic training partition.

Figure 11. Synthetic training-fold Ridge CV MAE falls from 3.237 (reduced) to 1.634 (with G1) and 1.464 (with G1 and G2). Timing changes the task.
Figure 11. Synthetic training-fold Ridge CV MAE falls from 3.237 (reduced) to 1.634 (with G1) and 1.464 (with G1 and G2). Timing changes the task.

In the fictional data, mean training-CV MAE for a Ridge model fell from 3.237 with reduced features to 1.634 with G1 and 1.464 with G1 plus G2. These values arise partly because the synthetic generation intentionally relates earlier grades to the final grade. They neither establish real UCI outcomes nor show that family support or study time causally determines grades. They demonstrate why a predictor should state when an estimate is meant to be made. A model using G2 is inappropriate for a claim about the beginning of a school year, however low its error may later become.

Feature importance is not causal evidence

After fitting a model, students may ask which fields matter most. A Ridge coefficient expresses a model association under the selected encoding, not the effect of changing a student’s circumstances. In a forest, impurity-based feature importance has known biases. Permutation importance asks how much a named score falls when one feature is shuffled under a stated evaluation setup. Correlated features may substitute for one another, making individual rankings unstable; sample size and the chosen scoring function also matter. Do not claim that increasing study time or altering family support will cause a particular improvement simply because a predictive feature seems important. We intentionally do not invent feature-importance rankings for the unavailable UCI observations.

Generalization beyond the original schools

The historical UCI data come from two Portuguese secondary schools and use a 0–20 scale. Modern curricula, student populations, support arrangements and grading systems can differ greatly, creating dataset shift. A model fitted on this historical benchmark cannot be declared accurate in another country, subject or year without independent external validation. Multiplying a predicted 0–20 grade by five does not establish validity for a 0–100 system: assessment constructs may not be equivalent. A useful model evaluation must describe the source population, prediction stage and actual setting in which an estimate would be used, rather than promoting benchmark results as universal.

Fairness, privacy and human oversight

Educational records can reveal sensitive circumstances. Historical correlations may reflect unequal opportunities, socioeconomic disadvantage and institutional practices rather than stable personal attributes. Apparently neutral variables may act as proxies for sensitive characteristics, so removing one demographic field does not automatically remove bias. Even a model with reasonable average error might perform differently for particular groups; this small benchmark cannot prove that a model is fair in contemporary schools. Responsible analysis asks who is represented, what outcomes mean, which errors matter, and whether the data can be used with appropriate safeguards. The UNESCO Recommendation on AI Ethics provides useful principles of fairness, transparency and accountability.

Do not ask real Notes for SHS students—especially minors—to enter identifiable grades, family details or private school records into an open form. Do not upload identifiable files to public GitHub repositories, publish predictions linked to named people, or use model estimates to deny admission, scholarships, tutoring, support or other opportunities. A numerical prediction is not a measurement of intelligence, ability or potential. Schools considering any predictive service would require lawful data governance, local evidence, student protections, independent assessment and meaningful human oversight. This article presents a historical educational demonstration only, not a system to deploy.

Figure 12. Educational data science requires privacy, fairness, uncertainty disclosure, human oversight and no exclusionary automated decisions.
Figure 12. Educational data science requires privacy, fairness, uncertainty disclosure, human oversight and no exclusionary automated decisions.

Uncertainty, grade boundaries and safe model files

An estimated final grade of 13.2 is not a guarantee. MAE describes average absolute error and can conceal exceptional mistakes; additional calibration or uncertainty methods require their own assumptions and validation. A 95% prediction interval cannot be created credibly by adding and subtracting an arbitrary fixed number. Numerical regressors can also return predictions below zero or above 20. Such predictions are not literal valid grades and should be flagged. Any clipping or constrained modelling policy must be defined and evaluated transparently, rather than adjusted to make a test score look better.

The ZIP contains executable Python source, a tested notebook, a model card and environment requirements rather than a serialized trained model file. Python pickle/joblib model deserialization can execute code when untrusted files are loaded. Students should never import unknown serialized models from random websites. If you save a model that you trained locally, document which code, library versions, source data and preprocessing produced it; that does not make it safe or approved for consequential school decisions.

Troubleshooting the most common Python errors

ProblemLikely reasonRecommended correction
FileNotFoundErrorOfficial CSV not foundDownload from UCI, verify folder
One giant CSV columnWrong delimiterUse sep=’;’
KeyError: G3Wrong file or header parsingInspect df.columns
Could not convert string to floatCategories not encodedOneHotEncoder in ColumnTransformer
Missing-value rejectionNo appropriate imputerSimpleImputer within Pipeline
Unknown categoryNew category in test datahandle_unknown=’ignore’; review meaning
Version-related API errorDifferent scikit-learn releaseCheck installed version and docs
Implausibly perfect performancePossible target/timing leakageAudit features and split
Large score changes across runsRandomness or data changedRecord seed, folds, version
Out-of-range predicted gradeUnconstrained regressorFlag and disclose policy

Excel and Google Sheets: verify the five-student calculations

The main predictive model belongs in Python and Scikit-Learn, but a spreadsheet helps verify regression metrics. The companion workbook contains five fictional actual grades in column B and corresponding estimates in column C. =ABS(B2-C2) produces absolute error, and =AVERAGE(D2:D6) returns 1.2 grade points after filling down. The squared-error and R² formulas also recalculate successfully. The Sheets-compatible XLSX has been generated but not executed in the native Google Sheets online editor. This exercise is distinct from evaluating the UCI model; it supports transparent arithmetic only.

Forty-five common modelling mistakes and their corrections

Common errorCorrection
Unverified datasetUse original UCI page
Missing attributionCite creators and DOI
0–20 called percentageReport grade points
Studytime coded as exact hoursRead category definitions
Wrong targetUse G3
Target G3 included as featureRemove G3 from X
G2 used before period twoDefine prediction date
No feature timestampsDisclose retrospective limits
Combining two subjects blindlyReview repeated-student risk
No test setReserve held-out 20%
Training and testing on same rowsSplit before fitting
Imputer fitted on all rowsUse Pipeline within CV
Scaler fitted before CVFit per training fold
Categorical text unencodedUse OneHotEncoder
Unknown categories mishandledhandle_unknown and review
Low grades removedRetain valid values
Zero treated as blankUse 0–20 definition
No baselineUse training mean DummyRegressor
Training error called test errorLabel evaluation stage
Classification accuracy for regressionMAE, RMSE, R²
MAE expressed as percentUse grade points
MSE in ordinary pointsSquared-point units
RMSE confused with MSESquare root
R² labelled probabilityExplain mean comparison
Assuming R² never negativeTest R² may be negative
Complex model always preferredCompare cross-validation
Ignoring overfittingCheck generalization
Tuning on held-out testTune inside training
CV score called final testSeparate CV/test
Invented performance resultsExecute code before claims
Ignoring residualsPlot and review errors
Importance called causalExplain model reliance
Correlated predictors ignoredCaution with rankings
Ignoring sensitive proxiesAudit fairness risks
Historical model called globalAssess dataset shift
Different grade systems conflatedExternal validation
Prediction portrayed certainReport uncertainty
Silently clipping predictionsDocument postprocessing
Deploying classroom modelNo high-stakes deployment
Unnecessary personal dataMinimize collection
Private records uploaded publiclyUse authorized data only
Fictional figures labelled realDeclare synthetic source
Loading untrusted model filesAvoid unsafe deserialization
Software version omittedRecord dependencies
Fabricated actual-vs-predicted plotsUse computed predictions

Four-week learning roadmap

WeekFocusEvidence of progress
1Target, UCI source, timing and exploratory analysisExplain G1/G2/G3 and selection
2Baseline, Pipeline, Ridge and Random ForestRun tested synthetic notebook
3CV, MAE/MSE/RMSE/R² and residualsRecalculate five-student metrics
4Bias, privacy, report and capstoneSubmit reproducible model card

Capstone: Predicting Final Mathematics Grades Responsibly

The complete ten-task capstone is a structured investigation rather than a contest to reach the lowest possible MAE. Students should document the intended prediction date, distinguish the UCI file from the fictional offline demonstration, cite the source, inspect quality, select features with defensible timing, reserve a held-out test set, compare baseline and candidate algorithms, and explain uncertainties and ethical limitations. For every task, include the relevant code or method, evidence of completion, an interpretation, a common failure and an extension. If the official file cannot be obtained, submit the source-retrieval limitation and the separately labelled synthetic exercise; do not copy the demo metrics into a claimed UCI results table.

Capstone 1 — Define the prediction question

Complete this step in the local notebook and document evidence before revealing the reference.

Show required evidence

Specify G3 and when the estimate is made; don’t imply early-warning validity without feature timestamps.

Common error: Confusing synthetic practice outputs with verified performance on the real UCI dataset, or using features unavailable at the defined prediction time.

Capstone 2 — Verify source and licence

Complete this step in the local notebook and document evidence before revealing the reference.

Show required evidence

Cortez/ UCI 320, 395 Mathematics records, semicolon CSV, 0–20 grade scale, CC BY 4.0.

Common error: Confusing synthetic practice outputs with verified performance on the real UCI dataset, or using features unavailable at the defined prediction time.

Capstone 3 — Inspect data quality

Complete this step in the local notebook and document evidence before revealing the reference.

Show required evidence

Validate columns, target range, missing cells, duplicates and coded variables.

Common error: Confusing synthetic practice outputs with verified performance on the real UCI dataset, or using features unavailable at the defined prediction time.

Capstone 4 — Select legitimate features

Complete this step in the local notebook and document evidence before revealing the reference.

Show required evidence

Reduced historical features first; G1/G2 only in later stages; never include G3.

Common error: Confusing synthetic practice outputs with verified performance on the real UCI dataset, or using features unavailable at the defined prediction time.

Capstone 5 — Split before training

Complete this step in the local notebook and document evidence before revealing the reference.

Show required evidence

Reserve 20% test, use the remaining 80% for cross-validation.

Common error: Confusing synthetic practice outputs with verified performance on the real UCI dataset, or using features unavailable at the defined prediction time.

Capstone 6 — Fit a mean baseline

Complete this step in the local notebook and document evidence before revealing the reference.

Show required evidence

Calculate baseline from training labels only.

Common error: Confusing synthetic practice outputs with verified performance on the real UCI dataset, or using features unavailable at the defined prediction time.

Capstone 7 — Build two Pipelines

Complete this step in the local notebook and document evidence before revealing the reference.

Show required evidence

Median/scale numeric features; encode categorical features; Ridge and Random Forest.

Common error: Confusing synthetic practice outputs with verified performance on the real UCI dataset, or using features unavailable at the defined prediction time.

Capstone 8 — Compare training CV results

Complete this step in the local notebook and document evidence before revealing the reference.

Show required evidence

Use common five folds, MAE and justified model selection.

Common error: Confusing synthetic practice outputs with verified performance on the real UCI dataset, or using features unavailable at the defined prediction time.

Capstone 9 — Evaluate the selected model

Complete this step in the local notebook and document evidence before revealing the reference.

Show required evidence

On untouched test, report MAE, MSE, RMSE, R² and residual graphics.

Common error: Confusing synthetic practice outputs with verified performance on the real UCI dataset, or using features unavailable at the defined prediction time.

Capstone 10 — Produce an ethical report

Complete this step in the local notebook and document evidence before revealing the reference.

Show required evidence

Include provenance, test limitations, bias, privacy, uncertainty, model card and no high-stakes use.

Common error: Confusing synthetic practice outputs with verified performance on the real UCI dataset, or using features unavailable at the defined prediction time.

Can You Spot the Machine Learning Mistake?

Before reading an answer, identify what is wrong with each scenario and name the violated principle. These eight short exercises use expandable solutions; they are not unverified web-based model execution buttons. Try them in class or alongside your local notebook and discuss why a plausible-looking evaluation can still be invalid.

Scenario 1: G3 appears in the features

Show hint

Consider feature timing, training/test separation, model meaning or student protection.

Reveal correction

Target leakage: remove the G3 column from X before fitting.

Scenario 2: G2 is used to predict before the second term

Show hint

Consider feature timing, training/test separation, model meaning or student protection.

Reveal correction

Timing leakage: G2 is unavailable until that grading stage.

Scenario 3: Median imputation happens before splitting

Show hint

Consider feature timing, training/test separation, model meaning or student protection.

Reveal correction

Preprocessing leakage: fit the imputer only within training folds.

Scenario 4: The reported performance comes from training data

Show hint

Consider feature timing, training/test separation, model meaning or student protection.

Reveal correction

Use unseen held-out observations after training-only selection.

Scenario 5: schoolsup is fed as unencoded text

Show hint

Consider feature timing, training/test separation, model meaning or student protection.

Reveal correction

Use a suitable categorical encoder in ColumnTransformer.

Scenario 6: Complex model is worse than the mean baseline

Show hint

Consider feature timing, training/test separation, model meaning or student protection.

Reveal correction

Explain why added complexity is unjustified for the task; compare common metrics.

Scenario 7: Feature importance is used to prove causation

Show hint

Consider feature timing, training/test separation, model meaning or student protection.

Reveal correction

Model dependence is not a causal effect of changing a feature.

Scenario 8: A public prediction form requests minors’ family data

Show hint

Consider feature timing, training/test separation, model meaning or student protection.

Reveal correction

No high-stakes or privacy-invasive deployment; use fictional data locally.

Thirty original practice questions and worked solutions

The questions below progress from supervised-learning vocabulary to grade-point calculations and advanced evaluation decisions. There are exactly thirty questions: ten foundations, ten calculation and modelling problems, and ten interpretation and responsible-use questions. Every question provides a hint, an answer and a common error. The companion PDF separates the question-only version from the worked answers, allowing classroom or independent assessment without immediately revealing solutions.

Level 1 — Machine Learning Foundations

Question 1 — Define supervised learning

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Learning a mapping from inputs to known outcomes in labelled examples.

Common mistake: A model does not understand potential.

Question 2 — Explain regression

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Predict a numerical final grade such as 12.5.

Common mistake: Do not call it categorical accuracy.

Question 3 — Explain classification

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Predict a defined category, such as a grade band.

Common mistake: Define thresholds locally.

Question 4 — Name the target

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: G3 is the final Mathematics grade (0–20).

Common mistake: Never put G3 in X.

Question 5 — Name two input features

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: studytime and failures are documented coded predictors.

Common mistake: Studytime codes are not hours.

Question 6 — Define training data

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Rows used to fit the model and learned preprocessing.

Common mistake: Test rows must remain untouched.

Question 7 — Define a held-out test set

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Unseen observations for final evaluation.

Common mistake: Not tuning data.

Question 8 — Why use a baseline?

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: To compare complex models with a training-mean reference.

Common mistake: Mean based only on training labels.

Question 9 — When is G2 unavailable?

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Before the second grading period is completed.

Common mistake: Prediction date matters.

Question 10 — Are predicted grades certain?

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: No; point predictions have errors and uncertainty.

Common mistake: Not inherent ability.

Level 2 — Calculations and Model Building

Question 11 — Split 395 records 80/20

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: 316 training and 79 test if all observations retained.

Common mistake: Validate actual rows.

Question 12 — Identify target leakage

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Using G3 as an input to predict G3.

Common mistake: Remove it.

Question 13 — Encode schoolsup

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: One-hot encode yes/no within a Pipeline.

Common mistake: Arbitrary numeric codes can mislead.

Question 14 — When fit imputers?

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Only on training folds, applied to validation/test.

Common mistake: No full-data median.

Question 15 — Find five absolute errors

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: For actual 8,10,12,14,16 and predictions 9,9,13,12,17: 1,1,1,2,1.

Common mistake: Do not sum signed errors.

Question 16 — Calculate MAE

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: 6/5=1.2 grade points.

Common mistake: Grade-point units.

Question 17 — Calculate MSE

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: 8/5=1.6 squared grade points.

Common mistake: Not ordinary points.

Question 18 — Calculate RMSE

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Square root of 1.6 ≈1.2649 grade points.

Common mistake: Do not confuse with MSE.

Question 19 — Calculate R²

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: 1−8/40=0.80 for five fictional grades.

Common mistake: Not 80% classification accuracy.

Question 20 — Compare mean baseline

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Fictional baseline MAE 2.4 vs fictional example MAE 1.2.

Common mistake: Not UCI results.

Level 3 — Evaluation and Responsible AI

Question 21 — Explain overfitting

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Poor generalization despite fitting training-specific noise.

Common mistake: Train score alone insufficient.

Question 22 — Explain underfitting

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Model too limited to capture useful relationships.

Common mistake: Not always high variance.

Question 23 — Choose evaluation scheme

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: CV on training data; untouched final test.

Common mistake: Group/time splits may be needed.

Question 24 — Identify CV leakage

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Full-data imputer or scaler fitted before folds.

Common mistake: Use a Pipeline.

Question 25 — Ridge versus forest

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Regularized linear model vs nonlinear tree ensemble; select using CV.

Common mistake: Forest not universally better.

Question 26 — Interpret actual/predicted plot

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Points on y=x are exact; above overpredict; below underpredict.

Common mistake: Read axes carefully.

Question 27 — Does importance prove a cause?

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: No, it describes model reliance under an evaluation method.

Common mistake: Correlated features complicate rankings.

Question 28 — Name fairness/privacy risks

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Bias, proxies, identification and harmful automated decisions.

Common mistake: Don’t collect private pupil records.

Question 29 — Can this model transfer globally?

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: No without external validation across new settings and grade scales.

Common mistake: Scaling by five is not validation.

Question 30 — Recommend responsible use

Show hint

Consider the prediction stage, units, original source, train/test design and whether the data are real or synthetic.

Show worked answer

Answer: Educational research only; cite source, report errors, uncertainty and no high-stakes deployment.

Common mistake: Do not rank real students.

How to make model comparisons scientifically stronger

Once the basic pipeline works, a more advanced student can test a small, predeclared hyperparameter grid using GridSearchCV or RandomizedSearchCV, always restricted to the training partition. For example, compare a few Ridge regularization strengths or forest minimum leaf sizes under the same cross-validation scheme. Record the searched values, scoring measure and computation budget; do not choose them using held-out test scores. A single five-fold average can be unstable on a small school dataset, so inspect fold-to-fold variation as well as the mean. If observations represent repeated learners or chronological assessments, the validation splitter must reflect the intended deployment population and prediction stage. Random K-fold is not automatically an appropriate substitute for group-based or forward-in-time evaluation.

For reproducibility, preserve the exact code version, environment, selected data file, random seed, feature list, CV folds, training/test indices and metric definitions. The accompanying project exports its synthetic demonstration results as JSON and a separate held-out prediction table, allowing students to reproduce the figure coordinates rather than tracing invented points from an image. If you rerun it on the official UCI file, document any difference in rows, missing values, model choice or errors. A notebook that executes correctly on fictional examples demonstrates software operation, not predictive validity on the target population. Any unexpected discrepancy should trigger an audit of inputs, source versions and preprocessing rather than a silent change to the reported figures.

Finally, separate descriptive interpretation from decision making. A residual plot can reveal a subset with large prediction errors, but it cannot tell you which intervention would help that student. Research into educational support requires a stronger evidence design, participant safeguards, appropriate comparators and transparent evaluation of possible benefits and harms. In a teaching project, the most valuable conclusion may be that a simple baseline remains difficult to outperform without later grades, or that historical data lack the timing and representativeness required for an operational early-warning system. An honest limitation is a valid scientific finding.

A final five-point model-readiness check

Before sharing your notebook, confirm five essentials rather than adding another very long on-page checklist. Source: the correct CSV, citation, history and grade scale are identified. Timing: G3 is the target and every selected input is available at its stated stage. Evaluation: preprocessing stays inside training folds, the baseline is genuine and the held-out test remains untouched until selection. Interpretation: every graph and metric names its units, population and synthetic or authentic status. Ethics: privacy, possible unequal errors, uncertainty, external validation and prohibition of high-stakes use are explained. More detailed printable checklists are included in the downloads.

Download the companion machine-learning resources

The connected Notes for SHS WordPress media library now contains the supported Excel, Google Sheets-compatible, PDF and Word files below. The ZIP package provided with the completion report includes the executed Python notebook, the original fictional CSV, validation scripts, model card, 14 figures, reproducibility README and requirements file. It does not include the original Mathematics CSV, because the official source could not be retrieved from this environment. Students may download the dataset lawfully from the UCI page and run the included program locally; doing so is necessary before they can report real UCI model performance.

Optional learning resources

For additional structured study, the public Coursera Python machine-learning course catalogue and Udemy Scikit-Learn course directory may help students compare options. These are ordinary provider discovery links, not verified affiliate-tracked URLs; no approved course-level tracking destination or promotional image was available for this post. Check the current syllabus, availability, prerequisites and pricing directly. A course cannot replace thoughtful data provenance, valid evaluation and responsible treatment of people.

Frequently asked questions

Can Python predict student grades?

It can estimate numerical grades from historical patterns, but the predictions are uncertain and not suitable for automatic consequential decisions.

Which UCI dataset does this tutorial use?

Student Performance, Mathematics file student-mat.csv, described by UCI as 395 historical records from Portuguese schools.

What is G3?

The target: final Mathematics grade on the source’s 0–20 scale.

How are G1 and G2 different?

Earlier grades from the first and second periods, available only after those periods.

Why is this a regression task?

G3 is estimated as a numerical outcome rather than a category.

What does studytime code 3 mean?

An ordinal study-time range in the source codebook, not exactly three hours.

What is target leakage?

Illegitimately using target G3 itself or information derived from it among inputs.

Why split training and test records?

To reserve observations for final evaluation after fitting and training-fold model selection.

What is a mean baseline?

A DummyRegressor that predicts the training-target mean for each observation.

How does Random Forest differ from Ridge?

A forest averages tree models, whereas Ridge is a regularized linear model.

What does an MAE of two points mean?

The mean absolute difference between predictions and observed grades is two points on the relevant scale.

Can R² be negative?

Yes. Test predictions can perform worse than the mean-reference baseline.

Were the UCI model scores verified here?

No. The original file could not be downloaded; all shown numerical model scores come from 180 fictional teaching records.

Does high feature importance prove a cause?

No. It describes model reliance under a particular setup and can be influenced by correlated predictors.

Can this model be used for admission or pupil ranking?

No. This unvalidated historical teaching project is not appropriate for high-stakes or privacy-invasive decisions.

Conclusion: training a model is not the same as trusting it

A responsible student grade prediction project begins with the research question and intended timing, not the algorithm. You must know where the data came from, what the grade scale means, whether the selected features could exist at the prediction date, and whether the training and evaluation procedures preserve genuinely unseen observations. A baseline tests the need for complexity; cross-validation supports training-only candidate selection; and MAE, RMSE, R² and residual plots reveal complementary aspects of prediction errors. The verified five-student calculation and the executed fictional Python demonstration show how these steps fit together without making unsupported claims about actual students.

The next step for independent learners is to obtain the official UCI Mathematics CSV, rerun the provided script and notebook, replace the illustrative model outputs with authentic computed values, and document whether the results change. Any comparison between stages must acknowledge that additional earlier grades become available over time. Do not extrapolate a historical model to a different national grading system without external validation, and never invite or expose identifiable pupil data to demonstrate the code. A reproducible model report should make the limits of its evidence as visible as its numerical results.

Official technical and ethical references

Related Notes for SHS Data Science lessons