1. Home
  2. Explore
  3. Mathematics
  4. Linear Regression

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Linear Regression

An Introduction to Machine Learning

Machine learning is concerned with building computer programs that can improve their performance by learning patterns from examples. Instead of writing every rule explicitly, a programmer supplies data and a learning procedure, and the computer infers a model that can be used on new cases.

This idea connects naturally to linear regression. In a spring experiment, measured data might contain different masses and the resulting spring displacements. A regression algorithm uses those observations to fit a mathematical model. If the relationship is known to be linear, the algorithm finds the best-fitting line. If the correct form is unknown, validation can help compare linear, quadratic, cubic, or higher-order models.

The important shift is that the computer is not merely executing a rule that was completely specified in advance. It is using examples to infer a rule or model that can make predictions about cases not yet observed.

Machine learning is the study of methods that give computers the ability to learn from experience without being explicitly programmed for every situation.

What Does It Mean for a Computer to Learn?

Traditional programming follows this general pattern:

  1. A programmer writes a program.
  2. The program receives input data.
  3. The program produces an output.

For example, a programmer can write an implementation of Newton’s method that takes a number as input and computes its square root. The behavior of the program has already been specified by the programmer.

A machine-learning approach reverses part of this process:

  1. The computer receives examples or observations.
  2. The examples may include desired outputs, called labels.
  3. A learning algorithm infers a model or program from those examples.
  4. The resulting model is applied to new inputs.

The model learned from spring data might predict the displacement produced by a mass that was not included in the original experiment. Similarly, a model trained on labeled examples of football players might predict the likely position of a new player from that player’s physical characteristics.

This distinction is related to two kinds of knowledge:

  • Declarative knowledge consists of statements or facts, such as “this player is a receiver” or “this animal is cold-blooded.”
  • Imperative knowledge consists of procedures for deriving new information, such as a rule that uses height and weight to predict a player’s position.

Memorizing facts allows a system to recognize examples it has already seen. Learning is more powerful when the system can infer a general pattern and apply it to unfamiliar examples.

The progression from traditional computation to learning can be viewed as a spectrum. A square-root algorithm is mostly explicitly programmed. Linear regression is more learning-oriented because it infers a model from data. A system that learns to play checkers, chess, or Go goes further by using experience to improve future decisions.

The Basic Learning Paradigm

Most machine-learning problems contain three central stages:

  1. Training data: The system receives observations, which may be labeled or unlabeled.
  2. Inference: The system infers a model describing patterns in the observations.
  3. Prediction: The model is used to make decisions or predictions about new examples.

In the spring example:

  • The training data consists of masses and measured displacements.
  • Inference estimates the relationship between mass and displacement.
  • Prediction estimates the displacement for a new mass.

In a classification problem:

  • The training data consists of examples, features, and labels.
  • Inference identifies patterns associated with each label.
  • Prediction assigns a label to a new example.

Why Machine Learning Matters

Machine learning is used in many areas because large amounts of data often contain patterns that are difficult to encode manually. Examples include:

  • Recommendation systems used by services such as Netflix and Amazon
  • Online advertising systems that predict user preferences
  • Game-playing systems such as AlphaGo
  • Handwritten-character recognition
  • Drug discovery
  • Speech assistants such as Siri
  • Face detection and face recognition
  • Computer vision for driver-assistance and autonomous vehicles
  • Financial modeling and trading
  • Medical applications such as cancer diagnosis

These applications differ greatly, but they share a basic structure: examples are represented as data, patterns are inferred, and the inferred model is applied to new cases.

Supervised and Unsupervised Learning

The most important early distinction is whether the training examples have known labels.

Supervised Learning

In supervised learning, every training example has an associated label. The label identifies the category or outcome that the example belongs to.

For example, a dataset of football players might contain:

  • Height
  • Weight
  • Position

The position is the label. The goal is to infer a rule that predicts the position of a new player from the player’s height and weight.

Supervised learning is useful when the desired categories are already known. The system learns from examples for which the correct answer has been supplied.

Common supervised tasks include:

  • Classification: Predicting a discrete category, such as receiver or lineman.
  • Regression: Predicting a numerical value, such as spring displacement.

Unsupervised Learning

In unsupervised learning, the examples do not have labels. The system must look for natural groupings or structures in the data.

For example, a collection of football players might be represented only by height and weight, with no positions provided. The system can search for clusters of players that are close together in feature space.

Unsupervised learning may be used when:

  • The natural groups are unknown.
  • Labels are expensive or impossible to obtain.
  • The purpose is to discover structure rather than predict a known category.

The process of grouping similar examples is called clustering.

Supervised learning learns from labeled examples; unsupervised learning searches for structure in unlabeled examples.

Think About It: If a dataset contains photographs already labeled “cat” and “dog,” which type of learning is appropriate? If it contains photographs with no labels and the goal is to discover natural groups, which type is appropriate?

Examples, Features, and Labels

An individual data item is called an example or instance. Each example is represented using one or more features.

A feature is a measurable property used to describe an example. For a football player, possible features include:

  • Height
  • Weight
  • Speed
  • Arm length

If an example has several numerical features, those values can be represented as a feature vector. A football player represented by height and weight occupies a point in a two-dimensional space:

player=(height,weight)\text{player} = (\text{height},\text{weight})player=(height,weight)

A label identifies the category associated with an example. In the football example, the possible labels might be:

  • Receiver
  • Lineman

The machine-learning algorithm attempts to discover a relationship between the feature vector and the label.

The Football-Player Example

Suppose several known players are plotted according to height and weight. Receivers and linemen may occupy different regions of the plot. Linemen tend to be heavier, while receivers tend to be lighter.

If the labels are ignored, the system can search for natural clusters. If the labels are retained, the system can search for a boundary separating the two categories.

A new player can then be classified according to the region in which the player falls.

This example also reveals an important limitation: two players from different positions may have almost identical heights and weights. No boundary based only on those two features can separate them perfectly. The system must either accept some errors or use additional, more informative features.

Similarity and Distance

Machine-learning methods often need a way to determine whether two examples are similar. A common approach is to define a distance measure.

Two examples are considered similar when their distance is small. They are considered dissimilar when their distance is large.

For example, if two football players have nearly the same height and weight, their points will be close in the feature space. If one player is much taller and heavier than another, the distance between their points will be larger.

Distance is used in two major ways:

  • In clustering, distance helps determine which examples belong together.
  • In classification, distance helps determine which labeled examples are most relevant to a new example or where a separating boundary should be placed.

The Minkowski Metric

A general family of distance measures is the Minkowski metric. Given two vectors,

x=(x1,x2,…,xn)\mathbf{x} = (x_1,x_2,\ldots,x_n)x=(x1​,x2​,…,xn​)

and

y=(y1,y2,…,yn),\mathbf{y} = (y_1,y_2,\ldots,y_n),y=(y1​,y2​,…,yn​),

the Minkowski distance with power ppp is

d(x,y)=(∑i=1n∣xi−yi∣p)1/p.d(\mathbf{x},\mathbf{y}) = \left( \sum_{i=1}^{n} \left|x_i-y_i\right|^p \right)^{1/p}.d(x,y)=(i=1∑n​∣xi​−yi​∣p)1/p.

The choice of ppp determines the particular distance measure.

Manhattan Distance

When p=1p=1p=1, the distance becomes

d(x,y)=∑i=1n∣xi−yi∣.d(\mathbf{x},\mathbf{y}) = \sum_{i=1}^{n} \left|x_i-y_i\right|.d(x,y)=i=1∑n​∣xi​−yi​∣.

This is called Manhattan distance because it resembles movement through a city grid, where movement is restricted to horizontal and vertical streets rather than allowing a direct diagonal path.

Euclidean Distance

When p=2p=2p=2, the distance becomes

d(x,y)=∑i=1n∣xi−yi∣2.d(\mathbf{x},\mathbf{y}) = \sqrt{ \sum_{i=1}^{n} \left|x_i-y_i\right|^2 }.d(x,y)=i=1∑n​∣xi​−yi​∣2​.

This is the familiar straight-line distance between points. In two dimensions, it corresponds to the ordinary distance measured with a ruler.

The choice of distance measure can change which examples are considered closest. Two points may be closer under Euclidean distance but closer in a different pairing under Manhattan distance. Therefore, distance is not a neutral detail; it affects the model’s conclusions.

Clustering Unlabeled Data

Suppose a set of examples has no labels, but the system is told to search for kkk groups. A simple clustering procedure works as follows:

  1. Choose kkk initial representative examples, called exemplars.
  2. Assign every other example to the exemplar it is closest to.
  3. For each resulting group, identify the example closest to the group’s center.
  4. Use those central examples as the new exemplars.
  5. Repeat the assignment and replacement steps.
  6. Stop after a fixed number of repetitions or when assignments stop changing.

The goal is to create clusters in which examples within the same cluster are close together. At the same time, different clusters should be separated from one another.

The source describes selecting a central or median example rather than calculating an ordinary numerical mean. Such a representative is an actual example from the group and is chosen because it lies near the group’s center.

Choosing the Number of Clusters

The number of clusters is a model-design decision. If the system is told to create too few clusters, genuinely different groups may be merged. If it is told to create too many clusters, the result may overfit the data.

For example, if there are 100100100 examples and the system creates 100100100 clusters, every example forms a cluster by itself. The distance within each cluster is then minimal, but the result is not useful for discovering broad structure or classifying new examples.

A useful clustering solution should balance:

  • Small distances within clusters
  • Meaningful separation between clusters
  • A reasonable number of clusters
  • Sufficient simplicity to avoid overfitting

Validation in Clustering

After clusters have been formed, new examples can be used to test whether the grouping remains sensible. If a new example lies almost exactly between two clusters, the clustering may be uncertain or inadequate.

One possible response is to reconsider the original number of clusters. A two-cluster solution may force together examples that actually belong to a third group. A three-cluster solution may produce tighter and more natural groups.

However, adding more clusters is not automatically better. A fourth cluster might separate a few awkward points only by creating an unnecessarily complicated grouping. The aim is not to explain every individual point separately, but to discover a useful underlying structure.

Classification with Labeled Data

When labels are available, the goal changes. Instead of discovering unlabeled groups, the system seeks a classifier: a rule that assigns a label to a new example.

In a two-dimensional feature space, the classifier may be a line. In higher-dimensional spaces, it may be a plane or another separating surface.

The ideal boundary places examples of one class on one side and examples of the other class on the other side. If the classes are cleanly separated, a simple boundary may work well.

For the football-player data, a line based mainly on weight might divide the players into receivers and linemen. A new player’s position can then be predicted by determining which side of the line contains the player’s feature vector.

Overfitting and Model Complexity

A classifier should not merely memorize the training examples. It should capture a pattern that generalizes to new data.

Overfitting occurs when a model becomes too closely tailored to the training data. A very complicated boundary may classify every training example correctly while performing poorly on unseen examples.

A simpler boundary may misclassify a few training examples but generalize better. This creates a trade-off:

  • A model that is too simple may miss important patterns.
  • A model that is too complex may treat accidental details as meaningful.

Sometimes a few classification errors must be tolerated to avoid a complicated and unreliable model.

The kkk-Nearest-Neighbors Method

A standard supervised method is kkk-nearest neighbors, often abbreviated kkk-NN.

For a new example:

  1. Compute its distance from each labeled training example.
  2. Select the kkk closest examples.
  3. Examine their labels.
  4. Assign the new example the label receiving the majority vote.

For instance, if k=5k=5k=5 and three of the five nearest examples are receivers while two are linemen, the new example is classified as a receiver.

A system can also refuse to classify an example when the nearest neighbors do not provide a sufficiently strong majority. This is useful when the evidence is ambiguous.

The method depends heavily on the chosen features and distance measure. If irrelevant or badly scaled features are included, the nearest neighbors may not actually be the most similar examples.

Feature Engineering

Feature engineering is the process of choosing and preparing the features used by a learning algorithm.

Feature selection matters because not every measurable property carries useful information. Consider an attempt to predict a student’s performance in a programming course. Potential features might include:

  • Previous academic performance
  • Prior programming experience
  • Eye color
  • Month of birth

Previous academic performance and programming experience might contain useful information. Eye color and month of birth are unlikely to be meaningful predictors. Including irrelevant features can allow a model to discover accidental correlations.

The goal is to maximize the signal-to-noise ratio:

  • Signal is information that helps predict the outcome.
  • Noise is irrelevant variation or accidental correlation.

Including too many features can increase the risk of overfitting. A model may find a relationship in the training data that has no real significance.

Feature Scaling

Features may be measured on very different numerical scales. In the animal example, some properties are binary:

  • Has scales: 000 or 111
  • Is cold-blooded: 000 or 111
  • Lays eggs: 000 or 111

The number of legs, however, might be represented as 000 or 444. Under Euclidean distance, a difference of 444 in the legs dimension contributes

42=164^2 = 1642=16

to the sum of squared differences, while a binary difference contributes only

12=1.1^2 = 1.12=1.

As a result, the number-of-legs feature can dominate the distance calculation, even if it is not conceptually more important than the other features.

This is a problem of scale. A feature with larger numerical values can exert disproportionate influence on distance-based methods.

Possible solutions include:

  • Representing the feature as a binary property, such as “has legs” versus “does not have legs”
  • Choosing a distance measure less sensitive to large numerical differences
  • Rescaling the feature so that its numerical range is comparable to the ranges of other features

The distinction between feature scale and feature weight is important. Scale concerns the numerical representation of a feature. Weight concerns intentionally assigning different importance to features in a model.

The Reptile Example

Suppose animals are described using features such as:

  • Whether they lay eggs
  • Whether they are cold-blooded
  • Whether they have scales
  • Whether they are poisonous
  • Number of legs

A few examples might initially suggest that reptiles are animals that lay eggs, have scales, are poisonous, are cold-blooded, and have no legs. A boa constrictor challenges this rule because it is a reptile but is not poisonous and does not lay eggs in the relevant representation.

Removing features that are not shared by all examples produces a more general rule. However, new examples continue to test the rule:

  • A chicken has scales but is not cold-blooded, so it provides a negative example.
  • An alligator is cold-blooded and has scales but has legs, requiring further refinement.
  • A dart frog has legs but lacks scales and is not cold-blooded, helping distinguish it from reptiles.
  • A python reinforces the similarity between snakes.
  • A salmon creates a difficult case because it has scales and is cold-blooded but is not a reptile.

No rule based only on the selected features can perfectly separate the python from the salmon. A design choice is therefore required. One possible rule labels every scaly, cold-blooded animal as a reptile. This correctly includes the python but incorrectly includes the salmon.

That error is a false positive: the system predicts that an example belongs to a class when it does not.

A false negative occurs when the system predicts that an example does not belong to a class even though it does. A system can often reduce false positives only by accepting more false negatives, or reduce false negatives only by accepting more false positives.

When the features do not contain enough information to separate classes perfectly, classification requires an explicit trade-off between different kinds of errors.

Think About It: If missing a true reptile were considered much worse than incorrectly labeling a non-reptile as a reptile, should the classifier favor sensitivity or specificity?

Evaluating a Classifier

A model should be evaluated not only on the examples used to train it but also on new examples. A common procedure is to divide the data into:

  • A training set, used to construct the model
  • A test set, used to evaluate how well the model generalizes

A model that performs very well on training data but poorly on test data is likely overfitting.

Confusion Matrix

A confusion matrix compares predicted labels with actual labels. For a binary classification problem, it contains four categories:

  • True positive: The model predicts the positive class, and the example really is positive.
  • True negative: The model predicts the negative class, and the example really is negative.
  • False positive: The model predicts the positive class, but the example is actually negative.
  • False negative: The model predicts the negative class, but the example is actually positive.

Correct predictions appear on the diagonal of the confusion matrix.

Accuracy

Accuracy is the fraction of all predictions that are correct:

Accuracy=true positives+true negativesall predictions.\text{Accuracy} = \frac{\text{true positives}+\text{true negatives}} {\text{all predictions}}.Accuracy=all predictionstrue positives+true negatives​.

Two classifiers can have the same accuracy while making different kinds of errors. Therefore, accuracy alone does not always identify the better model.

Positive Predictive Value

Positive predictive value, or PPV, measures how many examples predicted to be positive really are positive:

PPV=true positivestrue positives+false positives.\text{PPV} = \frac{\text{true positives}} {\text{true positives}+\text{false positives}}.PPV=true positives+false positivestrue positives​.

A high PPV means that positive predictions are generally trustworthy.

Sensitivity

Sensitivity measures how many of the truly positive examples the classifier successfully identifies:

Sensitivity=true positivestrue positives+false negatives.\text{Sensitivity} = \frac{\text{true positives}} {\text{true positives}+\text{false negatives}}.Sensitivity=true positives+false negativestrue positives​.

A classifier can achieve sensitivity of 111 by labeling every example as positive. That guarantees that no positive example is missed, but it also produces many false positives.

Specificity

Specificity measures how many of the truly negative examples the classifier correctly rejects:

Specificity=true negativestrue negatives+false positives.\text{Specificity} = \frac{\text{true negatives}} {\text{true negatives}+\text{false positives}}.Specificity=true negatives+false positivestrue negatives​.

A classifier can achieve specificity of 111 by labeling every example as negative. That avoids false positives, but it also misses every true positive.

Sensitivity and specificity therefore express competing priorities. Improving one may reduce the other.

Receiver Operating Characteristic Curve

A receiver operating characteristic curve, or ROC curve, helps examine the trade-off between sensitivity and specificity as the classification threshold changes.

A classifier can be made more willing to assign the positive label, increasing sensitivity but also increasing false positives. Alternatively, it can be made more cautious, reducing false positives but potentially missing more positive examples.

The ROC approach helps select a threshold appropriate to the consequences of different errors.

The Five Design Components of a Learning Method

Every machine-learning method requires several important design decisions.

1. Training Data and Evaluation

The system must determine which examples will be used for learning and how success will be measured. Training accuracy alone is not enough; performance on unseen test data is essential for judging generalization.

2. Representation

Each example must be represented using features. The representation determines what information the algorithm can use.

A football player represented only by height and weight may be difficult to classify correctly. Additional features, such as speed, might make the groups easier to distinguish.

3. Distance or Similarity

The system needs a rule for deciding which examples are close or similar. Euclidean distance, Manhattan distance, and other measures can produce different results.

4. Model Constraints

The system must control the complexity of the model. For clustering, this includes deciding how many clusters to form. For classification, it includes deciding whether a simple line or a more complicated boundary is appropriate.

5. Optimization

The algorithm needs a method for finding a model that performs well according to an objective. For clustering, the objective might involve minimizing average within-cluster distance. For classification, it might involve reducing prediction errors while avoiding excessive complexity.

These choices are interconnected. A poor feature representation cannot generally be rescued by a sophisticated optimization procedure. Likewise, a good representation can still produce poor results if distance is defined badly or the model is allowed to overfit.

Bringing the Ideas Together

Machine learning begins with examples and attempts to infer a useful model from them. The examples must be represented through features, and the choice of features determines what patterns can be recognized.

When labels are available, supervised learning constructs a classifier or predictor. The classifier may use a separating line, a more complex surface, or the labels of nearby examples through kkk-nearest neighbors.

When labels are absent, unsupervised learning searches for natural clusters. A distance-based clustering method repeatedly assigns examples to nearby representatives and updates those representatives until the grouping stabilizes.

Distance is central to both approaches, but its meaning depends on how features are encoded and scaled. A feature with a large numerical range can dominate a distance calculation. Irrelevant features can introduce noise and overfitting. Feature engineering is therefore a central part of machine-learning design.

Finally, no model should be judged only by how well it handles training data. Validation and test data reveal whether the model generalizes. Accuracy, PPV, sensitivity, and specificity describe different aspects of performance, while ROC analysis helps study the trade-off between detecting positive cases and rejecting negative cases.

A successful machine-learning system combines informative features, an appropriate similarity or distance measure, a suitably constrained model, and evaluation on unseen data.

Comprehensive Review

  • Machine learning infers models from examples rather than relying entirely on explicitly programmed rules.
  • Training data provides the observations from which a model is learned.
  • Features describe examples; labels identify their categories or desired outcomes.
  • Supervised learning uses labeled examples to predict labels for new examples.
  • Unsupervised learning uses unlabeled examples to discover natural groupings.
  • Clustering groups examples that are close according to a chosen distance measure.
  • Classification separates labeled categories using a boundary or a neighborhood-based rule.
  • kkk-nearest neighbors classifies a new example by taking a vote among its closest labeled examples.
  • The Minkowski metric provides a general family of distance measures.
  • Manhattan distance is the Minkowski metric with p=1p=1p=1.
  • Euclidean distance is the Minkowski metric with p=2p=2p=2.
  • Feature selection determines which properties carry useful signal.
  • Feature scaling prevents a numerically large feature from dominating distance calculations.
  • Overfitting occurs when a model captures accidental details of training data instead of general patterns.
  • False positives and false negatives represent different classification errors.
  • Accuracy measures overall correctness.
  • PPV measures the reliability of positive predictions.
  • Sensitivity measures the ability to find true positive cases.
  • Specificity measures the ability to reject true negative cases.
  • ROC analysis examines the trade-off between sensitivity and specificity.
  • Generalization to unseen data is the central test of whether a learned model is genuinely useful.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent