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 enables computers to perform tasks by learning patterns from data rather than following only explicitly programmed instructions. Instead of specifying every rule needed to solve a problem, a developer provides data and allows an algorithm to infer relationships within that data.

A machine-learning system generally attempts to learn a function that maps inputs to outputs:

f(input)→outputf(\text{input}) \rightarrow \text{output}f(input)→output

For example:

  • Weather measurements may be mapped to a prediction of rain or no rain.

  • Measurements of a banknote may be mapped to authentic or counterfeit.

  • Advertising spending may be mapped to an estimated amount of sales.

The function that truly describes the relationship between inputs and outputs is usually unknown and may be highly complex. A machine-learning algorithm therefore attempts to construct an approximate function, called a hypothesis, that performs well on both known and previously unseen data.


Supervised Learning

Supervised learning is a machine-learning approach in which the computer receives labeled input-output pairs.

Each training example contains:

  • Input features: Information available to the computer.

  • Output label or target: The correct answer associated with that input.

The objective is to learn a function that maps the input features to the appropriate output.

For example, a weather dataset might contain:

  • Humidity

  • Air pressure

  • A label indicating whether it rained

The computer studies many examples of this form and attempts to infer the relationship between the weather measurements and the observed weather outcome.

Supervised learning: Learning a mapping from inputs to outputs using examples for which the correct outputs are already known.

The human-provided labels are what distinguish this process from unsupervised learning. The computer does not merely observe weather measurements; it also receives information about whether each recorded day was rainy.

Classification and Regression

Two major supervised-learning tasks are classification and regression.

Classification

Classification predicts a discrete category or class.

Examples include:

  • Rain or no rain

  • Authentic or counterfeit

  • Red or blue

  • Spam or not spam

The possible outputs are separate categories rather than arbitrary numerical values.

Regression

Regression predicts a continuous numerical value.

Examples include:

  • Expected sales based on advertising spending

  • House price based on property features

  • Temperature based on environmental measurements

Although both tasks learn a function from inputs to outputs, classification predicts categories while regression predicts numerical quantities.


Classification

Suppose a computer receives two weather features:

  • x1x_1x1​: Humidity

  • x2x_2x2​: Air pressure

The desired output is a category:

  • Rain

  • No rain

The unknown real-world relationship can be represented by a function fff:

f(x1,x2)→{rain,no rain}f(x_1, x_2) \rightarrow \{\text{rain}, \text{no rain}\}f(x1​,x2​)→{rain,no rain}

Because the exact function is unknown, the machine-learning algorithm attempts to learn a hypothesis function hhh that approximates it:

h(x1,x2)≈f(x1,x2)h(x_1, x_2) \approx f(x_1, x_2)h(x1​,x2​)≈f(x1​,x2​)

The quality of the learned model depends on how accurately hhh predicts the correct category for both training examples and new inputs.

Representing Classification Data Geometrically

When there are two numerical input features, each example can be plotted on a two-dimensional graph:

  • The horizontal axis may represent humidity.

  • The vertical axis may represent pressure.

  • Blue points may represent rainy days.

  • Red points may represent days without rain.

A new, unlabeled data point can then be classified by examining its relationship to the labeled points.

A computer can extend this idea to many more dimensions. Each feature corresponds to one dimension:

  • Two features produce a two-dimensional representation.

  • Ten features produce a ten-dimensional representation.

  • One hundred features produce a one-hundred-dimensional representation.

Although humans cannot easily visualize spaces beyond three dimensions, computers can process high-dimensional numerical data without needing to visualize it.


Nearest-Neighbor Classification

Nearest-neighbor classification assigns a new data point to the category of the single labeled data point closest to it.

The process is:

  1. Receive an unlabeled input.

  2. Measure its distance from the known data points.

  3. Identify the closest data point.

  4. Assign the new input the same class as that nearest point.

For example, if a new weather observation is closest to a previously observed rainy day, it is classified as a rainy day.

This approach is based on the assumption that nearby data points are likely to have similar labels.

Strengths and Limitations

Nearest-neighbor classification is intuitive and can work well when similar inputs tend to belong to the same class. However, relying on only one neighbor can produce poor decisions near the boundary between categories.

A point may be closest to a red data point but still be surrounded by many blue data points. In such cases, a single neighbor may not represent the broader pattern of the data.


kkk-Nearest-Neighbor Classification

kkk-nearest-neighbor classification improves on single-neighbor classification by examining the kkk closest data points rather than only one.

The process is:

  1. Choose a value for kkk, such as 333, 555, or 777.

  2. Find the kkk nearest labeled data points.

  3. Count how many neighbors belong to each class.

  4. Assign the new input to the class with the most votes.

For example, if the five nearest neighbors contain:

  • Three rainy-day examples

  • Two non-rainy-day examples

The new point is classified as a rainy day.

Each neighbor effectively casts one vote. The most common class becomes the prediction.

Choosing kkk

  • A small kkk makes the model sensitive to local details and individual outliers.

  • A larger kkk considers a broader region and may produce more stable predictions.

  • The best value of kkk depends on the dataset and should often be determined experimentally.

Computational Limitation

A naive nearest-neighbor implementation must compare a new point with every existing data point. This can become slow when the dataset is large.

Possible improvements include:

  • Data structures designed for efficient neighbor searches

  • Removing redundant or unimportant data points

  • Pruning the dataset to retain only relevant examples


Decision Boundaries and Linear Models

Instead of examining nearby examples for every prediction, a model can attempt to find a decision boundary that separates one category from another.

With two input features, the boundary may be a line. With more features, it may be a higher-dimensional surface called a hyperplane.

A decision boundary divides the input space into regions. For example:

  • Points on one side may be classified as rainy.

  • Points on the other side may be classified as not rainy.

Linear Separability

A dataset is linearly separable if a single line or hyperplane can perfectly divide its classes.

Real datasets are often not perfectly linearly separable because of:

  • Measurement errors

  • Random noise

  • Outliers

  • Overlapping categories

  • Incorrect or ambiguous labels

Even when perfect separation is impossible, a line may still make mostly correct predictions.


Linear Combination of Features

A linear decision boundary can be defined using weighted features.

Let:

  • x1x_1x1​ and x2x_2x2​ be input features.

  • w1w_1w1​ and w2w_2w2​ be their corresponding weights.

  • w0w_0w0​ be an additional constant, sometimes called a bias or intercept term.

The model calculates:

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

The weights determine the position and orientation of the boundary:

  • Changing w1w_1w1​ changes the influence of x1x_1x1​.

  • Changing w2w_2w2​ changes the influence of x2x_2x2​.

  • Changing w0w_0w0​ shifts the boundary.

A threshold-based classifier may be written as:

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

Here:

  • 111 represents rain.

  • 000 represents no rain.

The algorithm must learn suitable values for the weights so that rainy examples tend to produce 111 and non-rainy examples tend to produce 000.


Vector Representation and the Dot Product

The weights can be represented as a weight vector:

w=[w0w1w2]\mathbf{w} = \begin{bmatrix} w_0 & w_1 & w_2 \end{bmatrix}w=[w0​​w1​​w2​​]

The input can be represented as:

x=[1x1x2]\mathbf{x} = \begin{bmatrix} 1 & x_1 & x_2 \end{bmatrix}x=[1​x1​​x2​​]

The initial 111 in the input vector allows the bias weight w0w_0w0​ to participate in the same calculation:

w0⋅1=w0w_0 \cdot 1 = w_0w0​⋅1=w0​

The dot product of w\mathbf{w}w and x\mathbf{x}x is:

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

The hypothesis can therefore be written compactly 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 vectors must have the same length because the dot product multiplies corresponding entries and sums the results.

The purpose of training is to learn a weight vector that produces accurate predictions for the available examples and generalizes to new inputs.


The Perceptron Learning Rule

The perceptron learning rule is a method for adjusting the weights of a linear classifier.

Each training example consists of:

  • An input vector x\mathbf{x}x

  • The correct output yyy

  • A current prediction h(x)h(\mathbf{x})h(x)

The algorithm compares the correct output with the prediction. A general update can be expressed as:

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

where:

  • wiw_iwi​ is an individual weight.

  • yyy is the actual label.

  • h(x)h(\mathbf{x})h(x) is the predicted label.

  • xix_ixi​ is the corresponding input feature.

  • α\alphaα is the learning rate.

The exact implementation may vary, but the central idea is to update weights based on prediction errors.

Correct Predictions

If the prediction is correct:

y=h(x)y=h(\mathbf{x})y=h(x)

Therefore:

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

The update becomes zero, so the weights remain unchanged.

Incorrect Predictions

If the prediction is incorrect, the difference between the actual and predicted values is nonzero. The algorithm adjusts the weights to make the current example more likely to be classified correctly in the future.

Conceptually:

  • If the actual output is larger than the prediction, the relevant weights are increased.

  • If the actual output is smaller than the prediction, the relevant weights are decreased.

The algorithm processes examples one at a time and may revisit the data repeatedly. Ideally, the weights converge to values that produce accurate classifications.

Learning Rate

The learning rate, represented by α\alphaα, controls how strongly new information changes the weights.

  • A large α\alphaα produces larger updates.

  • A small α\alphaα produces smaller updates.

  • A learning rate of zero prevents learning.

  • An excessively large learning rate may cause unstable updates.

  • An excessively small learning rate may make learning slow.

The appropriate value depends on the problem and often requires experimentation.


Hard Thresholds and Soft Thresholds

A perceptron uses a hard threshold. It produces only two possible results:

  • 000

  • 111

The model immediately changes from one output to the other when the weighted sum crosses the threshold.

This is useful when only a categorical decision is needed, but it has limitations:

  • It provides no confidence score.

  • It cannot distinguish between a barely positive prediction and an extremely strong positive prediction.

  • It is mathematically difficult to work with in some optimization settings because of the abrupt step.

For example, two inputs may both be classified as rainy, even though one lies very close to the decision boundary and the other lies far inside the rainy region.

Logistic Regression

Logistic regression replaces the hard threshold with a smooth soft threshold, usually represented by a logistic or sigmoid function.

A typical logistic function is:

σ(z)=11+e−z\sigma(z)=\frac{1}{1+e^{-z}}σ(z)=1+e−z1​

where zzz is commonly the weighted sum:

z=w⋅xz=\mathbf{w}\cdot\mathbf{x}z=w⋅x

The output lies between 000 and 111:

0≤σ(z)≤10 \leq \sigma(z) \leq 10≤σ(z)≤1

This output can be interpreted as a confidence level or estimated probability. For example:

  • A value near 000 indicates strong evidence for class 000.

  • A value near 111 indicates strong evidence for class 111.

  • A value such as 0.70.70.7 indicates that class 111 is favored but not certain.

A soft threshold therefore gives more information than a hard threshold and has useful mathematical properties for optimization.


Support Vector Machines

A support vector machine, or SVM, is a classification method that attempts to find a decision boundary with the best possible generalization.

Many different lines may separate the training examples correctly. However, a boundary that lies very close to one category may perform poorly on new examples.

Maximum-Margin Separator

The SVM seeks a maximum-margin separator: a boundary that maximizes the distance between the boundary and the closest examples from each class.

The margin is the region separating the boundary from the nearest data points.

A larger margin is generally preferred because:

  • It is less sensitive to small changes in the data.

  • It is less likely to classify nearby unseen points incorrectly.

  • It tends to generalize better beyond the training data.

Support Vectors

Support vectors are the training examples closest to the decision boundary.

These points are especially important because they determine the position of the maximum-margin boundary. The SVM attempts to maximize the distance between the boundary and these closest examples.

In two dimensions, the boundary is a line. In higher-dimensional spaces, the boundary is a hyperplane.

Nonlinear Classification

Some datasets cannot be separated effectively by a straight line. For example, one class may form a cluster in the center while another class surrounds it.

A straight line cannot cleanly separate these arrangements. SVM methods can operate in higher-dimensional spaces and construct more complex effective boundaries, such as circular boundaries in a two-dimensional visualization.

This allows them to address some cases of data that is not linearly separable.


Comparing Classification Approaches

Different classification algorithms can solve the same general problem but have different strengths and weaknesses.

Nearest-Neighbor Methods

  • Use nearby labeled examples.

  • Are intuitive and simple.

  • Can be affected by the choice of kkk.

  • May become slow with large datasets.

Perceptrons and Linear Models

  • Learn weights defining a linear boundary.

  • Can be efficient and interpretable.

  • Work best when a linear relationship is appropriate.

  • May struggle with strongly nonlinear data.

Support Vector Machines

  • Seek a boundary with a large margin.

  • Often generalize effectively.

  • Can handle higher-dimensional representations.

  • May involve more complex mathematics and parameter choices.

No algorithm is always best. Performance depends on:

  • The structure of the dataset

  • The number and type of features

  • The presence of noise and outliers

  • Whether the classes are linearly separable

  • The desired balance between speed, accuracy, and interpretability

Machine-learning practice commonly involves testing several algorithms and comparing their performance.


Regression

Regression is a supervised-learning task in which the output is a continuous numerical value rather than a discrete class.

For example, a company might want to predict sales from advertising spending.

The input could be:

  • Advertising budget

The output could be:

  • Expected sales

A dataset might contain one row for each month:

  • Amount spent on advertising

  • Actual sales during that month

The model attempts to learn a function:

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

With two numerical variables, the data can be plotted:

  • The horizontal axis represents advertising expenditure.

  • The vertical axis represents sales.

  • Each point represents one period of observed data.

A regression model may fit a line through the data. The line provides an estimated sales value for each possible advertising budget.

Unlike classification, regression does not divide the data into categories. It estimates a continuous relationship.


Evaluating Machine-Learning Models

A model produces a hypothesis that maps inputs to outputs. The model must be evaluated to determine how well it performs.

This evaluation can be viewed as an optimization problem:

  • Maximize an objective function, or

  • Minimize a cost function

In machine learning, the cost often includes a loss function.

Loss Functions

A loss function measures how poorly a model’s prediction matches the actual result.

For each example, the loss function considers:

  • The actual output

  • The predicted output

The individual losses can be combined into an overall empirical loss:

Total empirical loss=∑i=1nlossi\text{Total empirical loss} = \sum_{i=1}^{n}\text{loss}_iTotal empirical loss=∑i=1n​lossi​

A good model generally has a low loss, but minimizing training loss alone can cause overfitting.


The 000-111 Loss Function

The 000-111 loss function is commonly used for classification.

For a single 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\ne\hat{y} \end{cases}L(y,y^​)={01​if y=y^​if y=y^​​

where:

  • yyy is the actual label.

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

The function ignores how confident the model was and records only whether the prediction was correct.

The total loss is the number of incorrectly classified examples.

For instance, if a decision boundary misclassifies four training points, its total 000-111 loss is 444.


L1 Loss

For regression, the distance between the prediction and the actual value matters. Predicting sales of 2,9002{,}9002,900 when actual sales are 2,8002{,}8002,800 is better than predicting sales of 1,0001{,}0001,000.

L1 loss uses the absolute difference:

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

The total L1 loss is:

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

L1 loss measures how far predictions are from actual values and treats each unit of error proportionally.

It is often less strongly affected by extreme outliers than squared loss.


L2 Loss

L2 loss uses the squared difference:

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

The total L2 loss is:

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

Squaring the error penalizes large mistakes more severely than small mistakes.

For example:

  • An error of 222 produces a squared loss of 444.

  • An error of 101010 produces a squared loss of 100100100.

L2 loss is useful when large errors should be penalized strongly. However, because large deviations are squared, outliers can have a disproportionate influence.

Choosing Between L1 and L2 Loss

  • L1 loss may be preferable when the dataset contains many outliers that should not dominate the model.

  • L2 loss may be preferable when large errors are especially costly.

  • The appropriate loss function depends on the application and the type of errors that matter most.


Overfitting and Generalization

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

The purpose of training is not merely to memorize known examples. The model should learn general patterns that apply to unseen examples.

Examples of desired generalization include:

  • Using past weather data to predict future weather.

  • Using known counterfeit and authentic banknotes to classify new banknotes.

  • Using previous advertising and sales data to estimate future sales.

Classification Overfitting

Suppose a mostly linear pattern separates rainy and non-rainy days, but one unusual non-rainy day lies among the rainy examples.

A simple line may misclassify this one outlier but correctly capture the general pattern. A highly complex boundary could be drawn to classify every training example correctly, but that boundary might treat future points incorrectly.

The complex boundary has lower training loss but may have worse performance on unseen data.

Regression Overfitting

A simple line may provide a useful approximation between advertising and sales. A highly complex curve could be constructed that passes through every training point exactly.

Although this produces zero training error, it may fail to predict sales for a new advertising budget because it has memorized the training examples instead of learning the underlying relationship.

A model should not be judged only by how accurately it reproduces the training data; it should also be judged by how well it generalizes to unseen data.


Regularization

One way to reduce overfitting is to include model complexity in the cost function.

Without regularization, the objective may be:

Cost(h)=Empirical loss(h)\text{Cost}(h)=\text{Empirical loss}(h)Cost(h)=Empirical loss(h)

This encourages the model to minimize training errors, even if doing so requires a highly complicated hypothesis.

With regularization, the cost becomes:

Cost(h)=Empirical loss(h)+λ⋅Complexity(h)\text{Cost}(h) = \text{Empirical loss}(h) + \lambda\cdot\text{Complexity}(h)Cost(h)=Empirical loss(h)+λ⋅Complexity(h)

where:

  • Empirical loss(h)\text{Empirical loss}(h)Empirical loss(h) measures prediction errors.

  • Complexity(h)\text{Complexity}(h)Complexity(h) measures how complicated the hypothesis is.

  • λ\lambdaλ controls the strength of the complexity penalty.

Regularization is the process of penalizing complex hypotheses in order to favor simpler models that are more likely to generalize.

The Regularization Parameter

The value of λ\lambdaλ determines the trade-off between fitting the training data and maintaining simplicity.

  • A large λ\lambdaλ strongly penalizes complexity.

  • A small λ\lambdaλ allows more complex hypotheses.

  • A value that is too large may cause underfitting.

  • A value that is too small may not prevent overfitting.

This reflects an Occam’s-razor principle: when several models perform similarly, the simpler model is often preferred because it is more likely to generalize.


Cross-Validation

A model should be tested on data that was not used to train it. This provides evidence about whether it generalizes.

Holdout Cross-Validation

Holdout cross-validation divides the dataset into two separate subsets:

  • Training set: Used to learn model parameters.

  • Testing set: Used to evaluate the trained model.

The process is:

  1. Split the data into training and testing subsets.

  2. Train the model using only the training set.

  3. Generate predictions for the testing set.

  4. Compare predictions with the known testing labels.

  5. Calculate accuracy or another evaluation measure.

If a model performs well on training data but poorly on testing data, it may be overfitting.

The testing data must remain separate from training so that it provides an honest evaluation of performance on unseen examples.

Limitations of a Single Holdout Split

A single split may waste data:

  • Some data is reserved for testing and cannot be used for training.

  • The measured performance may depend heavily on which examples happen to be placed in each subset.

  • A 50/50 split provides a simple evaluation but may not use the available data efficiently.


kkk-Fold Cross-Validation

kkk-fold cross-validation divides the dataset into kkk subsets, called folds.

For example, with 101010 folds:

  1. Train on nine folds and test on the remaining fold.

  2. Repeat the process while changing which fold is held out.

  3. Continue until every fold has served as the testing fold.

  4. Record the performance from each experiment.

  5. Average the results.

Each example is used:

  • For training in most experiments

  • For testing in exactly one experiment

The average performance provides a more stable estimate than a single train-test split.

Cross-validation separates the data used for learning from the data used for evaluation, helping determine whether a model has learned general patterns rather than memorized examples.


Applying Machine Learning with scikit-learn

Python libraries can provide implementations of common machine-learning algorithms. scikit-learn includes models for:

  • Perceptron learning

  • Support vector classification

  • Nearest-neighbor classification

  • Many additional supervised-learning methods

Using a library allows a programmer to apply these algorithms without implementing every mathematical detail manually.

Banknote Classification Example

A banknote dataset contains rows representing individual banknotes. Each row includes:

  • Four numerical measurements serving as input features

  • A label indicating whether the note is authentic or counterfeit

The labels can be encoded numerically:

  • 000: Authentic

  • 111: Counterfeit

The goal is to learn a function that maps the four measurements to the correct label.

Preparing the Data

The dataset is separated into:

  • Evidence or feature vectors, containing the four measurements

  • Labels, containing the correct classification

The feature and label lists must remain aligned. The label at position iii must correspond to the feature vector at position iii.

Training and Testing Procedure

A typical workflow is:

  1. Load the banknote data.

  2. Separate each row into features and label.

  3. Randomly shuffle the examples.

  4. Divide the data into training and testing subsets.

  5. Train the model on the training features and labels.

  6. Generate predictions for the testing features.

  7. Compare predictions with the actual testing labels.

  8. Count correct and incorrect predictions.

  9. Calculate the overall accuracy.

The dataset can be used with several different models, including:

  • A perceptron

  • A support vector classifier

  • A nearest-neighbor classifier

Different models may produce different results on the same data. In one experiment, all three approaches performed very well, with the nearest-neighbor model using three neighbors correctly classifying every testing example. Such results depend on the particular random split and dataset; an algorithm that performs best in one situation may not perform best in another.

Automated Data Splitting

scikit-learn provides a train_test_split function that automatically divides data into training and testing sets.

The programmer specifies the proportion of data reserved for testing. For example, a testing proportion of 0.50.50.5 reserves half the examples for testing.

Library functions can simplify:

  • Data splitting

  • Model training

  • Prediction generation

  • Counting correct predictions

  • Measuring accuracy


Reinforcement Learning

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

Instead, an agent learns through interaction with an environment.

The agent:

  1. Observes its current state.

  2. Chooses an action.

  3. Receives a new state.

  4. Receives a numerical reward or punishment.

  5. Uses that experience to improve future decisions.

The reward is typically:

  • Positive for desirable outcomes

  • Negative for undesirable outcomes

  • Sometimes zero for neutral outcomes

Reinforcement learning: Learning what actions to take through experience and feedback from rewards or punishments.

Examples

Reinforcement learning can train:

  • A physical robot to walk

  • A virtual agent to navigate a world

  • A game-playing program

  • An agent that learns which actions lead to long-term success

A robot does not necessarily need explicit instructions for every movement. It can receive rewards for moving forward and punishments for falling, gradually learning actions that improve its performance.


Markov Decision Processes

A reinforcement-learning environment is often represented as a Markov decision process, or MDP.

An MDP models:

  • States

  • Available actions

  • Transitions between states

  • Rewards associated with transitions

States

A state describes the current situation of the agent.

Examples include:

  • The current position of a robot in a grid

  • The current configuration of a game

  • The current state of an explored environment

Actions

An action is a choice available to the agent in a given state.

For example, an agent in a grid might be able to:

  • Move up

  • Move down

  • Move left

  • Move right

The available actions may differ from one state to another.

Transition Model

The transition model describes the probability of reaching a new state after taking an action.

It is conditioned on both:

  • The current state sss

  • The selected action aaa

The transition probability can be represented as:

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

where s′s's′ is the next state.

In a deterministic environment, a particular state-action pair always produces the same next state. In a stochastic environment, the same action may lead to different next states with different probabilities.

Reward Function

The reward function specifies the reward associated with a transition:

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

This represents the reward received when the agent:

  1. Begins in state sss.

  2. Takes action aaa.

  3. Transitions to state s′s's′.

The total reward accumulated over multiple actions determines how successful the agent has been.

Relationship to Markov Chains

A Markov chain describes transitions between states based on probabilities, without giving an agent control over the process.

An MDP extends this idea by allowing the agent to choose actions. Each action may have its own transition probabilities and rewards.


Learning in a Grid Environment

Consider an agent navigating a grid containing:

  • A starting state

  • A goal state with a positive reward

  • Red or dangerous states with negative rewards

  • Other neutral states

Initially, the agent may not know:

  • Which states contain rewards

  • Which states contain punishments

  • Which actions lead toward the goal

  • Which actions should be avoided

The agent explores by taking actions and observing the results.

For example:

  • If moving right from a particular state produces a punishment, the agent learns to avoid that action from that state.

  • If moving down from another state leads to punishment, the agent records that association.

  • If moving up eventually leads to a reward, the agent learns that the action is valuable.

  • If moving left leads to a state from which the goal can later be reached, the agent may learn the value of that sequence.

Over time, the agent learns both:

  • Actions that are immediately beneficial or harmful

  • Actions that lead to beneficial states in the future


Q-Learning

Q-learning is a reinforcement-learning method that learns a function QQQ.

The function takes a state-action pair as input:

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

It estimates the value of taking action aaa in state sss.

The value reflects the expected amount of reward obtainable from that decision, including possible future rewards.

Initial Values

Before the agent has any experience, it can initialize all state-action values to zero:

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

As the agent interacts with the environment, it updates these estimates based on observed outcomes.

Current and Future Rewards

When the agent takes an action, it receives an immediate reward rrr. However, the action may also lead to future rewards.

A good action may:

  • Produce an immediate reward

  • Lead to a state from which future rewards are likely

  • Produce no immediate reward but create a path toward a valuable future outcome

Therefore, Q-learning considers both:

  • The reward received immediately

  • The estimated value of future actions

A common update rule is:

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+\gamma\max_{a'}Q(s',a')-Q(s,a) \right]Q(s,a)←Q(s,a)+α[r+γmaxa′​Q(s′,a′)−Q(s,a)]

where:

  • Q(s,a)Q(s,a)Q(s,a) is the current estimate.

  • rrr is the immediate reward.

  • s′s's′ is the next 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 estimated value of the best future action.

  • γ\gammaγ is a discount factor for future rewards.

  • α\alphaα is the learning rate.

The term inside brackets is the difference between the new estimate and the old estimate.

Learning Rate in Q-Learning

The learning rate determines how much new experience changes the current value.

An equivalent update form is:

Qnew(s,a)=Qold(s,a)+α(new estimate−Qold(s,a))Q_{\text{new}}(s,a) = Q_{\text{old}}(s,a) + \alpha \left( \text{new estimate} - Q_{\text{old}}(s,a) \right)Qnew​(s,a)=Qold​(s,a)+α(new estimate−Qold​(s,a))
  • If α=1\alpha=1α=1, the new estimate completely replaces the old one.

  • If α=0\alpha=0α=0, the old value remains unchanged.

  • A value between 000 and 111 balances new and previous experience.

The learning rate allows the agent to preserve useful information from earlier experiences instead of responding entirely to the most recent outcome.

Discounting Future Rewards

The discount factor γ\gammaγ controls how much future rewards matter compared with immediate rewards.

  • A larger γ\gammaγ places greater value on future rewards.

  • A smaller γ\gammaγ emphasizes immediate rewards.

  • Discounting reflects situations in which an immediate reward is more valuable than an equivalent reward received much later.

The chosen value depends on the task and the programmer’s goals.


Policies: Exploitation and Exploration

Once Q-learning has estimated values for different actions, the agent can choose the action with the highest estimated value:

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

This is a greedy policy. It always exploits the agent’s current knowledge.

Exploitation

Exploitation means choosing the action currently believed to be best.

Advantages include:

  • Taking actions known to produce rewards

  • Using accumulated experience

  • Producing reliable behavior based on current knowledge

However, exploitation alone can prevent the agent from discovering better possibilities.

Exploration

Exploration means trying actions whose values are uncertain or that have not been tried sufficiently.

Exploration may reveal:

  • A faster route to a goal

  • A larger future reward

  • A better strategy than the one currently known

An agent that never explores may repeatedly use an acceptable but inefficient strategy.

The Exploration-Exploitation Trade-Off

Reinforcement learning must balance:

  • Exploiting known good actions

  • Exploring alternatives that might be better

This is one of the central challenges of reinforcement learning.


Epsilon-Greedy Algorithm

The epsilon-greedy algorithm introduces random exploration.

The parameter ϵ\epsilonϵ represents the probability of choosing a random action.

  • With probability 1−ϵ1-\epsilon1−ϵ, the agent chooses the currently best action.

  • With probability ϵ\epsilonϵ, the agent chooses a random action.

Thus:

P(best action)=1−ϵP(\text{best action})=1-\epsilonP(best action)=1−ϵ
P(random action)=ϵP(\text{random action})=\epsilonP(random action)=ϵ

A larger ϵ\epsilonϵ produces more exploration. A smaller ϵ\epsilonϵ produces more exploitation.

A common strategy is to use a larger ϵ\epsilonϵ early in learning and gradually reduce it as the agent becomes more knowledgeable.


Reinforcement Learning in Games

Game playing is a natural application of reinforcement learning.

The agent can play repeatedly and receive a final reward:

  • Positive reward for winning

  • Negative reward for losing

The agent does not need to be told which intermediate actions are good. It learns by connecting earlier decisions with eventual game outcomes.

Nim

Nim is a two-player game involving several piles of objects.

For example, the piles may contain:

  • One object

  • Three objects

  • Five objects

  • Seven objects

On each turn, a player:

  1. Selects exactly one pile.

  2. Removes at least one object from that pile.

  3. May remove any number of objects from the selected pile.

The player who removes the final object loses.

Representing Nim for an AI

A state can be represented by the number of objects in each pile:

(s1,s2,s3,s4)(s_1,s_2,s_3,s_4)(s1​,s2​,s3​,s4​)

An action specifies:

  • Which pile is selected

  • How many objects are removed

The reward is given at the end:

  • The player forced to remove the final object receives a punishment.

  • The other player receives a reward.

Self-Training

An AI can play Nim against itself repeatedly:

  1. The AI selects actions.

  2. The game reaches an outcome.

  3. The AI receives a reward or punishment.

  4. The AI updates its Q-values.

  5. The process repeats across many games.

With no training, the AI may act randomly and be easy to defeat. After thousands of self-play games, it can learn which state-action combinations are favorable and which are dangerous.

Self-play allows an agent to learn without requiring a human to label every possible move.


Function Approximation in Reinforcement Learning

Small games such as Nim have a manageable number of states. Larger environments, such as chess, may contain enormous numbers of possible states and actions.

It may be infeasible to store a separate Q-value for every state-action pair.

Function approximation addresses this problem by estimating values using features of the state rather than memorizing every exact state.

The approximating function may learn patterns such as:

  • Certain positions are generally favorable.

  • Certain features indicate danger.

  • An action that works in one state may work in another similar state.

Function approximation allows knowledge to generalize across related states. It is especially useful when the state space is too large to explore completely.


Unsupervised Learning

Unsupervised learning uses data without labeled outputs.

In supervised learning, examples are labeled as:

  • Rain or no rain

  • Authentic or counterfeit

In unsupervised learning, the computer receives only the input data and must discover patterns or structure on its own.

Unsupervised learning: Finding structure in data when no correct labels or output values are provided.

A major unsupervised-learning task is clustering.

Clustering

Clustering organizes objects into groups whose members are similar to one another.

The algorithm is not told what the groups represent. It must identify them from the relationships among the data points.

Applications include:

  • Grouping genetically similar genes

  • Dividing image pixels into regions

  • Segmenting consumers for market research

  • Identifying natural groups within scientific data


kkk-Means Clustering

kkk-means clustering divides data into kkk clusters.

The algorithm represents each cluster by a center, called its mean or centroid.

The basic process is iterative.

Step 1: Choose the Number of Clusters

The programmer selects a value for kkk, such as 333.

The choice of kkk determines how many groups the algorithm will attempt to find. Different values can be tested to determine which produces the most useful organization.

Step 2: Initialize Cluster Centers

The algorithm begins by placing kkk cluster centers, often at random locations.

For k=3k=3k=3, there would initially be three centers.

Step 3: Assign Points to the Nearest Center

Each data point is assigned to the cluster whose center is closest.

This creates an initial division of the data into kkk groups.

Step 4: Recenter the Clusters

For each cluster, the algorithm calculates the average location of all assigned points and moves the cluster center to that average.

A center may move toward the side of the cluster containing more points.

Step 5: Repeat

The algorithm repeatedly:

  1. Assigns each point to its closest center.

  2. Recalculates each center as the mean of its assigned points.

  3. Moves the centers.

  4. Reassigns points as necessary.

The assignments can change when the centers move.

Step 6: Stop at Equilibrium

The process ends when assignments stop changing, or when the changes become sufficiently small.

At that point, the algorithm has reached an approximate equilibrium in which each point belongs to the cluster whose center is closest.

The final clusters represent groups of data points that are more similar to one another than to points in other groups.

kkk-means clustering discovers groups from unlabeled data by alternating between assigning points to the nearest center and moving each center to the mean of its assigned points.


Major Categories of Machine Learning

Supervised Learning

  • Uses labeled input-output pairs.

  • Learns a function connecting inputs to known outputs.

  • Includes classification and regression.

  • Examples include banknote authentication, weather prediction, and sales estimation.

Reinforcement Learning

  • Learns through interaction with an environment.

  • Uses rewards and punishments rather than predefined labels.

  • Involves states, actions, transitions, and rewards.

  • Examples include robotics, game playing, and navigation.

Unsupervised Learning

  • Uses data without labels.

  • Discovers patterns, structure, or groups.

  • Includes clustering.

  • Examples include genetic analysis, image segmentation, and customer grouping.

Machine learning methods differ in how they use data and feedback, but all attempt to extract useful patterns that allow a computer to make decisions, predictions, or organizational judgments from information.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent