Machine Learning Foundations
Machine Learning: Foundations, Data Preparation, Supervised Learning, and Model Evaluation
1. What Machine Learning Is
Machine learning (ML) is a branch of artificial intelligence in which algorithms learn patterns from data and use those patterns to make predictions or decisions. Rather than receiving a complete set of rules for every possible situation, a learning system infers useful rules from examples.
A traditional computer program receives data and explicit instructions, then produces an output. A machine-learning system instead uses examples of data and, depending on the learning method, may also receive desired outputs. The algorithm uses these examples to construct a model: a learned representation of patterns that can be applied to new data.
The experience–task–performance definition
A program is said to learn from experience E with respect to a task T and a performance measure P when its performance on tasks in T, as measured by P, improves with experience E.
For a self-driving vehicle:
Task T: Driving on highways using vision sensors.
Performance measure P: The distance traveled before a driving error, such as swerving out of the lane.
Experience E: Recorded images and steering actions from observing human driving.
As the system receives more relevant experience, its measured performance should improve. The important distinction is that the system is designed to learn how to perform the task, rather than being given an exhaustive list of driving rules.
Traditional programming compared with machine learning
In traditional programming, a developer supplies the rules that transform inputs into outputs:
Traditional programming: Data + explicit program → output
Machine learning: Data + desired outputs → learned program or model
For example, writing a traditional program to identify every possible kind of cake would require manually specifying many rules about shape, color, decoration, and other properties. Exceptions would need additional rules. A machine-learning approach can instead learn patterns from many labeled cake images, then use those patterns to recognize previously unseen examples.
Machine learning does not eliminate the need for human decisions. People still choose the data, define the task, select and train models, and evaluate results. The difference is that the model infers patterns from examples rather than relying solely on explicitly written rules.
Core capabilities and characteristics
Learning from data: Algorithms infer patterns from examples rather than requiring a separate hand-written rule for every case. A spam filter can learn from labeled emails and recognize combinations of text patterns associated with spam.
Adaptability and improvement: A model can be retrained or updated as new data becomes available. A recommendation system can adjust as a user’s interests change.
Handling large data volumes: ML systems can analyze datasets too large or complex for people to inspect manually. Financial systems, for example, can examine large numbers of transactions to identify suspicious activity.
Automating repetitive tasks: Models can handle recurring tasks, such as answering routine customer-service questions, allowing people to focus on less standardized issues.
Personalization: Systems can use an individual’s behavior to tailor recommendations, playlists, or other experiences.
Addressing complex problems: ML can detect patterns in complex data, such as faint variations in medical images that may be associated with early disease.
2. The Three Main Types of Machine Learning
The three principal learning types differ in the information available during learning and in how a system receives feedback.
Supervised learning
Supervised learning uses labeled examples: each training input is paired with its correct output. The algorithm learns a mapping from inputs to outputs by comparing its predictions with known answers.
Data: Labeled.
Feedback: Predictions can be compared with correct outputs.
Typical goal: Predict an output for a new input.
For example, a clinic dataset might contain patient features such as age and gender, along with labels indicating whether each patient is healthy or sick. The model learns relationships between the features and health labels, then predicts a label for a new patient.
Common supervised algorithms include linear regression, logistic regression, decision trees, and support vector machines.
Unsupervised learning
Unsupervised learning uses data without supplied labels. The algorithm searches for structure, similarities, groups, or other patterns without being told the correct answer for each example.
Data: Unlabeled.
Feedback: No known target answer is supplied during learning.
Typical goal: Discover structure in the data.
For example, an algorithm could analyze patient age, gender, and blood-test results without being told who is healthy or sick. It might identify groups of patients with similar characteristics, potentially revealing a pattern that was not specified in advance.
Clustering and principal component analysis are examples of unsupervised methods.
Reinforcement learning
Reinforcement learning trains an agent to act in an environment and learn from the consequences of its actions. Instead of receiving the correct action for every situation, the agent receives rewards or penalties and seeks to maximize its cumulative reward.
Learner: An agent that takes actions.
Environment: The world or system with which the agent interacts.
Feedback: Rewards or penalties resulting from actions.
Typical goal: Learn a strategy that produces strong long-term outcomes.
Rewards may be delayed. A move in a game may provide no immediate benefit but help create a winning position later. The agent must therefore learn to value future rewards, not just immediate ones. Reinforcement learning is used in applications such as game-playing systems and robots learning to walk or maintain balance.
3. The Machine-Learning Lifecycle
A machine-learning project is an iterative process that turns raw data into a model capable of making predictions on new examples.
Collect input data. Data may be structured, such as spreadsheet columns, or unstructured, such as text and images.
Process and clean the data. Missing values, inconsistent formats, noisy measurements, and outliers may need to be addressed.
Select or construct features. Features are the variables used by a model. Removing irrelevant information can reduce noise and complexity.
Select a model. The algorithm is chosen to suit the task and the available data.
Train the model. The algorithm uses training data to learn patterns or relationships.
Evaluate the model. Its performance is tested, ideally on data not used to train it.
Tune and revise. If performance is inadequate, features, model choices, or hyperparameters can be adjusted and the process repeated.
Deploy the model. After sufficient testing and refinement, the model can be used to make predictions on new data.
This process is iterative, not simply a one-time sequence. Evaluation may reveal problems that require additional data preparation, feature changes, model selection, or tuning.
Training, testing, and generalization
A model should not be judged only by how well it performs on its training data. A model that merely memorizes training examples may perform poorly on new cases. Testing on unseen data helps determine whether the model has learned patterns that generalize beyond the examples it was given.
Hyperparameters
Hyperparameters are settings chosen to guide the learning process rather than values learned directly from the training examples. Tuning them can improve a model’s performance. The process resembles adjusting settings after observing a result: a model is trained, evaluated, adjusted, and retrained until a suitable performance level is reached.
4. Machine Learning in the Broader Technology Landscape
Artificial intelligence (AI) is the broad field concerned with making computers perform tasks associated with intelligent behavior. Machine learning is one approach within AI: systems use data to learn patterns rather than relying entirely on explicitly programmed rules. Deep learning is a specialized area within machine learning that uses layered neural networks to learn complex representations.
Data science is the broader practice of extracting knowledge and insight from data. It overlaps with AI and machine learning but is not simply another level in the same nested hierarchy. It can involve methods and work beyond machine learning, including data analysis, interpretation, and communication.
Machine learning supports applications across many fields:
Recommendations: Collaborative filtering identifies users with similar patterns of preferences. If two users liked the same films, a system may recommend a film liked by one user to the other.
Finance: Fraud-detection systems can examine transaction details—such as location, timing, purchase history, and merchant information—to flag unusual activity.
Medicine: Models trained on medical images can detect image patterns associated with illness, including subtle variations that may be difficult for a person to notice.
Robotics and transportation: Learning systems can help vehicles interpret their surroundings and help robots develop effective movements.
Machine learning is particularly useful when data is too large or complex for people to inspect manually. Its speed, scale, and ability to identify patterns across many variables extend the kinds of analysis that can be performed in fields such as medicine, finance, physics, astronomy, and internet services.
5. High-Dimensional Data and Dimensionality Reduction
A dataset’s dimensionality is the number of features or variables it contains. A dataset with thousands of columns has high dimensionality. High-dimensional datasets can be difficult to analyze and can create computational and statistical challenges.
The curse of dimensionality
The curse of dimensionality refers to the difficulties that arise as the number of features increases. The volume of the space represented by the features grows rapidly, and data points may become sparse within that space.
High dimensionality can:
Increase training and processing time.
Make it harder to identify meaningful patterns.
Increase the chance that a model will be distracted by irrelevant information.
Make distance-based comparisons less useful when the data is sparse.
For example, a high-resolution image can be represented using a very large number of pixel features. A text dataset may have a feature for each word in a large vocabulary. Both can produce data with many dimensions.
Dimensionality reduction
Dimensionality reduction transforms high-dimensional data into a lower-dimensional representation while aiming to preserve the most important information or structure.
The goal is not to discard information indiscriminately. Instead, the method seeks a compact representation that retains the patterns useful for analysis or prediction. Reducing dimensionality can make data easier to process, visualize, and model.
6. Datasets as Matrices
Machine-learning datasets are commonly represented as matrices, or structured grids of values.
Rows usually represent individual instances or observations.
Columns usually represent features or other variables recorded for each instance.
In a clinic dataset, one row might represent one patient, while columns could contain that patient’s age, gender, test results, and—if the task is supervised—a health label.
A row vector represents the values for one instance. A column vector represents the values of one feature across many instances. This structure allows algorithms to compare features, identify relationships, group similar observations, and perform mathematical operations on the data.
7. Data Preprocessing
Raw data often requires preparation before a model can use it reliably. A common preprocessing workflow includes cleaning, transformation, and reduction.
Data cleaning
Cleaning addresses problems such as:
Missing values: A value may be absent because a measurement was not recorded. One possible strategy is imputation—for example, replacing a missing age with the average age of the other cases. The appropriate strategy depends on the data and the task.
Noisy data: Measurements may contain random errors or inconsistent variation.
Outliers: Some values may be unusually distant from the rest of the data and may require investigation or special handling.
Keeping a record with a missing value can sometimes be preferable to discarding the entire instance, but imputation methods can also affect the data’s meaning. Cleaning decisions should therefore be appropriate to the context.
Data transformation: normalization and standardization
Features can be measured on very different scales. For example, the number of bedrooms in a house might range from one to five, while area might range from roughly one thousand to five thousand square feet. Some algorithms may give greater influence to a feature with larger numerical values simply because of its scale.
Standardization rescales features so that they are on comparable scales. A common approach transforms values so that a feature has mean 0 and standard deviation 1. Normalization is another family of scaling methods that adjusts values according to a chosen range or scale.
Scaling can help prevent a large-valued feature from dominating a model for reasons unrelated to its actual importance. It is especially important for methods whose calculations depend on distances or variance, including PCA and many applications of support vector machines.
Data reduction
Data reduction decreases the amount or complexity of data used in modeling. Dimensionality reduction is one form of data reduction: it reduces the number of features or replaces them with a smaller set of representations.
8. Feature Selection and Feature Extraction
Feature selection and feature extraction both aim to reduce or simplify the information used by a model, but they do so differently.
Feature selection
Feature selection keeps a subset of the original features and removes the rest. If a dataset contains age, blood pressure, hair color, and other variables, a selection method might retain age and blood pressure while excluding features judged irrelevant to the task.
The original meaning of the selected features remains intact.
Two iterative approaches are:
Forward selection: Begin with no features. Add the feature that most improves the model, then repeatedly add useful features until additional features no longer help sufficiently.
Backward selection: Begin with all features. Repeatedly remove the least useful feature until further removal harms model performance.
Feature extraction
Feature extraction transforms the original features into a new, usually smaller set of features. These new features combine information from the originals and may be more compact or informative for a particular task.
Unlike selection, extraction does not simply keep a subset of the original columns. The resulting features may not have direct, intuitive meanings. Principal component analysis is a major example of feature extraction.
9. Principal Component Analysis
Principal component analysis (PCA) is a dimensionality-reduction method that creates new features called principal components. It finds directions in the data that capture large amounts of variation and represents the observations using those directions.
Variance and principal components
Variance describes how spread out values are. In PCA, the first principal component is the direction along which the data has the greatest variance. The second principal component captures the greatest remaining variance subject to being orthogonal—at a right angle—to the first. Further components capture progressively smaller amounts of remaining variation.
A feature with no variation provides no distinctions among observations. For example, if every patient in a dataset has the same age, age cannot help distinguish one patient from another within that dataset.
PCA changes the coordinate system used to represent the data. Instead of describing each instance with all of its original features, it can describe the instance using a smaller number of principal components. A dataset with many original dimensions might therefore be represented by a smaller set of components while retaining much of its variation.
Benefits of PCA
Compression: A smaller number of components can reduce storage and processing requirements.
Noise reduction: Components that capture little systematic variation may be excluded, which can reduce the influence of some noise.
Addressing multicollinearity: Highly correlated original features can be represented by orthogonal principal components, reducing the direct redundancy between features.
Visualization: A high-dimensional dataset can be projected onto its leading components and plotted in two or three dimensions, making some clusters or broad patterns easier to inspect.
Limitations of PCA
Reduced interpretability: Principal components are combinations of original features, so they may not have an intuitive real-world meaning. A doctor, for example, may find it less useful to receive a prediction based on “component one” than one based directly on age or blood pressure.
Sensitivity to scaling: Features measured on larger numerical scales can dominate the variance calculations. Data generally needs to be scaled appropriately before PCA.
Linear structure: PCA captures directions of linear variation. It may not represent complex nonlinear relationships well.
Information loss: Keeping too few components can discard variation that is important to the task, even if those components account for less overall variance.
PCA is most useful when reducing dimensionality is worth the trade-off in interpretability and when its assumptions and preprocessing requirements are suitable for the data.
10. Supervised Learning in Detail
Supervised learning learns a function that maps inputs to outputs from labeled input-output examples. The inputs are commonly called features, and the known desired outputs are called labels or target outputs.
During training, the algorithm makes predictions and compares them with the known answers. The difference between a prediction and its target provides information used to adjust the model. Repeating this process enables the model to learn a mapping that can be applied to new examples.
For instance, a clinic model could use age and gender as features and healthy-or-sick status as the target label. After training on labeled patient records, it can estimate the status of a new patient based on the patient’s features. Such a prediction is not automatically a diagnosis; its reliability depends on the data, the model, and the way the system is evaluated.
The six-step supervised-learning workflow
Data collection: Gather examples containing features paired with correct outputs. A house-price dataset might pair square footage and other house characteristics with actual sale prices.
Data preprocessing: Clean the data, handle missing values, and scale features when appropriate.
Model selection: Choose an algorithm suited to the task and output type.
Training: Provide the labeled training examples so the model can learn relationships between features and targets.
Evaluation: Test performance using examples not used for training. This helps reveal whether the model generalizes or merely memorizes its training data.
Prediction: Use the trained model to generate outputs for new examples.
Regression and classification
The target output determines whether a supervised task is a regression or classification problem.
Regression
Regression predicts a continuous numerical value, such as:
A house’s sale price.
Next month’s revenue.
A person’s blood pressure.
Classification
Classification assigns an input to one of a set of categories, such as:
Spam or not spam.
Healthy or sick.
Cat, dog, or bird.
The type of output matters because algorithms and evaluation methods appropriate for predicting a number may differ from those appropriate for assigning categories.
11. Key Supervised-Learning Algorithms
Linear regression
Linear regression models a linear relationship between a target variable and one or more input features. It estimates a line or linear equation that represents the trend in the observed data.
Simple linear regression: Uses one input feature, such as house area, to predict a target such as sale price.
Multiple linear regression: Uses several features, such as area, number of bedrooms, house age, and location, to predict a target.
Linear regression is commonly used to predict continuous values. Its usefulness depends in part on whether a linear relationship is a reasonable approximation for the data.
Logistic regression
Despite its name, logistic regression is commonly used for classification. It estimates the probability that an example belongs to a category, rather than predicting an unrestricted continuous quantity.
Binary classification: Chooses between two categories, such as success and failure.
Multinomial classification: Handles three or more unordered categories, such as cat, dog, or bird.
Ordinal classification: Handles categories with a meaningful order, such as poor, good, and excellent.
The distinction between multinomial and ordinal classification is whether the categories have a natural ranking.
Decision trees
A decision tree is a hierarchical model that makes predictions through a series of tests, much like a flowchart.
The root node begins the decision process with a question or test.
Branches represent possible outcomes of a test.
Internal nodes apply additional tests.
Leaf nodes provide the final prediction or decision.
For example, a tree might first ask whether it is raining, then ask whether it is windy, and finally recommend whether an umbrella is needed. Decision trees can be used for both classification and regression.
Support vector machines
A support vector machine (SVM) is a supervised algorithm often used for classification. It seeks a decision boundary that separates categories while maximizing the distance between the boundary and the nearest data points from each category.
A hyperplane is the decision boundary. It is a line in two dimensions and a plane in three dimensions.
Support vectors are the data points closest to the boundary.
The margin is the distance between the boundary and the nearest support vectors.
A large margin can help a model generalize to unseen examples rather than fitting only the training data.
A hard-margin approach requires strict separation of the classes. It can be sensitive to outliers when real data is not cleanly separable. A soft-margin approach allows some violations of the boundary, often making the model more robust to noise and outliers.
12. Unsupervised Clustering with K-Means
K-means is an unsupervised clustering algorithm. It groups unlabeled data points into a specified number of clusters based on their similarity, typically measured using distance.
The number of clusters, K, must be selected before the algorithm runs. If K=3, for example, the algorithm seeks three clusters.
K-means procedure
Choose K. The person applying the method specifies the desired number of clusters.
Initialize centroids. The algorithm places K initial points, called centroids, in the data space.
Assign observations. Each data point is assigned to the cluster whose centroid is closest to it.
Update centroids. For each cluster, the algorithm calculates the center of its assigned points and moves the centroid to that center.
Repeat assignment and updating. Since centroids have moved, some data points may now be closer to a different centroid. The algorithm reassigns points and recalculates centers.
Stop when assignments stabilize. The process ends when centroids or assignments stop changing substantially, or when another stopping condition is reached.
The result is a partition of the data into groups. In customer analysis, for example, K-means could group customers with similar recorded characteristics even when no “premium customer” or “bargain shopper” labels are available.
The clusters are determined by the features and distance measure used. They do not automatically correspond to meaningful categories; interpretation requires examining the resulting groups and considering the application.
13. Ensembles and Boosting
Ensemble methods
An ensemble method combines predictions from multiple models to produce a result that may be more accurate or robust than the prediction of a single model.
The basic idea is that individual models can make different errors. Combining their outputs can reduce the impact of some errors and improve overall performance. For example, while an individual estimator may be far from the correct value, the average of many independent estimates can be more accurate.
Boosting
Boosting builds a strong model by combining a sequence of weaker learners. Its defining feature is that models are trained sequentially, with later models focusing on errors made by earlier ones.
A typical boosting process is:
Train an initial weak learner on the training data.
Identify examples the learner predicted incorrectly or poorly.
Give those difficult examples greater emphasis when training the next learner.
Train the next learner to address errors that remain.
Continue adding learners until a stopping condition is reached, such as a chosen limit on the number of models.
This sequence enables the ensemble to improve by focusing repeatedly on mistakes. However, continually fitting errors—including noise or peculiarities in the training set—can lead to overfitting. A model that matches training data extremely well may still perform poorly in a new environment, so evaluation on unseen data remains essential.
14. Evaluating Models and Understanding Errors
A model should be evaluated rather than assumed to work. Evaluation metrics provide different views of performance and can reveal different types of error.
Common evaluation measures
Accuracy: The proportion or percentage of predictions that are correct.
Confusion matrix: A table that compares predicted categories with actual categories, showing counts such as false positives and false negatives.
Precision: Among the examples predicted to be positive, the proportion that are actually positive.
Recall: Among the actual positive examples, the proportion the model correctly identifies.
F1 score: The harmonic mean of precision and recall, useful when both are important.
ROC curve: A graph showing how classification performance changes across decision thresholds.
AUC: The area under the ROC curve, a summary of the curve’s ability to distinguish between classes.
Error distribution: The spread and pattern of a model’s errors can show whether its predictions are consistent or vary widely.
No single metric tells the entire story. For example, accuracy may obscure poor performance on an important minority class, while precision and recall focus on different kinds of classification mistakes.
Mean absolute deviation
Mean absolute deviation (MAD) measures the average absolute distance of observations from their mean. For values x1,x2,…,xN with mean μ, it is calculated as
Here:
xi is an individual observation.
μ is the mean of the observations.
∣xi−μ∣ is the absolute distance of observation i from the mean.
N is the number of observations.
The summation adds the distances for all observations.
Absolute values are used because MAD measures distance, not direction. A point five units above the mean and a point five units below the mean each contribute a distance of five.
A high MAD indicates that observations are, on average, farther from the mean; a low MAD indicates that they are closer together. MAD is therefore a measure of spread. When applied to model errors, it can describe the average magnitude of deviations of those errors from their mean. It is distinct from simply calculating a model’s average prediction error.
15. Overfitting and Generalization
Overfitting occurs when a model fits the training data too closely, including details or noise that do not represent general patterns. Such a model can achieve very strong training performance yet make poor predictions on new data.
This risk can arise when a model has excessive complexity or when a sequential method such as boosting keeps focusing on training errors that reflect noise rather than useful structure. Testing with unseen data helps assess whether a model has learned patterns that generalize beyond its training examples.
The central goal is not merely to reproduce past data accurately. It is to learn patterns that support reliable performance on new cases.
16. Integrated Summary
Machine learning uses experience from data to improve performance on a task, rather than relying exclusively on hand-written rules.
The three main learning types are supervised learning with labeled examples, unsupervised learning that discovers structure in unlabeled data, and reinforcement learning based on actions and rewards.
Machine-learning work follows an iterative lifecycle of data collection, cleaning, transformation, feature preparation, model selection, training, evaluation, tuning, and deployment.
Dimensionality reduction addresses the challenges of high-dimensional data. Feature selection retains a subset of original features; feature extraction constructs new features from the originals.
PCA creates orthogonal components that capture decreasing amounts of variation. It can compress data and support visualization, but its components may be difficult to interpret and its results depend on appropriate scaling.
Supervised tasks are either regression, which predicts continuous values, or classification, which assigns categories.
Linear regression, logistic regression, decision trees, and SVMs provide different approaches to supervised prediction.
K-means repeatedly assigns data points to the nearest centroid and updates centroids to discover clusters in unlabeled data.
Ensembles combine multiple models, while boosting builds models sequentially so later learners focus on earlier errors.
Evaluation uses multiple measures, including accuracy, confusion matrices, precision, recall, F1, ROC, AUC, and measures of error spread such as MAD.
A model’s performance on unseen data is crucial: strong training performance alone does not establish that the model generalizes.

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