Predicting Re-Exam Outcome with K-NN Using the Q5a Dataset (Student #9)

Predicting Re-Exam Outcome with K-NN Using the Q5a Dataset (Student #9)

Verified Sources
Sep 14, 2026

In this section, you’ll use your existing Q5a dataset (the same dataset you prepared in Q5a) to train a K-NN classifier and predict whether the overslept student will pass the re-exam.

We’ll treat the student record as a new query instance:

  • ID: 9
  • Cell No.: 93333-11109
  • Language: C++
  • Passed all Assignments: Yes
  • GPA: 3.0
  • Target (Passed Exam): unknown

Key idea

A k-NN classifier predicts the unknown label by finding the kk nearest neighbors in feature space and taking a vote (or average) of their labels. This requires careful preprocessing because your features include both categorical (Language, Passed all Assignments) and numeric (GPA, possibly others).

Assumption (based on typical coursework):
Your Q5a dataset contains rows with features similar to: Language, Passed all Assignments, GPA, and a target Passed Exam. If Q5a also included additional features (e.g., Cell No.), you should follow the exact same Q5a preprocessing pipeline for those features. If Cell No. is an identifier (not a meaningful predictor), it should be excluded from modeling.

type="tip" title="Pro Tip: Keep Q5a preprocessing identical" content="Whatever you did in Q5a (dropping columns, encoding categories, scaling numeric features), reuse it exactly here; otherwise the distance comparisons in K-NN become invalid."

type="warning" title="Warning: Don’t feed raw categorical text to K-NN" content="K-NN uses numeric distances. So you must convert categorical variables (Language, Passed all Assignments) to numeric form (e.g., one-hot encoding) before fitting/predicting."

Workflow to Predict Student #9 Using K-NN

  1. 1
    Step 1

    Let XX be the feature columns and yy be the target column Passed Exam. Usually you exclude identifiers like Cell No. unless Q5a explicitly used it as a predictive numeric feature.

  2. 2
    Step 2

    Convert Language (e.g., C++, Java, Python) into numeric vectors using one-hot encoding. Convert Passed all Assignments (Yes/No) into binary (e.g., Yes=1, No=0) as done in Q5a.

  3. 3
    Step 3

    Because K-NN relies on distances, scale numeric features like GPA (e.g., StandardScaler). This prevents GPA from being overwhelmed by larger-scale encoded features or vice versa.

  4. 4
    Step 4

    Fit a KNeighborsClassifier with a chosen k. Use the same train/test split you used in Q5a if that was required.

  5. 5
    Step 5

    Create a feature vector for: Language=C++, Passed all Assignments=Yes, GPA=3.0 (and any other selected features). Ensure its encoded columns match the training matrix.

  6. 6
    Step 6

    Use y^=predict(xquery)\hat{y} = \text{predict}(x_{query}). Optionally use P(y^=1xquery)=predict_proba(xquery)P(\hat{y}=1|x_{query}) = \text{predict\_proba}(x_{query}) if supported by your classifier configuration.

  7. 7
    Step 7

    Find the k neighbors and report which training rows were closest and how many of them passed/failed. The vote (or probability) determines the final prediction.

Mathematical interpretation of the K-NN decision

Let the transformed training matrix be mathbfXinmathbbRntimesd\\mathbf{X} \\in \\mathbb{R}^{n\\times d} and the query point be \\mathbf{x}_\\* \\in \\mathbb{R}^{d} after preprocessing. For a chosen distance metric (commonly Minkowski distance), compute distances to all points:

d(mathbfxi,mathbfx\*)=left(sumj=1dxijx\*jpright)1/pd(\\mathbf{x}_i, \\mathbf{x}_\*) = \\left(\\sum_{j=1}^{d} |x_{ij} - x_{\*j}|^p\\right)^{1/p}

Pick the set mathcalNk(mathbfx\*)\\mathcal{N}_k(\\mathbf{x}_\*) of the kk smallest distances. Then:

  • Majority vote rule (classification):
haty=argmaxcin0,1sumiinmathcalNk(mathbfx\*)mathbbI(yi=c)\\hat{y} = \\arg\\max_{c \\in \\{0,1\\}} \\sum_{i \\in \\mathcal{N}_k(\\mathbf{x}_\*)} \\mathbb{I}(y_i=c)

This is how K-NN decides whether the student will pass.

Practical implementation (scikit-learn style)

Below is a template that matches the workflow you’d typically implement after Q5a.

Important

Because Q5a is not included in your prompt, the code shows the structure. You should align variable names and preprocessing steps with what you did in Q5a (e.g., which columns you dropped and how you encoded).

1import numpy as np 2import pandas as pd 3 4from sklearn.compose import ColumnTransformer 5from sklearn.preprocessing import OneHotEncoder, StandardScaler 6from sklearn.pipeline import Pipeline 7from sklearn.neighbors import KNeighborsClassifier 8 9# Assume df is your Q5a dataset 10# Target column: 11target_col = "Passed Exam" 12 13# Example feature columns (adjust to match Q5a) 14categorical_cols = ["Language", "Passed all Assignments"] 15numeric_cols = ["GPA"] 16# If Q5a kept Cell No. as a numeric/meaningful feature, include it in numeric_cols. 17# Otherwise drop it from features. 18 19X = df[categorical_cols + numeric_cols] 20y = df[target_col].astype(int) # ensure 0/1 21 22preprocess = ColumnTransformer( 23 transformers=[ 24 ("cat", OneHotEncoder(handle_unknown="ignore"), categorical_cols), 25 ("num", StandardScaler(), numeric_cols), 26 ] 27) 28 29knn = KNeighborsClassifier(n_neighbors=5) # set k as decided in Q5a 30 31model = Pipeline(steps=[("preprocess", preprocess), ("knn", knn)]) 32model.fit(X, y) 33 34# Query instance for ID=9 35query = pd.DataFrame([{ 36 "Language": "C++", 37 "Passed all Assignments": "Yes", 38 "GPA": 3.0 39}]) 40 41pred = model.predict(query)[0] 42proba = model.predict_proba(query)[0][pred] # probability of predicted class 43 44print("Predicted Passed Exam:", pred) 45print("Confidence (prob of predicted class):", proba)

How K-NN decides (conceptual neighbor vote)

Illustration: among the k nearest neighbors, how many are likely to pass vs fail

From Q5a Data to Final Prediction

Load Q5a dataset

Step 1

Define XX and yy (features vs Passed Exam)."

Encode + scale

Step 2

One-hot encode Language/Assignments; scale GPA."

Fit K-NN

Step 3

Choose k and train KNeighborsClassifier."

Create query vector

Step 4

Language=C++; Assignments=Yes; GPA=3.0."

Predict + justify

Step 5

Vote among nearest neighbors; output Pass/Fail."

Common K-NN pitfalls when predicting a single student

Knowledge Check

Question 1 of 4
Q1Single choice

In K-NN classification, the predicted label is determined primarily by: