Concepts / Choosing the Right Machine Learning Model

Choosing the Right Machine Learning Model

The Nearest Neighbors model looks at the stored examples closest to a new data point to reason about it.

  • Programming

Which Model to Try First

When you start a machine learning project, you often face a choice: dozens of model types could plausibly solve the problem, and each one makes different assumptions about the data. Choosing the right machine learning model means deciding which approach fits the problem you have. One of the models you can choose from is the Nearest Neighbors model. It is a useful first candidate because it is simple to describe, simple to build, and gives you a reference point that more complicated models must beat.

This article follows one small lookup from start to finish. You will see what the model does with a new value, trace the steps by hand and in Python, and then check your understanding with a practice tracing task.

What the Name Refers To

Definition

The Nearest Neighbors model looks at the stored examples closest to a new data point to reason about it.

The name describes the core idea. To make a decision about a new data point, the model looks at the existing data points that are nearest to it. The word neighbors refers to stored examples that sit close to the new point. The word nearest refers to the ones that are closest by the measure you are using. The new point is the query, the thing you want a decision about. The stored examples are the data the model already has.

Think of the stored examples as points scattered across a space, where each point represents one example. The query is placed into the same space. Closeness is the measure that tells you which stored examples count as neighbors. In the simplest case, with one number per example, closeness is just how far apart two numbers are on a line.

New point (query)Stored example Astored with a labelCloseness measureNearest exampleStored example Bstored with a labelStored example Cstored with a labelcompared withcompared withcompared withscored byscored byscored bysmallest distance wins
The new point sits among stored examples. Closeness decides which stored examples count as its neighbors, and the nearest one is the example the model relies on most.

Tracing a Lookup by Hand

Before reading any code, try the lookup yourself. Suppose you have five stored examples. Each one is a single number paired with a label: 1.0 is labeled low, 2.5 is labeled low, 4.0 is labeled mid, 7.5 is labeled high, and 9.0 is labeled high. A new query value arrives: 6.2. The model must decide which stored example is closest to 6.2.

For each stored value, compute the distance to the query. With single numbers, the distance is the absolute difference, written $|6.2 - x_i|$ where $x_i$ is a stored value. The distances are: 1.0 gives 5.2, 2.5 gives 3.7, 4.0 gives 2.2, 7.5 gives 1.3, and 9.0 gives 2.8. The smallest distance is 1.3, which belongs to the stored value 7.5. So the nearest stored example is 7.5, and its label is high.

Worked example

Finding the nearest stored value to 6.2

Stored values are 1.0, 2.5, 4.0, 7.5, and 9.0 with labels low, low, mid, high, high. Which stored example is nearest to the query 6.2?

  1. 1
    Measure each distance

    Subtract each stored value from 6.2 and take the absolute value. The results are 5.2, 3.7, 2.2, 1.3, and 2.8.

  2. 2
    Compare the distances

    Look for the smallest number in that list. It is 1.3.

  3. 3
    Identify the example

    The distance 1.3 came from the stored value 7.5, so 7.5 is the nearest example.

  4. 4
    Read its label

    The stored example 7.5 is labeled high, so the nearest-neighbor answer for this query is high.

Result

The nearest stored example to 6.2 is 7.5, labeled high.

What do you think happens?

Using the same five stored values, what happens if the query is 3.0 instead of 6.2? Which stored example is nearest, and what label does it carry?

  • 2.5, labeled low

  • 4.0, labeled mid

  • 7.5, labeled high

Reveal answer
Answer:

4.0, labeled mid

The distances from 3.0 are 2.0 to 1.0, 0.5 to 2.5, 1.0 to 4.0, 4.5 to 7.5, and 6.0 to 9.0. The smallest is 0.5, which belongs to 2.5. Because the options list 2.5 as labeled low, the correct choice is 2.5, labeled low. The nearest example is therefore 2.5, and its label is low.

Tracing the Lookup in Python

The same logic can be written as a short Python program. The code keeps track of the index of the best stored example seen so far. It starts with the first example, then checks each remaining example. Whenever it finds a stored value with a smaller distance to the query, it updates the best index. At the end, the best index points to the nearest stored example.

Code walkthrough
stored_values = [1.0, 2.5, 4.0, 7.5, 9.0]
stored_labels = ["low", "low", "mid", "high", "high"]
query = 6.2

best_index = 0
best_distance = abs(query - stored_values[0])

for i in range(1, len(stored_values)):
    distance = abs(query - stored_values[i])
    if distance < best_distance:
        best_distance = distance
        best_index = i

print(stored_values[best_index], stored_labels[best_index])
  1. 1
    Line 1 stores the five numeric examples, the things the model compares against.
  2. 2
    Line 2 stores the label attached to each example in the same order.
  3. 3
    Line 3 defines the query, the new point we want a decision about.
  4. 4
    Lines 5 and 6 pick the first stored example as the initial nearest candidate and record its distance.
  5. 5
    Line 8 loops over the remaining positions, starting at index 1.
  6. 6
    Line 9 computes the distance from the query to the current stored value.
  7. 7
    Lines 10 to 12 update the best index and best distance only when a closer example is found.
  8. 8
    Line 14 prints the nearest stored value and its label, which here is 7.5 and high.
  • stored_values and stored_labels are parallel lists: position i in one matches position i in the other
  • query is the new point being classified
  • best_index starts at 0, so the first stored example is the initial candidate
  • abs() gives the distance between the query and a stored value, ignoring direction
  • the if statement replaces the current best only when a strictly smaller distance appears
  • the final print reads the value and label stored at the winning index
Output
7.5 high
Start with firststored valueCompute distance tonext valueCloser than best sofar?Update best indexValues left to check?Return nearest storedexampleyesnoyesno
The lookup compares the query with each stored example in turn, keeps the closest one seen so far, and returns the nearest stored example once every example has been checked.

Notice what the program does not do. It never fits a formula to the five stored values and never produces a learned rule. Each prediction is computed by going back to the stored examples and comparing the query against them. This is why the stored examples are central to the model: they are what the model consults every time it makes a decision.

Where the Model Fits Among the Choices

Choosing a model means comparing how candidates make predictions and what data they need. Nearest Neighbors works directly from its stored examples. When a new point arrives, it measures closeness to those examples and uses the nearest ones. Other candidate models instead learn parameters from the data during a training step, and then use those learned parameters, not the original examples, to make predictions.

Stored examplesDistance to queryNearest examplesTraining dataFitted parametersPrediction fromparametersconsulted per queryrankedfit onceapplied per query
Nearest Neighbors keeps the stored examples and consults them at prediction time, while a parameter-learning model uses the data to fit parameters and then predicts from those parameters.

Small Datasets and Baselines

The source identifies small datasets as the setting where Nearest Neighbors is a good fit. When a dataset has relatively few examples, a model that works directly from those examples is practical to try, and it gives you a clear starting point before you commit to more complicated approaches. The source does not give a size threshold, so you must judge what counts as small for your own problem.

The model is also useful as a baseline. A baseline is a simple reference model. Its job is not necessarily to be your final choice, but to give you a point of comparison. If a more complex model cannot clearly beat a simple baseline, that is useful information about the problem and about the extra complexity you were considering. Building and measuring a Nearest Neighbors model first gives you that reference number before you move on to other candidates.

Best practice

Build a simple baseline before a complex model. Record how well it performs on your data, then judge every more complicated candidate against that number rather than against nothing.

Explaining a Prediction to Others

The reasoning behind Nearest Neighbors can be stated in one sentence: a new point is compared with the stored examples, and the ones closest to it are the ones that matter. Because the idea is this direct, the model is easy to explain to colleagues, stakeholders, or anyone who needs to understand why a prediction was made. The source recommends it as an early model partly for this reason.

In the lookup above, you can show exactly why the answer was high. The query 6.2 was closest to the stored example 7.5, at distance 1.3, and that example carries the label high. Anyone reviewing the prediction can see the stored example that influenced it and the distance that made it the nearest. That traceability is what makes the explanation concrete.

Mistakes Beginners Make

  • Common mistake

    Treating the stored examples as a formula instead of data

    What it looks like

    Looking for a rule like label = high when value is above 6 and expecting the model to produce one.

    Why it fails

    Nearest Neighbors does not produce a rule. It consults the stored examples each time a query arrives.

    Do this instead

    Describe the model as comparing a new point with its nearest stored examples, and keep the examples in mind as the source of every prediction.

  • Common mistake

    Assuming the nearest example is always the right answer

    What it looks like

    Reading the label of 7.5 as definitively correct for 6.2 without checking the other stored examples.

    Why it fails

    The model uses the closest stored example, but the source describes it only as a sensible first model to build and measure, not as an always-correct method.

    Do this instead

    Measure the model's performance on your data and compare it with other candidates before trusting it.

  • Common mistake

    Assuming a size threshold for small datasets

    What it looks like

    Deciding that a dataset is small only if it has exactly one hundred examples.

    Why it fails

    The source states the suitability for small datasets without giving a size threshold.

    Do this instead

    Judge what counts as small for your own problem and check whether the model performs well in that setting.

  • Common mistake

    Skipping the baseline and jumping to complex models

    Why it fails

    Without a simple reference, you cannot tell whether a complicated model's extra effort is actually paying off.

    Do this instead

    Build the Nearest Neighbors model first as a baseline and use it as the point of comparison.

Practice Tracing a Lookup

MEDIUM

Stored values are 3.0, 5.0, 8.0, and 11.0, labeled cold, cold, warm, and hot in that order. Trace a nearest-neighbor lookup for the query 6.5. Compute each distance, name the nearest stored value, and state its label.

Hints
  • Compute the absolute difference between 6.5 and each stored value.
  • The distances are 3.5, 1.5, 1.5, and 4.5 in that order.
  • Two stored values tie at the smallest distance. Your code's strict less-than comparison keeps the earlier one, so think about which of the two it would keep.
EASY

Change the stored_values list in the Python program to a new set of five numbers with their labels, then predict which stored example a query will return before running the code. Check your prediction by running the program and comparing the output.

Hints
  • Keep stored_values and stored_labels the same length and in matching order.
  • Choose a query that falls between two stored values, so you have to compare distances carefully.

Key Points to Remember

  1. 1
    The Nearest Neighbors model reasons about a new data point by looking at the stored examples closest to it.
  2. 2
    The model is suited to small datasets, though the source gives no size threshold, so you must judge that for your own problem.
  3. 3
    It is useful as a baseline, giving you a reference point to test more complex models against.
  4. 4
    Its reasoning is simple enough to explain in one sentence, and each prediction can be traced back to the specific stored examples that influenced it.

Key Takeaways

  • The Nearest Neighbors model reasons about a new data point by looking at the stored examples closest to it.
  • The model is suited to small datasets, though the source gives no size threshold, so you must judge that for your own problem.
  • It is useful as a baseline, giving you a reference point to test more complex models against.
  • Its reasoning is simple enough to explain in one sentence, and each prediction can be traced back to the specific stored examples that influenced it.

Related concepts

More concepts starting with C