1. Home
  2. Explore
  3. Computer Science
  4. Introduction to Machine Learning

Study methods

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

Introduction to Machine Learning

Foundations of Machine Learning

Machine learning is a way for a computer to perform a task by learning patterns from data rather than following a complete set of explicit instructions.

In traditional programming, a programmer describes the procedure:

  1. Receive an input.
  2. Apply specific rules.
  3. Produce an output.

In machine learning, the programmer instead provides examples or experiences. The computer searches for patterns that connect inputs to outputs or actions to consequences. The computer then uses the learned pattern to make predictions or decisions about new situations.

For example, instead of explicitly programming every rule that distinguishes an authentic banknote from a counterfeit one, a machine-learning system can receive many banknotes described by measured features. Each banknote is labeled as authentic or counterfeit. The system then attempts to discover a function that connects the measurements to the correct label.

A central goal of machine learning is generalization: performing well not only on the examples used during learning, but also on new examples that the system has not previously encountered.

Machine learning uses data or experience to estimate patterns that allow a computer to perform tasks without being given every instruction explicitly.

The Three Major Forms of Learning

The lesson introduces three broad categories:

  • Supervised learning: learning from labeled input-output examples.
  • Reinforcement learning: learning from actions, rewards, and punishments.
  • Unsupervised learning: finding patterns in data that has no labels.

These categories differ mainly in the type of information available during learning.

Think About It

If a computer is given measurements of many banknotes but no indication of which ones are counterfeit, can it still learn to distinguish them? That question leads to unsupervised learning rather than supervised learning.

Supervised Learning

In supervised learning, the computer receives a data set containing input-output pairs. Each input provides evidence, and each output provides the correct answer associated with that evidence.

The computer attempts to learn a function fff that maps an input to an output:

f(input)=outputf(\text{input}) = \text{output}f(input)=output

The exact function fff describing the real-world relationship is usually unknown and may be very complicated. Therefore, the machine-learning system constructs a hypothesis function, written as hhh, that approximates fff:

h(input)≈f(input)h(\text{input}) \approx f(\text{input})h(input)≈f(input)

The quality of supervised learning depends on how accurately hhh predicts the correct output for both known and new inputs.

For example, a weather data set might contain:

  • Humidity
  • Air pressure
  • A label indicating whether it rained

Each row is one labeled example. The humidity and pressure are the input, while “rain” or “no rain” is the output.

Mathematically, the hypothesis might be written as:

h(humidity,pressure)=rain or no rainh(\text{humidity},\text{pressure}) = \text{rain or no rain}h(humidity,pressure)=rain or no rain

The computer examines many historical examples and tries to discover how humidity and pressure relate to rainfall.

Classification

The first major supervised-learning task is classification. Classification assigns an input to one of a set of discrete categories, also called classes or labels.

Examples include:

  • Rainy day versus non-rainy day
  • Authentic banknote versus counterfeit banknote
  • Blue object versus red object
  • Spam message versus legitimate message

The output is categorical rather than an arbitrary numerical measurement.

A classification data set might represent categories numerically. For example:

  • 111 means rain
  • 000 means no rain

The numbers do not necessarily indicate quantity. They simply provide convenient labels for mathematical calculations.

Representing Data as Points

Suppose each weather example has two numerical inputs:

  • x1x_1x1​: humidity
  • x2x_2x2​: pressure

Each example can be plotted as a point on a two-dimensional graph. Humidity forms one axis, and pressure forms the other.

A rainy day could be shown as a blue point, while a non-rainy day could be shown as a red point. When a new, unlabeled point appears, the computer must decide whether it belongs to the rainy or non-rainy category.

The same idea extends to more inputs. With four measurements, each example has four coordinates. With one hundred measurements, each example has one hundred coordinates. Humans may have difficulty visualizing spaces beyond three dimensions, but a computer can process many numerical dimensions because each dimension is simply another value.

Nearest-Neighbor Classification

A straightforward approach is nearest-neighbor classification. The algorithm classifies a new point according to the class of the single training point closest to it.

The process is:

  1. Receive an unlabeled input.
  2. Measure its distance from the known data points.
  3. Find the closest data point.
  4. Assign the new input to the closest point’s class.

If the closest known weather example was a rainy day, the new day is classified as rainy. If the closest known example was a non-rainy day, the new day is classified as non-rainy.

The intuition is that nearby points often resemble one another. However, a single closest point can be misleading. A point might be closest to one red example while being surrounded by many blue examples.

kkk-Nearest-Neighbor Classification

kkk-nearest-neighbor classification reduces the dependence on one example. Instead of considering only the closest point, it examines the kkk closest points.

The algorithm is:

  1. Choose a value for kkk, such as 333, 555, or 777.
  2. Find the kkk data points nearest to the new input.
  3. Count how many neighbors belong to each class.
  4. Assign the input to the class with the most votes.

For example, if k=5k=5k=5 and the five nearest points contain:

  • Three rainy examples
  • Two non-rainy examples

then the new point is classified as rainy.

Each neighbor effectively contributes one vote. Using several neighbors can produce a more stable decision because the result is less likely to be controlled by one unusual or noisy data point.

Strengths and Weaknesses

Nearest-neighbor methods are intuitive and can work well when similar inputs tend to have similar labels. They also require relatively little effort to describe mathematically.

However, a naive implementation may be slow. For every new input, the algorithm may need to calculate distances to every stored data point. Faster data structures can help locate nearby points, and data-pruning methods can remove irrelevant examples, but nearest-neighbor classification can still become expensive with very large data sets.

Linear Decision Boundaries

Another approach is to examine the entire data set and construct a decision boundary that separates the classes.

With two input dimensions, a decision boundary can be a line. One side of the line represents one class, and the other side represents the second class. With more dimensions, the equivalent boundary is generally called a hyperplane.

A data set is linearly separable if a line or hyperplane can separate the classes perfectly. Real-world data is often not linearly separable because of noise, outliers, and overlapping categories. Even then, a line can sometimes provide a useful approximate separation.

Linear Hypotheses and Weights

Suppose the inputs are x1x_1x1​ and x2x_2x2​. A linear hypothesis can calculate a weighted combination of those inputs:

w0+w1x1+w2x2w_0 + w_1x_1 + w_2x_2w0​+w1​x1​+w2​x2​

Here:

  • w1w_1w1​ determines how strongly x1x_1x1​ affects the result.
  • w2w_2w2​ determines how strongly x2x_2x2​ affects the result.
  • w0w_0w0​ is an additional constant that shifts the boundary.

The values w0w_0w0​, w1w_1w1​, and w2w_2w2​ are called weights or parameters. They determine the position and orientation of the decision boundary.

The hypothesis can classify the result using a threshold:

h(x)={1if w0+w1x1+w2x2≥00otherwiseh(x) = \begin{cases} 1 & \text{if } w_0+w_1x_1+w_2x_2 \geq 0 \\ 0 & \text{otherwise} \end{cases}h(x)={10​if w0​+w1​x1​+w2​x2​≥0otherwise​

For the weather example, 111 might mean rain and 000 might mean no rain.

The expression equals zero along the decision boundary:

w0+w1x1+w2x2=0w_0+w_1x_1+w_2x_2=0w0​+w1​x1​+w2​x2​=0

Points producing a value greater than or equal to zero fall on one side of the boundary, while points producing a negative value fall on the other side.

Vector and Dot-Product Form

The same calculation can be written compactly using vectors.

The weight vector is:

w=(w0,w1,w2)\mathbf{w} = (w_0,w_1,w_2)w=(w0​,w1​,w2​)

The input vector includes a constant 111 so that w0w_0w0​ participates in the calculation:

x=(1,x1,x2)\mathbf{x} = (1,x_1,x_2)x=(1,x1​,x2​)

The dot product of these vectors is:

w⋅x=w0(1)+w1x1+w2x2\mathbf{w}\cdot\mathbf{x} = w_0(1)+w_1x_1+w_2x_2w⋅x=w0​(1)+w1​x1​+w2​x2​

Therefore, the hypothesis can be written as:

h(x)={1if w⋅x≥00otherwiseh(\mathbf{x}) = \begin{cases} 1 & \text{if } \mathbf{w}\cdot\mathbf{x}\geq 0 \\ 0 & \text{otherwise} \end{cases}h(x)={10​if w⋅x≥0otherwise​

The input vector represents the specific data point being classified. The weight vector represents the learned model. Different weights produce different decision boundaries.

The machine-learning algorithm’s task is therefore to learn a useful weight vector.

The Perceptron Learning Rule

The perceptron learning rule adjusts the weights using labeled examples. It can begin with arbitrary, even random, weights and then improve them by examining data points one at a time.

For a data point with input x\mathbf{x}x and actual label yyy, the algorithm compares:

  • yyy: the correct output
  • h(x)h(\mathbf{x})h(x): the predicted output

A conceptual update rule for each weight is:

wi←wi+α(y−h(x))xiw_i \leftarrow w_i+\alpha\left(y-h(\mathbf{x})\right)x_iwi​←wi​+α(y−h(x))xi​

Here:

  • wiw_iwi​ is one of the weights.
  • α\alphaα is the learning rate.
  • y−h(x)y-h(\mathbf{x})y−h(x) is the prediction error.
  • xix_ixi​ is the corresponding input component.

If the prediction is correct, then:

y−h(x)=0y-h(\mathbf{x})=0y−h(x)=0

The update becomes zero, so the weights remain unchanged.

If the actual value is greater than the prediction, the error is positive, and the weights are adjusted upward in a direction intended to increase the future result. If the actual value is lower than the prediction, the error is negative, and the weights are adjusted downward.

The process repeats across many examples:

  1. Start with initial weights.
  2. Select a labeled data point.
  3. Produce a prediction.
  4. Compare the prediction with the correct label.
  5. Adjust the weights if necessary.
  6. Continue through the data, possibly multiple times.

The hope is that the weights converge to a decision boundary that classifies the examples accurately.

Learning Rate

The learning rate α\alphaα controls how large each adjustment is.

  • A large α\alphaα causes larger updates.
  • A small α\alphaα causes smaller updates.
  • If α=0\alpha=0α=0, the weights never change.
  • A larger learning rate may allow faster changes but can also make learning unstable.
  • A smaller learning rate makes changes more gradual.

The appropriate value depends on the problem.

Hard Thresholds and Logistic Regression

The perceptron’s threshold produces only two outputs: 000 or 111. This is called a hard threshold.

A hard threshold is useful when only a category is needed, but it does not express confidence. It treats a point barely across the boundary and a point far beyond the boundary as equally certain members of the same class.

A different point is that the mathematical shape of a hard threshold is difficult to work with when methods involving derivatives are needed. For these reasons, classification often uses a soft threshold instead.

Logistic regression replaces the abrupt threshold with a smooth logistic function. Its output lies between 000 and 111:

0≤h(x)≤10 \leq h(\mathbf{x}) \leq 10≤h(x)≤1

A value such as 0.70.70.7 can be interpreted as a stronger indication of one category than the other, although the precise probability interpretation depends on the model and data.

The logistic function changes gradually:

  • Values far on one side approach 000.
  • Values far on the other side approach 111.
  • Values near the boundary fall between 000 and $1.

This provides a notion of confidence or likelihood rather than only an immediate yes-or-no decision.

Think About It

Two data points may both be classified as rainy, but one may lie far from the decision boundary while the other lies very close to it. Why should a useful model distinguish between these cases? A soft threshold provides a way to represent that difference.

Support Vector Machines

A support vector machine, or SVM, is another classification method based on a decision boundary.

Many different lines may correctly separate the known training examples. However, some separating lines are extremely close to one class. Such a line may classify the training examples perfectly but perform poorly on new data near the boundary.

An SVM addresses this by seeking the maximum-margin separator. Instead of choosing any boundary that separates the classes, it attempts to maximize the distance between the boundary and the nearest examples from each class.

The closest examples are called support vectors. They are especially important because they help determine the boundary and the size of the margin.

A large margin is desirable because it leaves more room for variation in future examples. A new point slightly different from the training examples is less likely to be misclassified when the boundary is positioned with a wide separation between classes.

In two dimensions, the separator is a line. In higher dimensions, it is a hyperplane.

Nonlinear Boundaries

Some data sets cannot be separated effectively by a straight line. For example, one class might form a group in the center while another class surrounds it. Any straight line would misclassify many points.

SVMs can operate in higher-dimensional spaces and can therefore represent more complex decision boundaries. A boundary that appears as a circle in two dimensions may correspond to a flat hyperplane in a transformed higher-dimensional space.

This allows the method to handle cases that are not linearly separable in the original representation.

Comparing Classification Methods

Nearest-neighbor classification, perceptron-style linear classification, logistic regression, and support vector machines all attempt to solve classification problems, but they use different assumptions.

  • Nearest neighbor: nearby examples are likely to have similar labels.
  • Perceptron: a weighted linear combination can separate the classes.
  • Logistic regression: a weighted combination can produce a smooth confidence-like output.
  • SVM: the best separating boundary is the one with the largest margin.

No single algorithm is always best. Performance depends on:

  • The structure of the data
  • The amount of noise
  • Whether the classes are linearly separable
  • The number of dimensions
  • The desired type of output
  • The computational resources available

Machine-learning work often involves testing several models and comparing their results.

Regression

Classification predicts discrete categories. Regression predicts continuous numerical values.

Examples include predicting:

  • Sales from advertising spending
  • A future measurement from current observations
  • A numerical quantity based on several input features

A regression hypothesis might be written as:

h(advertising spending)=predicted salesh(\text{advertising spending}) = \text{predicted sales}h(advertising spending)=predicted sales

Unlike classification, the output is not restricted to values such as 000 and 111. It may be any appropriate real number.

Linear Regression

A simple regression model can plot known data points and fit a line that approximates their relationship.

For example:

  • The horizontal axis represents advertising spending.
  • The vertical axis represents sales.
  • Each point represents one historical period.
  • The fitted line predicts the expected sales for a given advertising budget.

The model does not need to pass through every point. Instead, it attempts to capture the overall relationship. For a new advertising value, the predicted sales can be estimated from the line.

The model’s parameters are adjusted so that the line fits the observed data as effectively as possible.

Loss Functions

A machine-learning model produces a hypothesis, but the model must be evaluated. Evaluation can be viewed as an optimization problem.

The model may attempt to minimize a cost function. In machine learning, the cost often includes a loss function, which measures how poorly the model’s predictions match the actual outcomes.

A loss function compares actual values with predicted values. The total loss across a data set is often called the empirical loss.

The goal is generally:

minimize total loss\text{minimize total loss}minimize total loss

Different tasks require different loss functions.

The 000-111 Loss Function

The 000-111 loss function is useful for discrete classification.

For one example:

L(y,y^)={0if y=y^1if y≠y^L(y,\hat{y}) = \begin{cases} 0 & \text{if } y=\hat{y} \\ 1 & \text{if } y\neq\hat{y} \end{cases}L(y,y^​)={01​if y=y^​if y=y^​​

Here:

  • yyy is the actual label.
  • y^\hat{y}y^​ is the predicted label.

A correct prediction has loss 000. An incorrect prediction has loss 111.

For an entire data set, the empirical loss is the number of incorrectly classified examples:

Empirical loss=∑i=1nL(yi,y^i)\text{Empirical loss} = \sum_{i=1}^{n} L(y_i,\hat{y}_i)Empirical loss=i=1∑n​L(yi​,y^​i​)

For example, if a decision boundary misclassifies four examples, its total 000-111 loss is 444.

L1 Loss

For regression, being close to the correct value is better than being far away. The L1 loss measures the absolute difference between the actual and predicted values:

L1(y,y^)=∣y−y^∣L_1(y,\hat{y}) = |y-\hat{y}|L1​(y,y^​)=∣y−y^​∣

Across a data set:

Total L1 loss=∑i=1n∣yi−y^i∣\text{Total L1 loss} = \sum_{i=1}^{n}|y_i-\hat{y}_i|Total L1 loss=i=1∑n​∣yi​−y^​i​∣

If actual sales are 2,8002{,}8002,800 and predicted sales are 2,9002{,}9002,900, the error is relatively small. A prediction of 1,0001{,}0001,000 has a much larger error.

L1 loss treats the error in a direct, proportional way.

L2 Loss

The L2 loss squares the difference:

L2(y,y^)=(y−y^)2L_2(y,\hat{y})=(y-\hat{y})^2L2​(y,y^​)=(y−y^​)2

Across a data set:

Total L2 loss=∑i=1n(yi−y^i)2\text{Total L2 loss} = \sum_{i=1}^{n}(y_i-\hat{y}_i)^2Total L2 loss=i=1∑n​(yi​−y^​i​)2

Squaring makes large errors disproportionately expensive. An error of 222 produces a squared loss of 444, while an error of 101010 produces a squared loss of $100.

L2 loss is therefore more sensitive to outliers and large mistakes. It may be useful when large errors are especially undesirable. L1 loss may be preferable when the data contains outliers that should not dominate the model.

Overfitting and Generalization

A model should not merely memorize its training examples. It should learn a pattern that remains useful on new data.

Overfitting occurs when a model fits the training data too closely and consequently performs poorly on unseen examples.

For classification, an overfit model might create a highly complicated boundary that correctly classifies every training point, including unusual outliers. The model may then incorrectly classify ordinary future examples.

For regression, an overfit model might create a complicated curve that passes through every training point exactly. Its training loss may be zero, but its predictions between or beyond those points may be poor.

A simpler line that makes a few training errors may generalize better than a complicated curve that makes none.

Regularization

One way to reduce overfitting is regularization. Regularization adds a penalty for model complexity to the cost function.

A general form is:

Cost=Loss+λ⋅Complexity\text{Cost} = \text{Loss} + \lambda \cdot \text{Complexity}Cost=Loss+λ⋅Complexity

Here, λ\lambdaλ controls how strongly complexity is penalized.

  • A larger λ\lambdaλ favors simpler hypotheses more strongly.
  • A smaller λ\lambdaλ places less emphasis on simplicity.
  • A value of λ\lambdaλ must be chosen according to the problem.

Regularization reflects the idea that a model should explain the data without becoming unnecessarily complicated. It is related to Occam’s razor: when several explanations work, a simpler one may be more likely to generalize.

Regularization does not mean ignoring errors. It creates a balance between:

  1. Fitting the available data accurately.
  2. Keeping the hypothesis simple enough to work on new data.

Holdout Cross-Validation

Another way to evaluate generalization is holdout cross-validation.

The data is divided into two portions:

  • A training set, used to learn the model.
  • A testing set, reserved for evaluating the model.

The model learns only from the training set. After training, it predicts the examples in the testing set, which it has not previously seen.

Strong performance on the testing set suggests that the learned pattern generalizes. A large difference between training performance and testing performance suggests possible overfitting.

The testing data must remain separate from the training process. If the model is trained on the testing data, the test no longer provides an unbiased measure of generalization.

kkk-Fold Cross-Validation

Holdout validation has a limitation: some data is reserved for testing and therefore is not used for training. kkk-fold cross-validation uses the data more efficiently.

The data is divided into kkk groups, called folds. The process then repeats kkk times:

  1. Hold out one fold for testing.
  2. Train the model on the other k−1k-1k−1 folds.
  3. Evaluate the model on the held-out fold.
  4. Change which fold is held out.
  5. Repeat until every fold has served as the testing fold.

This produces kkk evaluation results. Their average provides an overall estimate of model performance.

For example, with 101010-fold cross-validation:

  • The data is divided into 101010 parts.
  • The model trains on 999 parts and tests on the remaining part.
  • This is repeated 101010 times.
  • Each part is used as the testing set once.
  • The results can be averaged.

The central principle is that evaluation must use examples different from those used to train the model.

Think About It

Why might a model with perfect training accuracy perform worse on new data than a model with a few training mistakes? Perfect memorization is not the same as learning a general pattern.

Machine Learning with scikit-learn

Python programs can implement learning algorithms from scratch, but libraries make practical experimentation much easier.

scikit-learn is a Python library containing implementations of many machine-learning algorithms, including:

  • Perceptron models
  • Support vector classifiers
  • Nearest-neighbor classifiers
  • Training and testing utilities
  • Evaluation tools

A typical supervised-learning workflow has several stages.

Loading Labeled Data

A banknote data set can be stored in a CSV file. Each row represents one banknote.

The row contains:

  • Four numerical measurements describing the banknote
  • A label indicating whether it is authentic or counterfeit

In the example:

  • Label 000 represents an authentic banknote.
  • Label 111 represents a counterfeit banknote.

The first four values form the evidence or input vector. The final value forms the target label.

Splitting the Data

The data is randomly shuffled and divided into training and testing sets. Randomization helps prevent the division from being biased by the original ordering of the file.

The training data is then separated into:

  • XXX: the input vectors
  • yyy: the corresponding labels

The ordering must remain consistent. The label in yyy must correspond to the input vector in the same position in XXX.

Training and Predicting

A model is trained using the training inputs and labels. In scikit-learn, the model’s fitting procedure performs the algorithm’s parameter-learning process.

Conceptually:

  1. Construct a model.
  2. Call the fitting method with training inputs and labels.
  3. Use the trained model to generate predictions for testing inputs.
  4. Compare predictions with the actual testing labels.
  5. Count correct and incorrect predictions.
  6. Calculate accuracy.

Accuracy can be expressed as:

Accuracy=number of correct predictionstotal number of predictions\text{Accuracy} = \frac{\text{number of correct predictions}} {\text{total number of predictions}}Accuracy=total number of predictionsnumber of correct predictions​

The model can be changed without rewriting the entire program. A perceptron can be replaced with a support vector classifier or a kkk-nearest-neighbor classifier.

The banknote example demonstrates that several different algorithms can perform very well on the same data set. In one experiment:

  • The perceptron correctly classified 679679679 banknotes and incorrectly classified 777.
  • The support vector classifier correctly classified 682682682 and incorrectly classified 444.
  • One-neighbor classification correctly classified 685685685 and incorrectly classified 111.
  • Three-neighbor classification correctly classified every tested example in that particular run.

These results are not universal. Randomly changing the training and testing division can change the outcome, and a different data set may favor a different algorithm.

The train_test_split utility in scikit-learn automates the division into training and testing sets. This reduces the amount of code needed and helps standardize the process.

Reinforcement Learning

Reinforcement learning differs from supervised learning because the agent is not given a complete collection of labeled input-output pairs in advance.

Instead, an agent learns through experience by interacting with an environment.

The agent:

  1. Observes its current state.
  2. Chooses an action.
  3. Moves to a new state.
  4. Receives a numerical reward or punishment.
  5. Uses that experience to improve future decisions.

A positive reward indicates a desirable result. A negative reward indicates an undesirable result.

The agent is not necessarily told which actions are good in advance. It discovers this by trying actions and observing their consequences.

For example, a walking robot could receive:

  • A positive reward for moving forward successfully.
  • A negative reward for falling.

Over many attempts, the robot can learn actions that tend to produce successful movement.

Markov Decision Processes

A common formal model for reinforcement learning is a Markov decision process, or MDP.

An MDP contains:

  • A set of states
  • A set of actions available in each state
  • A transition model
  • A reward function

A state describes the current situation. In a game, it might describe the board. In a grid world, it might be the agent’s current location.

An action is a choice the agent can make in a state, such as moving left, right, up, or down.

The transition model describes the probability of reaching a new state after taking an action. It can represent both deterministic and uncertain environments.

A transition can be represented as:

s→as′s \xrightarrow{a} s'sa​s′

where:

  • sss is the current state.
  • aaa is the selected action.
  • s′s's′ is the resulting state.

The transition model describes:

P(s′∣s,a)P(s' \mid s,a)P(s′∣s,a)

This means the probability of reaching state s′s's′ given current state sss and action aaa.

The reward function describes the reward associated with a transition:

R(s,a,s′)R(s,a,s')R(s,a,s′)

This represents the reward received after taking action aaa in state sss and arriving at state s′s's′.

Unlike a Markov chain, in which transitions occur according to probabilities without an agent choosing actions, an MDP gives the agent control over which action to attempt.

Learning from a Grid World

Imagine an agent moving through a grid. A green square is a goal that provides a positive reward. Red squares are dangerous locations that provide negative rewards.

At first, the agent may not know:

  • Which squares are dangerous
  • Which actions lead toward the goal
  • Which routes are efficient
  • Which actions should be avoided

The agent explores. If moving right from a particular state produces punishment, the agent learns that this action is undesirable in that state. If moving up eventually leads to a reward, the agent learns that the action may be valuable.

Over time, the agent can learn not only immediately rewarding actions but also sequences of actions that eventually lead to rewards.

Q-Learning

Q-learning is a reinforcement-learning method that learns the value of taking an action in a particular state.

It learns a function:

Q(s,a)Q(s,a)Q(s,a)

The value Q(s,a)Q(s,a)Q(s,a) estimates how rewarding it is to take action aaa while in state sss.

Initially, the agent knows nothing about the environment, so it may initialize every value to zero:

Q(s,a)=0Q(s,a)=0Q(s,a)=0

As the agent interacts with the environment, it updates these estimates using observed rewards and expected future rewards.

Current and Future Rewards

A useful action may not produce an immediate reward. An action might move the agent closer to a goal, even though the reward arrives later.

Therefore, Q-learning considers two components:

  1. The reward received immediately.
  2. The estimated rewards available in future states.

A conceptual new estimate is:

new estimate=r+max⁡a′Q(s′,a′)\text{new estimate} = r+\max_{a'}Q(s',a')new estimate=r+a′max​Q(s′,a′)

Here:

  • rrr is the reward just received.
  • s′s's′ is the new state.
  • a′a'a′ represents a possible next action.
  • max⁡a′Q(s′,a′)\max_{a'}Q(s',a')maxa′​Q(s′,a′) is the value of the best next action according to the current estimates.

The Q-value is then updated by moving the old estimate toward the new estimate:

Q(s,a)←Q(s,a)+α[r+max⁡a′Q(s′,a′)−Q(s,a)]Q(s,a) \leftarrow Q(s,a) + \alpha \left[ r+\max_{a'}Q(s',a')-Q(s,a) \right]Q(s,a)←Q(s,a)+α[r+a′max​Q(s′,a′)−Q(s,a)]

The expression inside the brackets is the difference between the new estimate and the old estimate. It is sometimes understood as a correction or error signal.

The Learning Rate in Q-Learning

The learning rate α\alphaα determines how much the new experience changes the existing Q-value.

  • If α=1\alpha=1α=1, the new estimate completely replaces the old estimate.
  • If α=0\alpha=0α=0, the new experience is ignored.
  • A value between 000 and 111 balances old and new information.

A high learning rate makes the agent respond strongly to recent experience. A lower learning rate preserves more of what the agent has learned previously.

Some systems also discount future rewards. A discount parameter makes rewards received sooner more valuable than rewards received much later. This represents situations in which immediate rewards are preferred over delayed rewards.

Greedy Decision-Making

Once Q-values have been learned, the agent can use a greedy policy. In a state sss, it selects the action with the greatest estimated value:

a∗=arg⁡max⁡aQ(s,a)a^*=\arg\max_a Q(s,a)a∗=argamax​Q(s,a)

This means the agent chooses the action currently believed to produce the greatest reward.

Greedy behavior is useful once the agent has reliable knowledge. However, it creates a problem early in learning: the agent may repeatedly choose a known action and never discover a better alternative.

Exploration and Exploitation

Reinforcement learning contains a tension between:

  • Exploitation: choosing the best-known action.
  • Exploration: trying an unfamiliar action to gather new information.

An agent that only exploits may obtain rewards but miss a faster or more valuable strategy. An agent that only explores may fail to use knowledge it has already gained.

Epsilon-Greedy Selection

The epsilon-greedy algorithm balances these behaviors.

Let ϵ\epsilonϵ represent the probability of making a random exploratory choice.

  • With probability 1−ϵ1-\epsilon1−ϵ, choose the currently best-known action.
  • With probability ϵ\epsilonϵ, choose a random action.

This gives the agent frequent opportunities to use its knowledge while still allowing it to discover alternatives.

A larger ϵ\epsilonϵ produces more exploration. A smaller ϵ\epsilonϵ produces more exploitation. It can be useful to begin with a larger ϵ\epsilonϵ and gradually reduce it as the agent becomes more knowledgeable.

Think About It

If an agent has found one route to a reward, why might it still need to try other routes? A different route may be faster, safer, or capable of producing a greater total reward.

Reinforcement Learning in Nim

Nim is a simple two-player game suitable for reinforcement-learning demonstrations.

The game consists of several piles of objects. On each turn, a player:

  1. Chooses exactly one pile.
  2. Removes at least one object from that pile.
  3. May remove as many objects as desired from that pile.

The player who removes the last remaining object loses.

A game state can be represented by the number of objects in each pile. For four piles, a state might be represented as a sequence of four numbers.

The available actions specify:

  • Which pile to select
  • How many objects to remove

The reward occurs when the game ends:

  • A player who causes the last object to be removed receives a punishment.
  • A player whose opponent removes the last object receives a reward.

An AI can train by playing Nim against itself. Each game provides experience. The AI records which state-action choices eventually lead to wins or losses and updates its Q-values.

With no training, the AI may make mostly random decisions. After many practice games, such as thousands of games played against itself, it can learn which actions are advantageous in particular states.

Nim is relatively manageable because its state space is small. The number of possible states is determined by the possible object counts in the piles.

Function Approximation in Reinforcement Learning

Games such as chess have enormously many states and possible actions. It may be impossible to store a separate Q-value for every state-action pair.

In such situations, reinforcement learning can use function approximation. Instead of memorizing an individual value for every exact state and action, the system learns a function that estimates value based on features of the state.

A feature might describe some relevant property of the situation. States that share similar features can receive similar value estimates.

This allows the agent to generalize:

  • If an action works well in one state,
  • and another state has similar important features,
  • the action may also be estimated as useful in the second state.

Function approximation is important when the state space is too large for complete enumeration.

Unsupervised Learning

In unsupervised learning, the data has no labels or external feedback.

The system receives examples but is not told which category each example belongs to. Its task is to discover structure within the data.

This differs from supervised learning:

  • Supervised learning receives labeled examples.
  • Unsupervised learning receives unlabeled examples.

Clustering

One important unsupervised-learning task is clustering. Clustering groups similar objects together.

Applications include:

  • Grouping similar genes in genetic research
  • Dividing image pixels into regions
  • Grouping consumers for market research
  • Identifying naturally occurring groups in a data set

The groups are not supplied in advance as labeled answers. The algorithm attempts to find them from the relationships among the data points.

kkk-Means Clustering

kkk-means clustering divides data into kkk clusters.

The algorithm represents each cluster by a center, often called a centroid. It repeatedly assigns points to centers and then moves the centers.

The process is:

  1. Choose the number of clusters, kkk.
  2. Initialize kkk cluster centers, often at random.
  3. Assign every data point to its nearest center.
  4. Recalculate each center as the average of the points assigned to it.
  5. Repeat the assignment and recalculation steps.
  6. Stop when the assignments no longer change substantially.

Assignment Step

For each point, the algorithm measures its distance to every cluster center. The point is assigned to the closest center.

If a point is closer to the blue center than to the red or green centers, it becomes part of the blue cluster.

Re-centering Step

After all points have been assigned, each center moves to the average location of its cluster’s points.

For a cluster containing points x1,x2,…,xm\mathbf{x}_1,\mathbf{x}_2,\ldots,\mathbf{x}_mx1​,x2​,…,xm​, the new center is:

μ=1m∑i=1mxi\boldsymbol{\mu} = \frac{1}{m} \sum_{i=1}^{m}\mathbf{x}_iμ=m1​i=1∑m​xi​

The center is pulled toward regions containing more assigned points.

Repetition and Convergence

Moving the centers changes which centers are closest to some points. Therefore, the assignments may change during the next iteration.

The algorithm continues alternating between:

  • Assigning points to their nearest centers
  • Moving centers to the average of their assigned points

Eventually, the assignments may stabilize. When no points change clusters, the algorithm has reached an equilibrium for that initialization.

Because the initial centers can affect the final result, different initializations may produce different clusters. Choosing the number kkk is also part of applying the method; multiple values can be tested to determine which produces useful groupings.

Comprehensive Review

Machine learning allows computers to learn patterns from data or experience rather than relying entirely on explicitly programmed instructions.

The central supervised-learning idea is to learn a hypothesis function hhh that approximates an unknown relationship fff between inputs and outputs.

  • Classification predicts discrete categories.
  • Regression predicts continuous numerical values.
  • Nearest-neighbor methods classify based on nearby examples.
  • Perceptrons learn weighted linear decision boundaries.
  • Logistic regression replaces a hard threshold with a smooth output between 000 and 111.
  • Support vector machines seek decision boundaries with a maximum margin.
  • Loss functions measure prediction error.
  • Regularization penalizes complexity to reduce overfitting.
  • Cross-validation evaluates whether a model generalizes to unseen data.

Reinforcement learning follows a different pattern. An agent interacts with an environment, observes states, takes actions, and receives rewards or punishments.

  • A Markov decision process represents states, actions, transitions, and rewards.
  • Q-learning estimates the value of taking an action in a state.
  • The learning rate controls how strongly new experiences change existing estimates.
  • A greedy policy chooses the action with the highest estimated value.
  • Epsilon-greedy selection balances exploration with exploitation.
  • Function approximation allows reinforcement learning to operate in very large state spaces.

Unsupervised learning receives data without labels and searches for structure within it.

  • Clustering groups similar objects.
  • kkk-means clustering repeatedly assigns points to nearby centers and moves the centers to the average of their assigned points.

Across all three forms of learning, the common theme is the discovery of useful patterns. Supervised learning learns from labeled examples, reinforcement learning learns from consequences, and unsupervised learning discovers structure without labels. The effectiveness of any method depends on the data, the task, the model’s assumptions, and how well the learned pattern generalizes beyond the experiences used during training.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent