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:
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:
x1: Humidity
x2: Air pressure
The desired output is a category:
Rain
No rain
The unknown real-world relationship can be represented by a function f:
Because the exact function is unknown, the machine-learning algorithm attempts to learn a hypothesis function h that approximates it:
The quality of the learned model depends on how accurately h 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:
Receive an unlabeled input.
Measure its distance from the known data points.
Identify the closest data point.
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.
k-Nearest-Neighbor Classification
k-nearest-neighbor classification improves on single-neighbor classification by examining the k closest data points rather than only one.
The process is:
Choose a value for k, such as 3, 5, or 7.
Find the k nearest labeled data points.
Count how many neighbors belong to each class.
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 k
A small k makes the model sensitive to local details and individual outliers.
A larger k considers a broader region and may produce more stable predictions.
The best value of k 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:
x1 and x2 be input features.
w1 and w2 be their corresponding weights.
w0 be an additional constant, sometimes called a bias or intercept term.
The model calculates:
The weights determine the position and orientation of the boundary:
Changing w1 changes the influence of x1.
Changing w2 changes the influence of x2.
Changing w0 shifts the boundary.
A threshold-based classifier may be written as:
Here:
1 represents rain.
0 represents no rain.
The algorithm must learn suitable values for the weights so that rainy examples tend to produce 1 and non-rainy examples tend to produce 0.
Vector Representation and the Dot Product
The weights can be represented as a weight vector:
The input can be represented as:
The initial 1 in the input vector allows the bias weight w0 to participate in the same calculation:
The dot product of w and x is:
The hypothesis can therefore be written compactly as:
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
The correct output y
A current prediction h(x)
The algorithm compares the correct output with the prediction. A general update can be expressed as:
where:
wi is an individual weight.
y is the actual label.
h(x) is the predicted label.
xi is the corresponding input feature.
α 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:
Therefore:
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 α, controls how strongly new information changes the weights.
A large α produces larger updates.
A small α 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:
0
1
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:
where z is commonly the weighted sum:
The output lies between 0 and 1:
This output can be interpreted as a confidence level or estimated probability. For example:
A value near 0 indicates strong evidence for class 0.
A value near 1 indicates strong evidence for class 1.
A value such as 0.7 indicates that class 1 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 k.
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:
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:
A good model generally has a low loss, but minimizing training loss alone can cause overfitting.
The 0-1 Loss Function
The 0-1 loss function is commonly used for classification.
For a single example:
where:
y is the actual label.
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 0-1 loss is 4.
L1 Loss
For regression, the distance between the prediction and the actual value matters. Predicting sales of 2,900 when actual sales are 2,800 is better than predicting sales of 1,000.
L1 loss uses the absolute difference:
The total L1 loss is:
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:
The total L2 loss is:
Squaring the error penalizes large mistakes more severely than small mistakes.
For example:
An error of 2 produces a squared loss of 4.
An error of 10 produces a squared loss of 100.
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:
This encourages the model to minimize training errors, even if doing so requires a highly complicated hypothesis.
With regularization, the cost becomes:
where:
Empirical loss(h) measures prediction errors.
Complexity(h) measures how complicated the hypothesis is.
λ 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 λ determines the trade-off between fitting the training data and maintaining simplicity.
A large λ strongly penalizes complexity.
A small λ 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:
Split the data into training and testing subsets.
Train the model using only the training set.
Generate predictions for the testing set.
Compare predictions with the known testing labels.
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.
k-Fold Cross-Validation
k-fold cross-validation divides the dataset into k subsets, called folds.
For example, with 10 folds:
Train on nine folds and test on the remaining fold.
Repeat the process while changing which fold is held out.
Continue until every fold has served as the testing fold.
Record the performance from each experiment.
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:
0: Authentic
1: 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 i must correspond to the feature vector at position i.
Training and Testing Procedure
A typical workflow is:
Load the banknote data.
Separate each row into features and label.
Randomly shuffle the examples.
Divide the data into training and testing subsets.
Train the model on the training features and labels.
Generate predictions for the testing features.
Compare predictions with the actual testing labels.
Count correct and incorrect predictions.
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.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:
Observes its current state.
Chooses an action.
Receives a new state.
Receives a numerical reward or punishment.
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 s
The selected action a
The transition probability can be represented as:
where 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:
This represents the reward received when the agent:
Begins in state s.
Takes action a.
Transitions to state 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 Q.
The function takes a state-action pair as input:
It estimates the value of taking action a in state s.
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:
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 r. 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:
where:
Q(s,a) is the current estimate.
r is the immediate reward.
s′ is the next state.
a′ represents a possible next action.
maxa′Q(s′,a′) is the estimated value of the best future action.
γ is a discount factor for future rewards.
α 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:
If α=1, the new estimate completely replaces the old one.
If α=0, the old value remains unchanged.
A value between 0 and 1 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 γ controls how much future rewards matter compared with immediate rewards.
A larger γ places greater value on future rewards.
A smaller γ 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:
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 ϵ represents the probability of choosing a random action.
With probability 1−ϵ, the agent chooses the currently best action.
With probability ϵ, the agent chooses a random action.
Thus:
A larger ϵ produces more exploration. A smaller ϵ produces more exploitation.
A common strategy is to use a larger ϵ 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:
Selects exactly one pile.
Removes at least one object from that pile.
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:
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:
The AI selects actions.
The game reaches an outcome.
The AI receives a reward or punishment.
The AI updates its Q-values.
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
k-Means Clustering
k-means clustering divides data into k 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 k, such as 3.
The choice of k 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 k cluster centers, often at random locations.
For k=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 k 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:
Assigns each point to its closest center.
Recalculates each center as the mean of its assigned points.
Moves the centers.
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.
k-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.