Model-Based vs Instance-Based Learning and Train–Test Splits — Day 3

Conceptual illustration of a small house beside a curved ribbon and a magnifying glass over example-house cards.
Conceptual illustration: learning a pattern and comparing examples are different ways to make predictions.

Day 03 · Learn, compare, evaluate

Model-based vs instance-based learning.

Learn a pattern or compare nearby examples. Understand both approaches, read the maths and test them fairly with complete Python code.

Start the lesson

By INGOAMPT · Originally published 2 July 2024
Expanded and technically reviewed 14 November 2026 · About 30 minutes

Conceptual illustration of a small house beside a curved ribbon and a magnifying glass over example-house cards.
Conceptual illustration of learning a pattern and comparing examples; not a data plot.

Understand the differenceCompare learned relationships and stored neighbors.

Make the maths readableFollow predictions, losses, distances and worked calculations.

Check a fair comparisonRun two methods on the same held-out examples.

In this lesson

Two ways to learn, one need for a fair test

Model-based learning uses a learned representation to predict. Instance-based learning predicts by comparing a new case with retained examples. Linear regression and k-nearest neighbors, or k-NN, make the difference concrete. Both are machine learning methods. Both can make useful predictions. Both can also give misleading results when evaluated on the wrong data.

One distinction matters from the start: an instance-based learner is not simply a trained instance of a model class. A fitted linear-regression object is an instance of a software class, but its learning approach remains model-based. Here, “instance-based” refers to using stored observations when producing a prediction.

Work through the same housing problem in two different ways, then learn how a held-out test set helps evaluate both. The comparison includes mathematical explanations, complete Python code and plots you can reproduce. All house prices here are fictional teaching data.

QuestionModel-based exampleInstance-based example
What is learned or retained?Linear regression learns coefficients describing a relationship.k-NN retains training examples and may build a search structure.
How is a prediction made?Apply the learned relationship to the new features.Find nearby training examples and combine their target values.
What affects the result?Features, model assumptions, capacity and fitting choices.Features, scaling, distance metric, neighbor count and weighting.
What must be evaluated?Performance on data excluded from fitting and model selection.The same: retained training examples must not leak into the test set.

These are useful categories, not a universal ranking. A compact regression model can predict quickly, while a large neural network can be expensive. Neighbor search can use different algorithms and indexes. Choose an approach using its actual task performance, resource needs and maintenance requirements.

Model-based learning: learn a relationship

In model-based learning, training produces a representation of the relationship between inputs and the desired output. For a supervised prediction task, each training example contains features and a target. The fitting procedure uses those examples to estimate the model’s parameters or structure.

Consider a fictional housing dataset. The inputs might be floor area, number of bedrooms and location; the target is the recorded sale price. A linear-regression model estimates a coefficient for each represented feature and an intercept. For a new house, it applies those learned values to the new feature vector.

  1. Prepare training examples. Check the units, missing values and meaning of each column. A location name is a category, not automatically a meaningful numerical distance.
  2. Fit the relationship. Ordinary least squares selects coefficients to minimise the sum of squared residuals on the training data.
  3. Predict on new inputs. Apply the same feature preparation and the fitted coefficients to houses excluded from training.

With one feature, a linear relationship can be drawn as a line. With several features, the fitted relationship is a plane or higher-dimensional surface. A two-dimensional picture of price against area cannot show the contribution of every bedroom and location feature at once.

A simple fitted model may be smaller than the dataset that produced it, and its prediction calculation may be efficient. Those are practical benefits of this example, not promises about every model-based method. Decision trees retain a learned branching structure; large ensembles or neural networks can require substantial memory and computation.

The challenge is choosing a representation that captures useful patterns without memorising accidental detail. A straight line may miss a curved relationship. An unnecessarily flexible polynomial may follow noise. The scikit-learn ordinary least-squares guide explains the regression objective and important limitations such as sensitivity to correlated features.

Instance-based learning: compare with stored cases

Instance-based learning keeps examples that can be consulted when a new input arrives. In k-NN regression, the prediction is based on target values associated with nearby training examples. A uniform-weight regressor averages their targets; other configurations give closer neighbors greater influence.

For the same fictional house, k-NN might find three training houses with similar prepared features and average their recorded prices. “Similar” is a design choice. If area is measured in thousands of square feet and bedrooms range only from one to five, raw Euclidean distance can be dominated by area.

  1. Prepare the training features. Fit any scaling or category encoding using training data only.
  2. Call fit. The estimator retains the training examples and may build a neighbor-search structure. “Lazy learning” does not mean that every implementation performs no work.
  3. Query a new case. Apply the fitted preparation, locate the chosen number of neighbors and combine their target values.

The approach is intuitive and can represent nonlinear behavior without fitting one global linear equation. It can also be sensitive to irrelevant features, unusual observations, the selected distance metric and regions with few representative examples. More stored data is useful only when its quality and relevance support the task.

Prediction cost depends on the search strategy, data size and dimensionality. The scikit-learn neighbors guide describes brute-force search, KD trees and Ball trees. It is therefore too broad to say that every prediction always compares against every stored row. High-dimensional data can still make neighbor search difficult.

Memory-based methods retain data or a representation of it, which can make storage important. Adding examples also needs a defined update procedure. A fitted scikit-learn k-NN object does not automatically notice that an external dataset has changed; the application must update or refit the estimator appropriately.

Overfitting, underfitting and where deep learning fits

Overfitting: learning detail that does not travel

An overfitted model performs well on the examples used to fit it but poorly on relevant unseen examples. A high-degree polynomial can bend through training noise. In k-NN, a very small neighbor count can make predictions sensitive to individual observations. Neither problem is diagnosed from training performance alone.

For a sufficiently represented training observation, one-neighbor regression can return that observation’s own target. That training result is not a fair estimate of future performance. Duplicate or near-duplicate records can make the same problem appear in a supposedly separate test set.

Possible remedies include simpler models, appropriate regularisation, better data, feature selection and choosing hyperparameters with validation or cross-validation. Early stopping is useful for applicable iterative training procedures; it is not a generic switch for ordinary least squares or a stored-neighbor regressor.

Underfitting: missing a useful relationship

An underfitted approach cannot capture an important pattern with its current features and configuration. A straight line may miss a strongly curved trend. A k-NN configuration with a very large neighborhood may average away meaningful local variation.

Possible improvements include more informative features, an appropriate model family, enough training for an iterative algorithm and a better choice of neighborhood or weighting. These are hypotheses to evaluate, not automatic fixes. Adding noisy features can worsen results, and training longer cannot make a linear model express every nonlinear relationship.

Observed problemQuestions to investigatePossible response
Good training score, weak validation scoreToo much capacity, leakage, few representative examples or a changed distribution?Correct the split first; then assess regularisation, simpler models or more suitable data.
Weak training and validation scoresMissing features, an unsuitable model, implementation errors or incomplete optimisation?Check the pipeline and baseline, then test an appropriate increase in useful capacity.
Unstable neighbor predictionsIs k too small? Are feature scales or irrelevant columns distorting distance?Tune k, weighting and relevant preprocessing inside validation or cross-validation.

Data augmentation can help in tasks where a transformation preserves the target meaning, such as suitable image transformations. It is not a universal remedy for every tabular dataset. Likewise, feature scaling affects distance-based methods strongly, but its effect depends on the estimator and feature representation.

Deep learning usually learns a parameterised representation

A neural network learns weights and other parameters from data. Backpropagation computes gradients of the chosen objective; an optimisation algorithm uses those gradients to update parameters. The objective depends on the task: regression, binary classification and multiclass classification need appropriately defined outputs and losses.

Convolutional neural networks can learn visual features useful for image recognition. Recurrent networks and Transformers can model sequences for tasks such as language processing, translation or text generation. These examples preserve the original lesson’s connection to deep learning without implying that every task needs a large network.

Well-designed deep learning systems can work at scale and achieve strong task performance, but network size alone does not establish generalisation. Dataset quality, evaluation, regularisation, computation and deployment constraints still matter. Hybrid systems can combine learned representations with retrieval or nearest-neighbor methods; the two ideas can complement one another.

The maths, one expression at a time

These expressions describe different parts of the workflow. A prediction rule produces an output, a loss describes an error, and a distance or similarity helps choose comparable examples. Keeping them separate makes the comparison easier to understand.

1. A linear prediction rule

ŷ = θ0+ ∑j=1n θjxj

Prediction = intercept + weighted feature values.

Here, x contains the prepared features, θ contains learned coefficients, n is the number of features and ŷ is the prediction. A coefficient relates to the representation actually supplied. If location was encoded into several columns, those columns have their own coefficients; a location name is not multiplied as a word.

2. Squared error and the original regression objective

J(θ) =12m∑i=1m (yi − ŷi)2

This objective is one half of the mean squared error.

The factor 1/(2m) describes the half-MSE objective. The factor one half is a common mathematical convenience when differentiating; literal MSE divides the sum by m. Both have the same minimiser when the remaining objective is unchanged. m is the number of evaluated examples, y is an observed target and ŷ is its prediction.

MSE =∑i=1m (yi − ŷi)2m
RMSE = √MSE

Average the squared prediction errors; take the square root to return to the target’s units.

Suppose two price errors are +10 and −10 in thousands of euros. Squaring gives 100 and 100, MSE is 100 in squared thousands of euros, and RMSE is 10 thousand euros. MSE does not cancel positive and negative errors. Its units must be stated before comparing numbers.

3. Binary cross-entropy has a specific scope

L = −(1/m) ∑i=1m[ yi log(pi)+ (1 − yi)log(1 − pi) ]

Penalise incorrect probability predictions for binary outcomes.

This binary cross-entropy expression applies to a binary probability-prediction task. y is a binary label, 0 or 1, and p is the predicted probability of label 1. For the literal logarithms shown here, 0 < p < 1; practical implementations handle numerical stability. This is not the loss used by all neural networks, and it is not the housing regressor’s MSE.

4. Euclidean distance depends on the features’ scale

d(x, x′) =√[ ∑j=1n (xj − x′j)2 ]

Combine corresponding feature differences into one distance.

For two-dimensional points (0, 0) and (3, 4), the distance is √(9 + 16) = 5. For houses, mixing area, room counts and category encodings changes what that distance means. Fit appropriate scaling on training data and apply that fitted transformation to later examples.

5. Cosine similarity compares direction

S(x, x′) =x · x′‖x‖ ‖x′‖

Compare vector direction after accounting for vector length.

The written formula assumes both vectors have nonzero length. Equal nonzero directions give similarity 1; perpendicular vectors give 0. Larger cosine similarity means greater alignment, while a smaller Euclidean distance means greater closeness. Libraries may define special behavior for zero vectors, so check the implementation used.

6. A uniform-neighbor regression prediction

ŷ(x) =1k∑j ∈ Nₖ(x) yj

Average the targets of the k selected training neighbors.

If three selected neighbors have prices 200, 220 and 240 thousand euros, their uniform-weight prediction is 220 thousand euros. This arithmetic does not determine which houses are neighbors: the feature representation, distance metric and search procedure do that first. Distance-weighted regression uses a different weighted combination.

Train–test splits: keep the final exam separate

A train–test split sets aside data for an evaluation that does not reuse the fitting examples. This requirement applies to learned coefficients and stored neighbors alike. The test set is useful only when the entire model-development process respects the separation.

One shared 80/20 split for the fictional 1,000-row example

800 training examples
Fit preprocessing and develop the approach within this portion.

200 held-out examples
Evaluate the selected pipelines on the same test rows.

With 1,000 observations, an 80% training allocation gives 800 training examples, and a 20% allocation gives 200 test examples. That arithmetic is correct. It is an illustration rather than a universal rule that 200 examples provide enough evidence for every task.

  1. Define the prediction task. Decide what counts as a genuinely new example. Will the application predict a new house, a new customer, another record from an existing customer, or a future time period?
  2. Choose a suitable split. Random splitting can be appropriate for independent, similarly distributed observations. Use a separation strategy that represents the actual deployment question.
  3. Set the final test portion aside. Exclude it from fitting preprocessing, estimating parameters and choosing hyperparameters.
  4. Develop within the training portion. Use a validation set or cross-validation to compare useful alternatives.
  5. Evaluate the selected pipeline. Report the agreed metric on the held-out test set, then interpret its uncertainty and limitations.

The train_test_split API supports a reproducible random split with test_size=0.2 and random_state=42. Fixing the seed helps reproduce the selected rows in a compatible environment. It does not make the split representative or remove uncertainty in the evaluation.

When shuffling is the wrong choice

For time-dependent predictions, random shuffling can allow information about later periods into training. Hold out an appropriate future period and consider time-aware validation. For related observations, such as several records for the same person or property, use group-aware separation when a new group is the intended prediction target.

For classification, stratification can help preserve class proportions across a random split. In scikit-learn, stratify=y applies to class labels; it is not a general instruction to stratify continuous house prices. Class imbalance, rare events and the number of examples per group can require additional planning.

Keep preprocessing inside the training boundary

Scaling the complete dataset before splitting leaks information from the future test portion into training. So can imputing missing values, selecting features or learning a vocabulary using all the rows. The scikit-learn common-pitfalls guide recommends pipelines to keep fitted transformations attached to the estimator.

Fit the pipeline on training rows, then use its predict method for test rows. If cross-validation is used to tune k or another hyperparameter, fit preprocessing separately inside each training fold. Selecting the best k after repeatedly looking at final test results turns that test set into another development set.

Why 80/20 can be useful without being mandatory

The ratio balances data available for learning against data reserved for evaluation. Other allocations, such as 70/30 or 90/10, may suit a particular dataset and task. Very large datasets may permit a smaller test fraction with many test examples; small or rare-event datasets may need a more careful evaluation design.

The test set should reflect the intended prediction population and provide enough relevant cases to assess important errors. More training data alone cannot fix a biased test set. Cross-validation, repeatable baselines, confidence intervals and meaningful subgroup evaluation can provide information that a single percentage split cannot.

Work through linear regression and k-NN on the same data

The complete example below uses train_test_split, LinearRegression, KNeighborsRegressor(n_neighbors=3), fitting, prediction and mean_squared_error. It creates explicit fictional data, so you can follow the feature preparation and run the comparison without inventing missing inputs.

The important fairness rule is that both approaches use the same training rows and the same held-out test rows. If one model sees different test houses, its error is not a clean comparison with the other model’s result. A shared split also makes the two prediction plots easier to interpret.

Run this Python example with NumPy, pandas and scikit-learn installed. It uses local synthetic data and makes no dataset download. The recorded run used NumPy 2.3.5, pandas 2.2.3 and scikit-learn 1.8.0; small floating-point differences can occur in other environments.

# Fictional teaching data. No real housing-market claims.
import numpy as np
import pandas as pd
import sklearn
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler


def make_preprocessor():
    # Each model gets a separate transformer, fitted only on its training rows.
    return ColumnTransformer([
        ("numbers", StandardScaler(), ["size_sq_ft", "bedrooms"]),
        ("location", OneHotEncoder(handle_unknown="ignore", sparse_output=False),
         ["location"]),
    ])


rng = np.random.default_rng(42)
n = 1000
X = pd.DataFrame({
    "size_sq_ft": rng.uniform(650, 2600, n),
    "bedrooms": rng.integers(1, 6, n),
    "location": rng.choice(["center", "suburb", "rural"], n,
                           p=[0.3, 0.5, 0.2]),
})
location_effect = X["location"].map({"center": 45000, "suburb": 10000,
                                   "rural": -12000})
y = (45000 + 160 * X["size_sq_ft"] + 18500 * X["bedrooms"]
     + location_effect + rng.normal(0, 18000, n))

# One split, shared by both approaches. k=3 is fixed before seeing the test.
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)
models = {
    "Linear regression": make_pipeline(make_preprocessor(),
                                       LinearRegression()),
    "k-NN (k=3)": make_pipeline(make_preprocessor(),
                               KNeighborsRegressor(n_neighbors=3)),
}
results, predictions = {}, {}
for name, model in models.items():
    model.fit(X_train, y_train)
    prediction = model.predict(X_test)
    mse = mean_squared_error(y_test, prediction)
    rmse = float(np.sqrt(mse))
    results[name] = {"mse_eur_squared": float(mse), "rmse_eur": rmse}
    predictions[name] = prediction
    print(f"{name}: MSE = {mse:,.2f} euro-squared; RMSE = {rmse:,.2f} euros")
Show the optional code that draws the comparison plots

Run this after the main example. Matplotlib and Pillow are the additional dependencies. This continuation draws both models on the same axes scale and saves the two figures locally.

# Optional continuation after the main example above.
from pathlib import Path

def make_plots(output_dir, actual, predictions, results):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    from PIL import Image
    plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 24,
                         "axes.labelsize": 24, "xtick.labelsize": 22,
                         "ytick.labelsize": 22, "axes.titlesize": 26})
    all_values = np.concatenate([actual, *predictions.values()]) / 1000
    lower = np.floor((all_values.min() - 12) / 50) * 50
    upper = np.ceil((all_values.max() + 12) / 50) * 50
    for name, filename, color in [
        ("Linear regression", "linear-heldout", "#285b50"),
        ("k-NN (k=3)", "knn-heldout", "#a2492b"),
    ]:
        fig, ax = plt.subplots(figsize=(8, 6), dpi=160)
        fig.patch.set_facecolor("#fbf8f2")
        ax.set_facecolor("#fbf8f2")
        ax.set_axisbelow(True)
        ax.grid(color="#dfe4dd", linewidth=1)
        ax.plot([lower, upper], [lower, upper], linestyle="--",
                color="#8a9891", linewidth=2.4, zorder=1)
        ax.scatter(actual / 1000, predictions[name] / 1000,
                   s=38, alpha=0.72, color=color, edgecolors="none", zorder=2)
        ax.set(xlim=(lower, upper), ylim=(lower, upper),
               xlabel="Actual price (€000)", ylabel="Predicted price (€000)",
               title="")
        ax.set_aspect("equal", adjustable="box")
        ax.text(0.04, 0.96, f"RMSE: €{results[name]['rmse_eur']:,.0f}",
                transform=ax.transAxes, va="top", fontsize=20,
                color="#172b39", bbox={"facecolor": "#fbf8f2", "alpha": 0.94,
                                      "edgecolor": "none", "pad": 5})
        for spine in ax.spines.values():
            spine.set_color("#9aaba2")
        ax.tick_params(colors="#354e43")
        ax.xaxis.label.set_color("#172b39")
        ax.yaxis.label.set_color("#172b39")
        ax.title.set_color("#172b39")
        fig.suptitle(name, x=0.56, y=0.98, va="top", fontsize=26, color="#172b39")
        fig.subplots_adjust(left=0.18, right=0.95, bottom=0.17, top=0.90)
        png = output_dir / (filename + ".png")
        fig.savefig(png, dpi=160, facecolor=fig.get_facecolor())
        plt.close(fig)
        Image.open(png).convert("RGB").save(output_dir / (filename + ".webp"),
                                             "WEBP", lossless=True, method=6)


make_plots(Path("."), np.asarray(y_test), predictions, results)

Results from the reproducible teaching run

The new example generates 1,000 fictional observations, then uses 800 for fitting and 200 for evaluation. Its target combines a base amount, a size effect, a bedroom effect, a location effect and random noise. Each model receives its own preprocessing pipeline, fitted only on the same training portion.

ApproachTest MSE, euros²Test RMSE, euros
Linear regression302,294,741.9017,386.63
k-NN, k = 3413,355,107.8520,331.14

These values were obtained by executing the displayed example in the recorded environment. The generator deliberately uses a mostly linear relationship, so the result is favorable to a suitable linear model. It is not evidence that linear regression always beats k-NN, and the specified k = 3 has not been claimed as an optimal choice. The prices and errors describe the synthetic exercise only.

What to inspect before interpreting the output

First, identify the target’s units and the exact feature columns. In the original story, location is a category; encoding it appropriately matters. The reproducible teaching example describes its actual inputs explicitly so you can distinguish the simplified demonstration from the broader housing scenario.

Next, follow the fit boundary. A scaler learns means and scales from the training set. The k-NN estimator uses those transformed training examples, and its test predictions apply the same fitted transformation. Linear regression and k-NN then receive a fair held-out evaluation; neither should be judged from its own training predictions alone.

Finally, read the numerical metrics with the plots. A lower MSE means a lower average squared error on these particular held-out examples under this metric. RMSE is easier to relate to the target’s units. Neither metric proves that one algorithm will win on a different population, different features or a changed data-generating process.

The neighbor count of three preserves the original lesson’s example. It is a specified demonstration setting, not a claim that three is optimal. A real project would choose such settings using training-only validation and keep the final test for the selected approach.

Read the plots without reading too much into them

Plots make prediction errors concrete, but their axes and legends must be understood first. A graph of price against one feature displays only part of a multi-feature problem. A graph of actual against predicted price answers a different question from a graph showing a fitted line across feature values.

Linear regression predictions against actual prices for the same 200 held-out fictional houses; the dashed diagonal marks perfect prediction.
Linear regression. Each point is one of the 200 held-out fictional houses. The dashed diagonal means predicted price equals actual price. Test RMSE: €17,386.63. Open the full-size figure.
Three-neighbor regression predictions against actual prices for the same 200 held-out fictional houses; the dashed diagonal marks perfect prediction.
k-NN, k = 3. The same held-out houses and axis scale make this a fairer comparison. Test RMSE: €20,331.14. The synthetic target was deliberately mostly linear; these figures do not rank the methods for every problem. Open the full-size figure.

Separate examples used for fitting from examples used for evaluation

Training points show the observations available to the fitting procedure. Test observations show the held-out examples whose targets are used for evaluation. Predicted values show the model’s output for a specified input. Use each figure’s own legend: colors should identify roles consistently, not imply that every point of one color is a nearest neighbor.

When actual and predicted values use the same units, a visible gap represents an error along the plotted axis. Inspect larger gaps and ask what the selected features may have missed. On an actual-versus-predicted plot, the identity line represents exact agreement; proximity to that line is useful, but it does not replace a numerical evaluation over all test observations.

The original lesson figures, preserved with context

The two original images remain part of this article’s history. Their embedded code contains a ten-row dataset, so its inputs could be recovered and rerun. The old narrative reports 1.6940658945086007e-21 for linear-regression MSE and 177777777.77777775 for k-NN MSE. The rerun reproduces the same practical conclusion, with tiny floating-point differences: linear-regression MSE is about 3.39 × 10−21, and k-NN MSE is about 177,777,777.78 in squared target-price units.

View the two original 2024 screenshots and their code

The original screenshots are preserved below as optimized copies. They contain the small ten-row dataset used for the recovered example.

Original 2024 Colab screenshot showing the ten-house linear regression code, near-zero mean squared error and size-versus-price plot.
Original linear-regression screenshot: ten rows, an 80/20 split and a perfectly linear price construction. Open the full-size figure.
Original 2024 Colab screenshot showing a three-neighbor regressor, mean squared error and size-versus-price plot for ten synthetic houses.
Original three-neighbor screenshot: the same two test rows, using raw numerical inputs. Open the full-size figure.

Unchanged original PNG files: linear-regression source screenshot · k-NN source screenshot.

The recovered example has only ten observations, with eight training rows and two test rows under the specified split. Its targets follow price = 200 × size exactly. The screenshot does not name its third numerical feature; the older prose alternates between location and bathrooms, so those meanings should not be assigned to it without evidence.

In the original linear-regression discussion, blue points represented training houses, orange points represented held-out observations and a red line represented predictions. A line can depict a one-feature relationship or a particular slice through a larger model. If several features vary, it does not by itself display their combined effects faithfully.

The old description called training points far from the line “outliers or high-leverage points.” A large vertical residual does not establish high leverage: leverage concerns an observation’s position in feature space relative to the other observations. A point can have a large error without having high leverage, and the picture alone does not identify a data-entry error.

In the original k-NN discussion, blue points represented retained training observations, orange points represented actual test targets and red points represented predictions for test inputs. Gaps between corresponding actual and predicted targets illustrate error. The fact that a blue point is far from a red point in this projection does not show that it was selected as a neighbor.

To inspect an actual neighbor set, query the fitted estimator’s neighbor-search method using the same prepared features and examine the returned indices and distances. An area-versus-price display cannot reveal every distance in an area, bedroom and encoded-location space.

For the recovered test rows, the actual targets are 460,000 and 320,000. Linear regression returns those values to numerical precision. Uniform three-neighbor regression returns approximately 446,666.67 and 333,333.33, explaining its larger squared error. Small differences in the printed last decimal places are numerical details, not a meaningful change in model quality.

The almost-zero linear score follows the deliberately exact linear construction and the tiny test set. It is not evidence of almost-perfect prediction in a real housing market. The larger historical k-NN score also does not establish that instance-based learning is generally worse. The new 1,000-row example makes the split and evaluation mechanics clearer with a larger, explicitly fictional dataset.

The practical conclusion is conditional: linear regression can work well when its representation suits the relationship; neighbor methods can represent useful local patterns when distances and data coverage are meaningful. Compare selected, validated pipelines on a relevant held-out set, then check their resource needs and expected failure cases.

Try it: explain what is allowed to see the test set

You have 1,000 fictional housing observations and want to compare linear regression with k-NN. You plan an 80/20 split, several candidate values of k and a standard scaler. Write down when each component is fitted, how k is selected and when the 200 held-out targets are examined.

Show a worked planning answer

Reserve the 200 test observations first using an appropriate separation strategy. Develop both candidate pipelines within the 800 training observations. Fit the scaler inside each training fold when using cross-validation, and select k from those validation results. Refit the selected pipeline on the training portion, then evaluate it on the same reserved 200 observations used for the other selected approach. Report the metric, units and limitations. If the application predicts future periods or unseen groups, replace the simple random split with a strategy that represents that goal.

As a second check, explain why a one-neighbor model predicting its own stored training examples can look excellent while making weak predictions for new houses. The missing ingredient is independent evaluation, not a more impressive-looking training score.

Continue with the 80-day machine learning learning path or explore INGOAMPT’s iOS app projects to connect the concepts with practical product ideas.

Frequently asked questions

What is the difference between model-based and instance-based learning?

Model-based methods learn a representation, such as regression coefficients, and use it to predict. Instance-based methods such as k-NN consult retained training examples when predicting a new case. A fitted software object is not automatically an instance-based learner.

Does k-NN have a training or fit step?

Yes. A k-NN estimator retains training data and may build a search structure during fit. It is often called a lazy learner because much of the comparison work happens at prediction time. Its exact computational costs depend on the data and implementation.

Why do both approaches need a train–test split?

Both need an evaluation on relevant data excluded from fitting and model selection. Learned coefficients can overfit, and stored examples can give misleading training predictions. Keeping the whole development pipeline away from final test targets makes the comparison more useful.

Is an 80/20 split always the best choice?

No. It is a common example, not a universal requirement. Dataset size, rare cases, related groups, time order and the intended deployment question determine a suitable split and validation design.

Should I scale all my data before splitting it?

No. Fit scaling and other learned preprocessing using training data only. Use a pipeline so the fitted preparation is applied consistently to held-out data and refitted correctly inside cross-validation folds.

Does a lower MSE prove that one learning approach is always better?

No. It establishes a lower average squared error on the particular evaluated examples under that metric. Check matching test rows and target units, then consider representative data, uncertainty, other useful metrics and deployment constraints before drawing a broader conclusion.

Primary sources and further reading

These references explain the estimator behavior, split boundaries and metrics used in the lesson. Check the installed library’s documentation when reproducing code, and keep the distinction between a small teaching demonstration and evidence about a real deployment.

Keep learning, then build something useful.
Continue the series or explore INGOAMPT’s iOS app projects.

Explore INGOAMPT’s iOS apps

You Can Also Learn Deep Learning in 80 Days Inside the iOS App Continue this roadmap in a focused mobile study experience with offline access, flashcards, notes, and progress tracking.
Open on the App Store