How Do You Choose a Model and Know It's Good?

Not every model is a neural network, and a high score can lie. This post covers classification vs. regression, the main families of models, how yes/no models measure mistakes, how to prepare and split data without leaking it, how to spot overfitting, and why accuracy misleads on rare events.

This is the fourth post in a five-part series on machine learning from zero. The previous post explained neural networks and how they learn. You don't have to read it first. The next section sums up the facts from the earlier posts that this one needs.

What you need from the earlier posts

  • A model is a rule plus learned numbers. A weight is a learned number multiplied with an input. A bias is a learned number added on its own. Together, they are the parameters. Each input is also called a feature, and the correct answer is the label.
  • Training lowers the loss. The loss is one number that says how wrong the model is. For number predictions, it is usually the mean squared error: the average of the squared errors.
  • Gradient descent. Training nudges every parameter a small step in the direction that lowers the loss. A parameter's gradient says which way, and how strongly. Training works through small groups of examples called batches. One full pass over the training data is an epoch.
  • Neural networks. A neural network is layers of neurons. Each neuron multiplies, adds, and applies a bend that turns negative numbers into 0. The bend lets a network learn curves.
  • Hyperparameters. Settings people choose before training, such as the number of layers or the learning rate.

Which model, and how good is it?

So far, we've built models and trained them. Two questions are left before you can use one for real. Which kind of model should you use? And how do you know it works?

We'll answer them in four steps:

  1. What kind of answer you need. A category or a number.
  2. Which family of model, and how each one learns. Neural networks are only one of several.
  3. Hiding data to grade honestly. How to prepare and split data so the score means something.
  4. Spotting memorizing and misleading scores. Overfitting, and when a high accuracy lies.

Most examples here use one running case: a bank that approves or rejects loans, using a table of past applications.

Two kinds of questions: classification and regression

Before building a model, you need to know what kind of answer you want. There are two main types. You don't really choose between them. You just look at what you're trying to predict.

TypeThe answer is...Examples
ClassificationA categoryLoan approved or rejected; spam or not spam; cat, dog or bird
RegressionA numberHouse price; exam score; tomorrow's temperature

If the answer is one of a fixed set of options, it's classification. If the answer is a number on a scale, it's regression.

Classification with exactly two options (yes or no) is called binary classification. With more than two options, such as cat, dog or bird, it is called multi-class classification. This post mostly uses yes/no examples, because they keep the math simple. The same ideas carry over to more options.

These two words describe the type of problem. They are not specific methods. The type affects what the model's output looks like, and how its mistakes are measured. Both come up in the next two sections.

Different kinds of models

Neural networks are popular, but they are only one family of models. Many real-world problems are solved with simpler ones.

Linear regression

Linear regression is the plain multiply-and-add rule. For the exam-score example from this series, that's:

score = w1 × study + w2 × sleep + b

It multiplies each input by a weight, adds a bias, and outputs a number. "Linear" means it can only describe straight-line relationships. It is used for regression, predicting numbers. It is simple, fast and easy to understand.

Logistic regression

Logistic regression uses the same multiply-and-add rule, then adds one extra step. It squashes the result into a number between 0 and 1. That number can be read as a probability.

Result of the ruleAfter squashingMeaning
−40.022% chance of "yes"
00.5050/50
20.8888% chance of "yes"
40.9898% chance of "yes"

A large negative result becomes a probability close to 0. A large positive result becomes a probability close to 1.

The squashing step is done by a function called the sigmoid. Like the bend inside a neural network, the sigmoid is an activation function: a fixed shape applied to a result. The bend is used inside a network. The sigmoid is mostly used at the very end, when the output should be a probability.

To make a final decision, you pick a cut-off, usually 0.5. Above it means "yes", for example "approve the loan". Below it means "no".

The sigmoid curve. The horizontal axis is the result of the multiply-and-add rule, from −6 to 6. The vertical axis is the probability of yes, from 0 to 1. The S-shaped curve starts near 0, passes through 0.5 at 0, and flattens near 1. Four points are marked: −4 gives 0.02, 0 gives 0.50, 2 gives 0.88, and 4 gives 0.98. A dashed line at 0.5 marks the cut-off: above means yes, below means no.

A few things to know about logistic regression:

  • It is used for classification, even though its name says "regression". The name makes sense once you see what it does. It predicts a number (the probability), and that number is then used to pick a category.
  • It is like a neural network with just one neuron, plus a squash at the end.
  • There is nothing to design. It has no middle layers, so the data sets its whole structure: one weight per input, plus one bias. With 5 inputs, it has 6 parameters.

Decision trees and tree-based models

A decision tree works very differently. It doesn't multiply inputs by weights. Instead, it learns a series of yes/no questions, like a flowchart:

A decision tree for loans. The first question is: is income above 50,000? If yes, the next question is: is credit score above 650? Yes leads to approve and no leads to reject. If income is not above 50,000, the next question is: is debt below 5,000?, which leads on to more questions. A footnote says the numbers a tree learns are the cut-off points: 50,000, 650 and 5,000.

The numbers a tree learns are the cut-off points in its questions, like 50,000 or 650. They are not weights.

A single tree is easy to understand, but it often isn't very accurate. So people usually combine many trees:

  • Random forest. Many trees, each trained a little differently, that vote on the final answer.
  • Gradient-boosted trees. Trees built one after another, where each new tree focuses on fixing the mistakes of the trees before it. Popular libraries for these are XGBoost and LightGBM. They are among the most accurate models for table-shaped data.

Neural networks

Neural networks are the most flexible family. They shine when patterns are complex and hard to describe with simple rules, such as in images, audio and text. They usually need more data and more computing power than the other families.

Which model fits which problem?

Kind of dataCommon starting point
Tables with rows and columns, like loan applicationsLogistic or linear regression first, then tree-based models like XGBoost
Images, audio and speechNeural networks
Text and languageNeural networks, often one already trained on lots of text, then adapted to the task
Decisions that must be explained, like loans or medicineSimpler, more explainable models

Some points worth remembering:

  • For table data, simple and tree-based models often do as well as neural networks, or better. They are also faster to train and easier to explain.
  • Explainability matters in many fields. If a bank rejects a loan, it is often required to say why. The weights of a logistic regression, or the questions in a tree, are much easier to explain than millions of neural network weights.
  • Some problems sit in between. Spam detection was long done with simple models. Today, large email providers such as Gmail also use neural networks for it.

How a yes/no model measures its mistakes

For number predictions, the loss is the squared error. For a yes/no question, the model outputs a probability instead. For example, 0.88 means "88% sure the answer is yes." The real answer is simply 1 (yes) or 0 (no). Plain subtraction doesn't work well here, so a different loss is used.

We want a penalty that:

  • is tiny when the model is confident and correct,
  • grows when the model is unsure,
  • becomes huge when the model is confident and wrong.

Here is how the standard penalty behaves when the real answer is yes (1):

Model's probability for "yes"SituationPenalty
0.99Very sure, correct0.01
0.90Fairly sure, correct0.11
0.50No idea0.69
0.10Fairly sure, wrong2.30
0.01Very sure, wrong4.61

Notice how fast the penalty grows as the model becomes confidently wrong. This teaches the model an important lesson: being confident and wrong is the worst outcome. When the real answer is no (0), the same idea applies the other way round.

This loss is called log loss, or binary cross-entropy. As with squared error, it is worked out per example and then averaged over many examples.

More than two options

For a multi-class problem, the model needs one probability per option, and they must add up to 1. For example: cat 0.90, dog 0.07, bird 0.03.

The step that produces these probabilities is called softmax. It is the many-option version of the sigmoid. It takes one raw number per option, from the multiply-and-add part, and turns them into probabilities that add up to 1. A bigger raw number gets a bigger share.

The penalty only looks at the probability given to the correct option. If the picture really is a cat, the model gave it 0.90, so the penalty is 0.11, just as in the table above. Confident and correct is cheap. Confident and wrong is expensive.

This loss is called cross-entropy. Binary cross-entropy is simply its two-option version.

Loss vs. accuracy

The loss is the number that training uses. But when people judge a classification model, they usually use a simpler number: accuracy. Accuracy is the share of examples the model gets right. If a model gets 880 out of 1,000 examples right, its accuracy is 88%.

So why not train on accuracy directly? Because accuracy only changes when a prediction flips from wrong to right. A tiny change to one weight usually flips nothing. So accuracy can't tell training whether that change helped. The loss changes a little with every tiny change, so it always can.

Not every model learns by gradient descent

Training usually follows the same recipe: predict, measure the loss, adjust the parameters, repeat. For linear regression, logistic regression and neural networks, the adjusting is usually done by gradient descent, or a close relative of it.

Decision trees are different. They have no weights to nudge. Instead, the training searches for the best question. It tries many possible yes/no questions, like "income above 30,000?" or "credit score above 650?". It keeps the one that best separates the approved applications from the rejected ones. Then it repeats this inside each branch.

What about gradient-boosted trees, with "gradient" in their name? Each tree is still built by searching for good questions, not by nudging weights. Remember that a gradient is a slope: it says which way, and how strongly. Gradient-boosted trees use it to work out which predictions are still wrong, and in which direction. Each new tree is then built to push those predictions the right way.

Preparing the data

Before any training can happen, the data must be prepared. This step matters as much as the model itself.

Models only understand numbers, and they need clean, consistent input. Common steps include:

  • Converting text to numbers. An "employment type" column with the values "salaried" and "self-employed" could become 0 and 1.
  • Filling in missing values. Most models can't handle an empty value. If some incomes are missing, you might fill them with the average income.
  • Scaling the numbers. Different columns can have very different ranges. Income might be in the tens of thousands, while years of employment might be between 1 and 10. Without adjusting, the large numbers can dominate training. Scaling brings all the columns into similar ranges.

Two of these steps need a little more care.

Text with more than two values. Two values can simply become 0 and 1. But say the column has three values: "salaried", "self-employed" and "unemployed". Numbering them 0, 1 and 2 would mislead the model. It would treat "unemployed" as if it were twice "self-employed", and that means nothing.

The fix is to give each value its own yes/no column:

employment_typeis_salariedis_self_employedis_unemployed
salaried100
self-employed010
unemployed001

This is called one-hot encoding, because exactly one column is "hot" (set to 1) in each row.

Scaling and tree models. Scaling matters for models that multiply inputs by weights, such as linear regression and neural networks. Tree models don't need it. Their questions look at one column at a time ("income above 50,000?"), so the size of the other columns doesn't matter. Many tree-based models, including XGBoost, LightGBM and the trees in recent versions of scikit-learn (a popular Python library), can also handle missing values on their own.

Never grade a model on its homework

You should never judge a model on the same examples it learned from. Instead, you divide the dataset into separate parts:

PartTypical shareWhat it's used for
Training set70–80%The model learns from these examples.
Validation set10–15%Comparing models and settings during development.
Test set10–15%One final, honest check at the very end.

For example, a bank with 10,000 past applications might split them like this:

One bar representing 10,000 loan applications, split to scale into 70%, 15% and 15%. The training set holds 7,000, and the model learns from these. The validation set holds 1,500, for comparing models and settings. The test set holds 1,500, for one final check at the very end.

Why hide data from the model?

A model can memorize its training examples instead of learning the real pattern. Think of a student who memorizes the answers to last year's exam. They'd score perfectly on those exact questions, but fail when given new ones.

If you only tested a model on its training examples, a memorizing model would look perfect. Hidden data reveals the truth, because the model has never seen it.

Why separate validation and test sets?

When you compare many models, you pick the one that scores best on the validation set. But if you test and pick many times, your choices slowly get tailored to that particular data. This is sometimes called "tuning to the test".

That's why the test set stays untouched until the very end. It gives one final, honest measure of how the chosen model will do on truly new data.

Split first, then fill in and scale

Some preparation steps learn something from the data. Filling in missing incomes needs an average. Scaling needs each column's average and its spread: how widely its values vary.

Those numbers must come from the training set only. The same numbers are then used on the validation and test sets.

Why does this matter? Suppose you worked out the average income from the whole dataset, test rows included. A little information about the test set would then sneak into training. The test would no longer be fully hidden, and its score would look slightly better than the truth. This mistake is called data leakage.

So the safe order is:

  1. Split the data into training, validation and test sets.
  2. Work out the averages and spreads from the training set.
  3. Use those same numbers to fill in and scale all three sets.

What about text? Some conversions use a fixed list you already know, like salaried → 0 and self-employed → 1. Those learn nothing from the data, so they're safe at any point. One-hot encoding usually learns its list of values from the data. So build that list from the training set too.

Overfitting and underfitting

A model that scores well on its training data is not necessarily a good model. Here are the two main ways learning goes wrong.

A story about three students

Three students prepare for an exam using the same 50 practice questions.

  • Student A studies the ideas behind the questions. They do well on the practice questions and on the real exam, which has new questions. This is what we want.
  • Student B memorizes the 50 answers word for word. They score 100% on the practice questions, but fail the real exam, because its questions are different. This is overfitting.
  • Student C barely learns anything. They do poorly on the practice questions and poorly on the real exam. This is underfitting.

Here is the same story as three models fitted to the same points:

Three panels showing the same eight data points, which rise to a gentle hump and then fall. Underfit: a nearly flat straight line that misses the hump; too simple, misses the pattern. Good fit: a smooth arch that follows the hump; follows the pattern, ignores the noise. Overfit: a wiggly line that passes exactly through every point and swings wildly between them; memorizes every point, noise included.

Overfitting: memorizing instead of learning

A model overfits when it learns the training examples too closely, including random details that don't matter. A loan model might "learn" that the applicant who earned exactly 45,230 was approved. The real pattern is that higher income and lower debt make approval more likely.

Overfitting is most likely when the model has many parameters but not much data. It has enough room to memorize, but not enough examples to force it to find general patterns.

Underfitting: not learning enough

A model underfits when it can't even learn the patterns in its own training data. Usually, the model is too simple for the problem. A straight-line rule, for example, can never learn a pattern that rises and then falls, like an exam score that rises with sleep up to 8 hours and then drops. No amount of training can fix that, because the shape of the rule doesn't allow it.

How to tell which one is happening

Compare the model's accuracy on the training data with its accuracy on the validation data, which it has never trained on:

Training accuracyValidation accuracyDiagnosis
99%70%Overfitting: great on what it studied, poor on new data
65%63%Underfitting: poor even on what it studied
88%86%Healthy: good on both, with only a small gap

Why is "65% training, 63% validation" underfitting?

Look at the training score first. 65% means the model gets 35% of its own training examples wrong. It failed its practice questions. The small gap between 65% and 63% only tells you the model isn't memorizing. It is mediocre everywhere.

Whether a score is "low" depends on the problem. Imagine that 60% of the applicants in the dataset were approved. A useless model that always says "approve" would already score 60%. Next to that, 65% is barely better than not thinking at all.

Two checks for every model

CheckQuestion to askIf the answer is "no"
Training scoreDid the model learn its own training examples well?Underfitting
Gap between training and validationDoes the model do about as well on unseen data?Overfitting

A good model passes both checks: a high training score, with the validation score close behind.

You can watch for this during training, too. Measure the loss on the validation set after every epoch, next to the training loss:

An illustration of loss over 100 epochs. The training loss falls steeply and then keeps falling slowly for the whole run. The validation loss falls with it until about epoch 30, reaches its lowest point, and then rises steadily. A dashed line at that lowest point is labelled: early stopping, keep the parameters from here. The region after it is shaded and labelled: overfitting, training keeps improving, validation gets worse.

As long as both lines fall, the model is learning real patterns. When the validation loss turns up while the training loss keeps falling, the model has started to memorize.

How to fix each problem

ProblemCommon fixes
UnderfittingUse a more capable model, such as more layers or more neurons. Add more useful inputs. Train for longer.
OverfittingCollect more data. Use a simpler model. Stop training as soon as the validation score stops improving (early stopping). Add a penalty for very large weights, which discourages overly specific rules (regularization).

This is the real reason for splitting data. Without hidden validation and test data, overfitting would be invisible, because the training score alone would look excellent.

When accuracy lies

Accuracy can also mislead you when one answer is rare. Imagine a model that catches fraud in card payments. Say only 1 payment in every 100 is fraud.

A lazy model that always says "not fraud" gets 99 out of 100 payments right. Its accuracy is 99%. Yet it has never caught a single fraud, which was the whole point.

When one answer is rare, look at that answer on its own. Start by sorting the model's predictions into four groups:

Model says "fraud"Model says "not fraud"
Really fraudCaughtMissed
Really not fraudFalse alarmCorrectly left alone

This table is called a confusion matrix. Two useful scores come from it:

  • Recall. Of all the real frauds, what share did the model catch? The lazy model catches none, so its recall is 0%.
  • Precision. Of all the payments the model flagged as fraud, what share really were fraud? A model that flags almost everything has low precision, because most of its flags are false alarms.

These two scores pull against each other. If the model flags more payments, it catches more fraud, so recall goes up. But it also raises more false alarms, so precision goes down.

Which score matters more depends on the problem:

  • In cancer screening, recall matters most. A missed case is far worse than a false alarm.
  • In a spam filter, precision matters most. Hiding a real email is worse than letting one spam message through.

Scores for number predictions

For regression, accuracy doesn't apply. A predicted number is rarely exactly right. Instead, people look at how big the errors are on average. Two scores are common:

  • MAE (mean absolute error) is the average size of the error, ignoring its sign.
  • RMSE (root mean squared error) is the square root of the mean squared error. Taking the root brings it back to the original units, such as exam points.

Say a model predicts four exam scores. It is off by +3, −3, +5 and −5 points:

  • MAE = (3 + 3 + 5 + 5) ÷ 4 = 4. "It is off by 4 points on average."
  • MSE = (9 + 9 + 25 + 25) ÷ 4 = 17, so RMSE = √17 ≈ 4.12.

RMSE comes out a little higher, because squaring makes the bigger misses count more.

How to choose a model

Everything in this post comes together here. Choosing a model isn't pure instinct. It usually follows three steps.

Step 1: What type of answer do you need? A category means classification. A number means regression.

Step 2: What kind of data do you have? Use the rules of thumb from the model families above to pick two or three candidates. For a table of loan applications, that might be logistic regression, XGBoost and a small neural network.

Step 3: Try the candidates and measure. Train each candidate on the training set. Compare them on the validation set, checking for overfitting and underfitting. Keep the best one. Check it once on the test set.

Experimenting is a normal, expected part of the work. Engineers compare:

  • Different model types, such as logistic regression vs. XGBoost vs. a neural network.
  • Different hyperparameters for the same model, such as a bigger or smaller network, or a higher or lower learning rate.
  • Different ways of preparing the data, such as adding a new input column like "debt divided by income".

All the candidates must be compared fairly, on the same held-back validation data.

You also don't need to master every method that exists. A small number of model types covers most practical work.

New words in this post

WordMeaning
ClassificationA problem where the answer is a category
RegressionA problem where the answer is a number
Binary / multi-class classificationClassification with two options / with more than two
Linear regressionA multiply-and-add model that predicts a number
Logistic regressionA multiply-and-add model plus a squash into 0 to 1, for yes/no problems
SigmoidThe squash that turns any number into a probability between 0 and 1
Decision treeA model that learns a chain of yes/no questions, like a flowchart
Random forestMany decision trees that vote on the answer
Gradient-boosted treesTrees built one after another, each fixing the mistakes of the ones before
Log loss (binary cross-entropy)The standard loss for yes/no problems; it punishes confident wrong answers hard
SoftmaxThe step that turns one raw number per option into probabilities that add to 1
Cross-entropyThe standard loss for classification with any number of options
AccuracyThe share of examples a model gets right
One-hot encodingOne yes/no column per text value, so the model doesn't assume a false order
ScalingBringing input columns into similar number ranges
Training / validation / test setData to learn from / to compare models / for one final check
Data leakageInformation from validation or test data sneaking into training
OverfittingMemorizing the training data instead of learning the general pattern
UnderfittingBeing too simple to learn even the training data well
Early stoppingStopping training when the validation score stops improving
RegularizationA penalty for very large weights, to reduce overfitting
Confusion matrixA table of caught, missed, false alarms and correctly left alone
PrecisionOf everything flagged "yes", the share that really was "yes"
RecallOf all the real "yes" cases, the share the model caught
MAE / RMSEThe average size of a number prediction's error / the root of the MSE

Recap

  • Classification predicts a category. Regression predicts a number.
  • Not every model is a neural network. For table data, logistic regression and tree-based models are often the best choice. Neural networks shine on images, audio and text.
  • Yes/no models output a probability through the sigmoid, and are trained with log loss. Softmax and cross-entropy do the same job for many options.
  • Trees don't use gradient descent. They search for the best yes/no questions.
  • Split the data first. Take averages and spreads from the training set only, or the test score leaks.
  • High training but low validation scores mean overfitting. Low scores on both mean underfitting.
  • When one answer is rare, accuracy lies. Check precision and recall. For number predictions, use MAE or RMSE.
  • Choosing a model means picking a few candidates, comparing them on validation data, and checking the winner once on the test set.

Next up: that's every idea we need. How Do You Build Your First Machine Learning Model? puts them all to work in real Python code, on a loan project you can run in your browser.