Sklearn Workflow (Cheatsheet)

Context: FIT1043_MOC Β· Weeks 5–7 modelling in ONE skeleton Β· code canon in the LAB notebooks (30_Projects/FIT1043_Labs/Week7-Classification-sklearn.ipynb, Week7-Clustering-KMeans.ipynb) Β· applied depth in Scikit-learn Classification and Clustering.

Unit-specific: FIT1043's linear regression is done with scipy linregress, not sklearn (Week 5 lab) β€” see Linear Regression in Python (scipy). sklearn here is for classification and clustering (Week 7). The sklearn regression rows below are the standard API for reference/other units.

Quick Revision

  • 🎯 Objective: every sklearn model, same four verbs βž” Estimator() β†’ fit(X_train, y_train) β†’ predict(X_test) β†’ evaluate.
  • ⚑ Key Constraint: shapes β€” (2-D, even for one feature via df.loc[:, ['weight']]), (1-D); most beginner errors are a 1-D .

🧩 Workflow Anatomy (execution order)

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X = df.iloc[:, [0, 1]].values       # (N, D) β€” always 2-D (or df.loc[:, ['a','b']])
y = df.iloc[:, 2].values            # (N,)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
 
sc = StandardScaler()               # scale AFTER splitting
X_train = sc.fit_transform(X_train) # fit on TRAIN only
X_test  = sc.transform(X_test)      # transform (never fit) TEST
 
model = SomeEstimator()             # swap this line per task ↓
model.fit(X_train, y_train)         # learn parameters from TRAIN only
y_pred = model.predict(X_test)      # apply to UNSEEN data

Why split βž” evaluating on training data rewards memorisation β€” the overfitting trap; test error is the honest estimate.

πŸŽ› Estimator Swap Table

TaskEstimator lineEvaluate withConcept note
linear regression (FIT1043)linregress(x, y) (scipy.stats) β†’ slope/intercept/r/p/std_err, plot the lineLinear Regression in Python (scipy)
classification (tree)DecisionTreeClassifier(criterion='entropy', random_state=0) (sklearn.tree)confusion matrix + metricsDecision Trees and Regression Trees
classification (forest)RandomForestClassifier(n_estimators=20, criterion='entropy') (sklearn.ensemble)confusion matrixRandom Forest
clustering (no labels!)KMeans(n_clusters=k, init='random') (sklearn.cluster)labels_, cluster_centers_; no y in fit(X)k-means Clustering
(other units)LinearRegression() / PolynomialFeatures(degree=k) (sklearn.linear_model)MSE, Linear and Polynomial Regression

πŸ“ Evaluation Calls

TaskMicro-syntaxReads as
regression errormean_squared_error(y_test, y_pred)mean of squared residuals β€” the loss regression minimises
fit qualityr2_score(y_test, y_pred) or model.score(X_test, y_test)proportion of variance explained
confusion matrixconfusion_matrix(y_test, y_pred)rows=actual, cols=predicted βž” TP/FP/FN/TN
accuracyaccuracy_score(y_test, y_pred)correct Γ· total β€” misleading on imbalance
full reportclassification_report(y_test, y_pred)precision, recall, F1 per class
k-means labelsmodel.labels_ Β· centroids model.cluster_centers_assignment after convergence

✍️ Practice

⚠️ Common Mistakes

  • πŸ’‘ 1-D X crash βž” a single-bracket df['w'] is ; estimators need 2-D β€” use df.loc[:, ['w']] or df.iloc[:, [0]].
  • πŸ’‘ Fitting on everything βž” split FIRST; any statistic learned from test rows (even StandardScaler) is leakage β€” fit_transform train, transform test.
  • πŸ’‘ Accuracy on imbalance βž” 95% accuracy on a 95/5 class split is the majority-class baseline, not skill.
  • πŸ’‘ Set random_state βž” without it, splits/forests/KMeans seeds change every run and results aren’t reproducible.