CSC 1913 Project 3 – Which penguin is that?
Nearest-neighbor classification with k-d trees
Deadline: Mon, Dec 14, 2026
Essential Information
Pacing and Planning
This is a three-week assignment. It is shorter in lines of code than Project 2, but it asks for more thinking per line.
This writeup is deliberately different from the ones you’ve seen so far. Earlier projects told you, often step by step, how to build each method. This one mostly tells you what each class must do (its contract) and why, and leaves the how to you. Expect to spend real time with paper and pencil:
- drawing trees
- tracing your algorithm on small examples
- convincing yourself that it is correct before you type it
That planning is the assignment, not a detour from it.
A suggested schedule:
| Week | Goal |
|---|---|
| 1 | Read this whole document and the code provided. KDTree insert / size / height / contains done. Start drawing nearest-neighbor examples by hand. |
| 2 | nearest working (correct first, then efficient). kNearest designed and working. |
| 3 | KNNClassifier, run ClassifierMain, write the analysis, clean up style. |
Deadline
The deadline for this assignment is Mon, Dec 14, 2026.
Late work is not generally accepted on projects – there will be a brief grace period on gradescope to help mitigate technical issues – but beyond this grace period late work will not be accepted without an exception.
To request an extension, please email course staff before the deadline, and clearly state both the reason an extension is needed/warranted, and the length of the extension you are requesting.
Files
You will write the following files:
KDNode.java– one node of a k-d tree. You design this class.KDTree.java– a k-d tree: a binary search tree for multi-dimensional points that can quickly find the points nearest to a query.KNNClassifier.java– a k-nearest-neighbor classifier that predicts a penguin’s species from its measurements.analysis.txt– your written answers to the analysis questions.
Other important restrictions
Individual project – Unlike labs, where partner work is allowed, this project is an individual assignment. This means that you are expected to solve this problem independently relying only on course resources (zybook, lecture, office hours) for assistance. Inappropriate online resources, or collaboration at any level with another student will result in a grade of 0 on this assignment, even if appropriate attribution is given. Inappropriate online resources, or collaboration at any level with another student without attribution will be treated as an incident of academic dishonesty.
To be very clear, you can ask other students questions only about this document itself (“What is Adriana asking for in the KDTree section?”). Questions such as “how would you approach method X”, “How are you storing the k nearest points?”, or “I’m stuck on nearest, can you give me a pointer” are considered appropriate only if no specific code is exchanged. Likewise, you are free to search for information about the java programming language and included java classes, but searching for information about the problem in this project (e.g. “k-d tree nearest neighbor java”) is not allowed.
Allowed java classes: You are not allowed to use any of the pre-built java classes except those we’ve explicitly discussed in class such as Scanner, Random, String, Math, Arrays, etc. If you are unsure if a java class would be allowed here you should ask. Using unapproved java classes can lead to failing this assignment.
Specific examples of BANNED java classes:
- Any subclass of
java.util.List(ArrayList,LinkedList, …) - Any subclass of
java.util.Map(HashMap,TreeMap, …) - Any subclass of
java.util.Set(HashSet,TreeSet, …) java.util.PriorityQueueandjava.util.Collections
Every data storage task in this project can be done with arrays and nodes you build yourself. Figuring out how to do that is part of the assignment.
Introduction
Between 2007 and 2009, Dr. Kristen Gorman and the Palmer Station Long Term Ecological Research program measured hundreds of penguins on three islands in Antarctica’s Palmer Archipelago. For each bird they recorded its species and four body measurements: bill length, bill depth, flipper length, and body mass.
Suppose a researcher measures a new penguin but isn’t sure of the species. Can a program tell them? This is a classification problem: given the measurements (the features) of something new, predict which category (the label) it belongs to. Classification is one of the most common tasks in statistics and machine learning. Examples include spam filters, medical diagnosis, handwriting recognition, and credit scoring.
Look at the plot above. If someone handed you a new penguin with a 225 mm flipper and a mass of 5500 g, you’d probably guess Gentoo. You wouldn’t need a formula: the penguins near that spot on the plot are almost all Gentoo.
That intuition is the k-nearest-neighbor (kNN) algorithm:
To classify a new point, find the k training points closest to it, and let them vote on the label.
The algorithm is simple, but doing it well raises three questions. This project answers each one with a class you build:
- What does “closest” mean when features are measured in different units? Body mass is in the thousands of grams and bill depth is around 17 mm. A raw distance would be almost entirely body mass. →
Scaler(provided to you) - How do we find the nearest points quickly? Checking every training point works for 342 penguins, but not for millions of data points. →
KDNodeandKDTree - How do we turn neighbors into a prediction, and how do we know if it’s any good? →
KNNClassifier
Learning Goals
- Design and build a tree data structure in which every node stores an array (a point in k-dimensional space).
- Design your own internal representation for a class from its public contract.
- Reason about when part of a tree can be safely skipped, and measure the efficiency gained by skipping it.
- Apply basic statistics to real data: means, standard deviations, z-scores, accuracy, and confusion matrices.
- Interpret experimental results and explain them in writing.
Background
Data points
Each penguin is a provided DataPoint: an array of double features plus a String label. For the penguin data the features are, in order:
| index | feature |
|---|---|
| 0 | bill length (mm) |
| 1 | bill depth (mm) |
| 2 | flipper length (mm) |
| 3 | body mass (g) |
and the label is "Adelie", "Chinstrap", or "Gentoo".
We treat a data point with \(d\) features as a point in \(d\)-dimensional space. The distance between two points \(p\) and \(q\) is the ordinary (Euclidean) distance:
\[\text{dist}(p, q) = \sqrt{\sum_{i=0}^{d-1} (p_i - q_i)^2}\]
Read DataPoint.java before you start. Note the difference between getFeature(i) (fast) and getFeatures() (makes a copy).
Standardization (z-scores)
To keep one feature from dominating the distance just because of its units, we standardize each feature. We replace each value \(x\) with its z-score: how many standard deviations it is above or below that feature’s mean.
\[z = \frac{x - \bar{x}}{s} \qquad \bar{x} = \frac{1}{n}\sum_{j=1}^{n} x_j \qquad s = \sqrt{\frac{1}{n-1}\sum_{j=1}^{n}(x_j - \bar{x})^2}\]
Here \(s\) is the sample standard deviation (divide by \(n - 1\)). This is the same value R’s sd() returns. After standardizing, every feature has mean 0 and standard deviation 1, so each one contributes on a comparable scale.
One important statistical rule: the mean and standard deviation are computed from the training data only. The same transformation is then applied to every new point we classify. (Think about why. You’ll be asked about it in the analysis.)
k-d trees
A k-d tree (“k-dimensional tree”) is a binary search tree for points with several coordinates. In an ordinary BST every node compares on the same thing (the key). A k-d tree rotates which coordinate it compares on as you go down the tree:
- A node at depth 0 (the root) compares on coordinate 0.
- A node at depth 1 compares on coordinate 1.
- … and a node at depth \(\text{depth}\) compares on coordinate \(\text{depth} \bmod d\).
The coordinate a node compares on is its splitting axis. The rule is the same BST rule you already know, applied to the splitting axis only. For a node at depth \(t\) with splitting axis \(a = t \bmod d\):
- every point in its left subtree has coordinate \(a\) less than the node’s coordinate \(a\),
- every point in its right subtree has coordinate \(a\) greater than or equal to the node’s coordinate \(a\).
For example, inserting the 2-dimensional points
f(7,2), b(5,4), c(9,6), a(2,3), d(4,7), e(8,1)
in that order produces this tree:
Trace each insertion yourself until you can reproduce this tree.
Geometrically, each node cuts its region of space in two with a line (or a plane, or a hyperplane in more dimensions). f splits the whole plane at \(x = 7\). b splits the left half at \(y = 4\). Each subtree is responsible for one rectangular region.
The nearest-neighbor problem
Given a query point \(q\), which stored point is closest to it?
The obvious answer is to compute the distance from \(q\) to every point and keep the smallest. That is \(O(n)\) per query. It is always correct, so it’s a good way to check your answers, but it is not acceptable as your final KDTree solution.
The k-d tree makes it possible to skip whole subtrees without ever looking at them. How to do that safely is the central design problem of this project, and it’s yours to solve. Some questions to work through on paper first (this is the “planning” part of your three weeks):
- If you walk down the tree as if you were inserting \(q\), is the last node you reach always the nearest neighbor? Try to construct a counterexample with the six points above. (Hint: try \(q = (7.2, 4.5)\).)
- Suppose you’re at a node whose splitting axis is \(a\), and the query is on the left side of the splitting line. Which side should you search first, and why might that order matter for efficiency?
- After searching one side, you know the closest point found so far and its distance \(r\). What is the closest that any point on the other side of the splitting line could possibly be to \(q\)? When does that let you skip the other side entirely?
- What changes when you want the \(k\) closest points instead of just one? What plays the role of “\(r\)” now?
Draw pictures. A circle of radius \(r\) around \(q\) and a splitting line make the answer to the third question visible.
Formal Requirements
The contracts below are what the autograder and the graders will check. Anything not specified (private fields, helper methods, how you store things internally) is your decision. You will be graded partly on making good decisions.
Where a method’s input is invalid, throw the exception listed. IllegalArgumentException means “you called this with a bad argument.” IllegalStateException means “this object isn’t ready for that call yet.”
Scaler (provided to you)
Learns the mean and sample standard deviation of each feature from a data set, then converts feature arrays to z-scores. Things to keep in mind:
transformnever modifies its input.transform(DataPoint p)callsp.getFeatures(), which returns a copy, and builds a newDataPointwith the scaled features and the same label. The original point is left unchanged.
When your KNNClassifier standardizes, the training points you pass in stay in their original units, and the tree stores separate, transformed copies.
KDNode
Represents one node of your k-d tree. There is no required public interface. Design the fields, constructor(s), and methods that make your KDTree clean. All fields must be private.
Keep in mind that an instance of this class will exist for every point in the tree, so don’t store things you don’t need. Anything you can compute cheaply from the node’s position in the tree is a candidate for not storing.
KDTree
A k-d tree of DataPoints, following the definition in the Background section exactly:
- A node at depth \(t\) splits on axis \(t \bmod d\).
- Points that are equal on the splitting axis go right.
- Duplicate points are allowed.
| Member | Contract |
|---|---|
public KDTree(int dimensions) |
An empty tree for points with that many features. Throws IllegalArgumentException if dimensions < 1. |
public int getDimensions() |
The number of dimensions. |
public void insert(DataPoint p) |
Adds p to the tree. Throws IllegalArgumentException if p has the wrong number of features (and the tree is unchanged). |
public int size() |
Number of points stored. \(O(1)\). |
public int height() |
Number of nodes on the longest root-to-leaf path. An empty tree has height 0 and a single node has height 1. |
public boolean contains(double[] point) |
true if some stored point equals point on every coordinate. Should only visit nodes along one root-to-leaf path. |
public DataPoint nearest(double[] query) |
The stored point closest to query, or null if the tree is empty. If several points are equally close, any of them is acceptable. |
public DataPoint[] kNearest(double[] query, int k) |
The k stored points closest to query, sorted closest first (you should consider creating an array of size k that you insert the DataPoints – sorted by distance – as you traverse the tree). If the tree holds fewer than k points, returns all of them (still sorted). Throws IllegalArgumentException if k < 1. |
public long getDistanceCount() |
The total number of point-to-query distance computations performed by nearest and kNearest since the tree was created or last reset. |
public void resetDistanceCount() |
Sets the distance count back to 0. |
contains, nearest, and kNearest throw IllegalArgumentException if the query array has the wrong length.
About the distance count: every time your code computes the distance between a stored point and the query, the count must go up by one. The easy way to guarantee this is to put all distance computation in a single private helper method that increments the counter. insert and contains don’t compute distances. Graders will check that the counter is honest.
Hints and constraints:
- You’ll never need the actual distance, only comparisons between distances. Is there a cheaper quantity that orders points the same way?
kNearestneeds to keep track of “the best \(k\) found so far” while it searches. Designing that bookkeeping (with arrays, no banned classes) is part of the assignment. Think about which operations it needs to support, and how often each one happens.
Efficiency goals (checked by the autograder with getDistanceCount):
neareston 20,000 random 2-D points: fewer than 100 distance computations per query on average. A linear scan uses 20,000.kNearestwith \(k = 10\) on 20,000 random 3-D points: fewer than 500 distance computations per query on average.
A correct but un-pruned search will pass every correctness test and fail only these. So get a correct (even slow) version working first, then make it efficient.
KNNClassifier
| Member | Contract |
|---|---|
public KNNClassifier(int k, boolean standardize) |
A classifier that votes with k neighbors and, if standardize is true, standardizes features with a Scaler. Throws IllegalArgumentException if k < 1. |
public KNNClassifier(int k) |
Same as KNNClassifier(k, true). |
public void train(DataPoint[] data) |
Builds the model from the training data. If standardizing, the Scaler is fit on this data and the tree stores transformed points. Calling train again replaces the old model. Throws IllegalArgumentException if data is empty. Add each DataPoint in data to the tree instance variable. Keep all unique labels in training data in an instance variable |
public String[] getLabels() |
The distinct labels in the training data, in alphabetical order. Should be created/updated in the train method. Just method should just return the labels instance variable |
public String predict(double[] features) |
The majority label among the k nearest training points. If the vote is tied, return the tied label whose neighbor is closest to the query. Must not modify features. |
public double accuracy(DataPoint[] testData) |
The fraction of testData whose predicted label equals its actual label. |
public int[][] confusionMatrix(DataPoint[] testData) |
A square matrix m where m[r][c] counts test points whose actual label is getLabels()[r] and whose predicted label is getLabels()[c]. Throws IllegalArgumentException if a test point’s label was not in the training data. |
getLabels, predict, accuracy, and confusionMatrix throw IllegalStateException before train has been called.
A confusion matrix shows which mistakes a classifier makes, not just how many. The diagonal holds the correct predictions. For example, a large value at row Chinstrap, column Adelie means Chinstraps are often mistaken for Adelies.
Your vote counting must not use banned classes. Decide how to map a label (String) to a position in your counting array.
Running the experiments
Once everything works, run the provided ClassifierMain. It:
- splits the 342 penguins into a training set (80%) and a test set (20%) using a fixed random seed,
- prints the training-set mean and standard deviation of each feature,
- prints test accuracy for \(k = 1, 3, \ldots, 25\) using all four features, with and without standardization,
- repeats the accuracy experiment using only flipper length and body mass,
- prints a confusion matrix, and
- benchmarks your
KDTreeon 100,000 and 5,000 random points, and on 5,000 points inserted in sorted order.
With a correct implementation, ClassifierMain should finish in well under a second. You are encouraged to modify it (it is not submitted) to run your own experiments.
Written Analysis
Submit analysis.txt answering the questions below. Keep each answer to a short paragraph (a few sentences, plus a number or small table where helpful). Use your actual program output. Graders are looking for reasoning, not for the “right number”.
- Units matter. Compare the raw and standardized accuracy columns from part 3. Using the means and standard deviations from part 2, explain why the unstandardized classifier does worse. Which feature dominates the raw distance, and why?
- Train only. We fit the
Scaleron the training data only, not on all 342 penguins. What would be wrong with fitting it on all the data before splitting? (Think about what the test set is supposed to simulate.) - Choosing k. Using the two-feature results from part 4, describe how accuracy changes as \(k\) grows. Explain in terms of the scatter plot at the top of this document what goes wrong when \(k\) is very small, and what would go wrong if \(k\) were very large (e.g. \(k\) = the size of the training set).
- Reading the confusion matrix. Which species does the two-feature classifier confuse, and which does it almost never get wrong? Connect your answer to the scatter plot.
- Trust the number? The test set has only 69 penguins. How much does the accuracy change if a single prediction flips? Modify
ClassifierMainto use a few different shuffle seeds and report how much the “best \(k\)” moves around. What does this suggest about drawing conclusions from one train/test split? - Pruning. Report the average distance computations per query for each benchmark in part 6. In your own words, explain the rule your
nearestuses to skip a subtree and why skipping it can never give a wrong answer. - Insertion order. Explain the height and distance-count results for the sorted benchmark. Draw (or describe) the shape of the tree. What does this tell you about the worst-case running time of
nearest? - Your design. Describe how your
kNearestkeeps track of the best \(k\) points so far, and give the big-O cost of adding a new candidate in terms of \(k\). What else did you consider, and why did you choose this?
Optional challenge (extra credit, up to 5 points)
Question 7 shows that insertion order can ruin a k-d tree. Add a method public static KDTree build(DataPoint[] points, int dimensions) that builds a balanced tree from a whole array at once. At each level, choose the point that splits the current subset in half along that level’s axis. Report in your analysis how the height and distance count on the sorted benchmark change. Your tree must still obey the “equal goes right” rule, so think carefully about how you choose the split point when coordinates repeat.
Files to download
- DataPoint.java – one labeled observation. Provided, do not modify.
- PenguinData.java – loads
penguins.csv, plusshuffle,slice, andselectFeatureshelpers. Run itsmainto check the data file is in the right place. Provided, do not modify. - penguins.csv – 342 penguins (the 2 rows with missing measurements are removed). Place it in your IntelliJ project folder, not in the
srcfolder. - ClassifierMain.java – runs the experiments for the written analysis.
- Scaler.java – Standardizes features to z-scores. Computes the mean and standard deviation of each feature in a data set and converts features to z-scores.
- ScalerTest.java – for your reference, so you see how its methods are called.
- KDTreeTest.java, KNNClassifierTest.java – tests that mirror the autograder. Run each one’s
main. - Assert.java – a helper class used by the test files.
The provided tests are a starting point, not a guarantee. Passing all of them does not mean your code is correct or efficient. Write your own small examples, especially for nearest and kNearest, where you can work out the answer by hand.
If you wrote a recursive method that is causing a StackOverflow error, you might consider writing a loop instead.
Submission and grading
Submit KDNode.java, KDTree.java, KNNClassifier.java, and analysis.txt to Gradescope.
A rough breakdown on points is as follows:
- 27 points for the autograded tests (including the efficiency goals)
- 10 points for code style
- 19 points for
KDNodeandKDTree– including design ofKDNode, thekNearestbookkeeping - 24 points for
KNNClassifier - 20 points for the written analysis
Data citation: Gorman KB, Williams TD, Fraser WR (2014). Ecological sexual dimorphism and environmental variability within a community of Antarctic penguins (genus Pygoscelis). PLoS ONE 9(3): e90081. Data distributed in R’s datasets package as penguins.