Machine Learning Fundamentals
Fundamentals of Machine Learning
Machine learning is a way of solving problems in which a computer learns patterns from data instead of relying entirely on rules written by a programmer. It is one part of the broader field of artificial intelligence, which aims to create systems capable of performing tasks that normally require human intelligence.
The central idea is simple:
A machine-learning system uses examples to learn a relationship between inputs and desired outputs, then applies that learned relationship to new data.
For example, instead of programming thousands of rules that describe every possible spam email, a system can study many emails that have already been labeled as “spam” or “not spam.” It then learns patterns that help it classify future emails.
Traditional Programming Versus Machine Learning
In a traditional rule-based system, a programmer studies a problem and writes explicit instructions. These instructions often use conditions such as:
- If a message contains certain words, mark it as spam.
- If a customer is younger than a certain age, apply a particular rule.
- If a sound has a certain frequency, assign it to a particular category.
The programmer must anticipate the relevant situations and encode them manually. For a simple problem, this approach can work well. However, complex real-world problems often contain too many possibilities for every rule to be written by hand.
Machine learning changes the structure of the problem. Instead of manually specifying all the rules, the system receives data and learns patterns from it. The training data may contain labels, such as “spam” or “not spam,” or it may contain no labels at all.
A typical supervised learning process works as follows:
- A training dataset is collected.
- Each example is paired with a known label.
- A machine-learning algorithm studies the examples.
- The algorithm learns patterns connecting the inputs to the labels.
- The trained model receives new, unseen data.
- The model predicts the appropriate label for each new example.
- The predictions are evaluated to determine how well the model performs.
The important goal is not simply to memorize the training examples. The model should generalize, meaning that it should apply what it learned to new examples that were not included during training.
Example: Detecting Spam Email
Spam detection is a straightforward example of machine learning. The system receives an email as input and predicts one of two possible classes:
- Spam
- Not spam
Because there are two possible classes, this is a binary classification problem. A classification problem assigns an observation to one of several categories.
The input could be the email’s text itself or a processed version of that text. Text is often converted into a form that a computer can process, such as a sequence of tokens. A token might be a word, part of a word, or another meaningful unit of text.
A spam detector could learn from examples containing patterns such as unusual wording, repeated advertising language, or other characteristics associated with spam. The system is not required to use the exact same words in every future message. A strong model can recognize related patterns and therefore handle messages it has never seen before.
This ability to respond to new variations is especially important because spam changes over time. Advertisers and spammers may alter their wording when they notice that existing messages are being blocked. A fixed rule that once worked may eventually become ineffective.
Problems with Rule-Based Systems
A traditional rule-based spam detector can face several difficulties:
- It may require a very long and complicated collection of rules.
- Its rules may become outdated as messages change.
- Maintaining thousands of lines of code can be difficult and expensive.
- The rules may fail to cover unusual or newly emerging cases.
- The system may produce false positives, classifying legitimate emails as spam.
- Some problems, such as speech recognition, are extremely difficult to express as complete sets of manually written rules.
A machine-learning approach can be retrained when new data becomes available. If performance declines, the development team can investigate whether the problem lies in the data, the algorithm, or the way the system was built.
Advantages of Machine Learning
Compared with a large rule-based system, a machine-learning solution can offer several advantages:
- Less code may be needed to create a sophisticated model.
- The model can be updated as new examples become available.
- Problems can be analyzed and improved systematically.
- The model can discover patterns that are difficult to describe manually.
- It can generalize to new cases more effectively.
- In many applications, it can achieve higher accuracy than manually written rules.
The advantage does not come from machine learning automatically being correct. Its performance depends heavily on the quality and quantity of the data, the choice of algorithm, the preparation of the data, and the evaluation process.
Think About It
If spam messages continually change their wording, why would a learned model usually be more adaptable than a fixed list of rules?
How Machine-Learning Systems Are Classified
Machine-learning systems can be described along several independent dimensions. A single system may belong to one category in each dimension. For example, a spam filter could be supervised, online, and instance-based at the same time.
Supervised and Unsupervised Learning
Supervised Learning
Supervised learning uses a labeled training dataset. Each training example includes both:
- Input features
- A known target or label
For spam detection, the email is the input and the label is either spam or not spam. The model learns how the features of an email relate to its known classification.
Supervised learning is useful when the desired answer is known for the training examples and the goal is to predict that answer for new examples.
Unsupervised Learning
Unsupervised learning uses data without known labels. The algorithm must identify useful structure in the data without being told the correct category for each example.
The source distinguishes supervised and unsupervised learning based on whether the training set contains labels. The essential difference is whether the learning process is guided by known answers.
Offline, or Batch, Learning
Offline learning, also called batch learning, trains a model using a collected dataset. The model is trained away from the live production system. After its performance is checked, the new model can be placed into production.
A common process is:
- A model is trained on historical data.
- Its accuracy is evaluated.
- The model is deployed.
- New data is collected while the model operates.
- After a period of time, the accumulated data is used to train an updated model.
- The updated model replaces the older production model.
This process may occur after several months or even a year or more, depending on how quickly the data changes and how frequently the organization needs to update the model.
Online Learning
Online learning updates a model as new observations arrive. Instead of waiting for a large collection of new data, the system retrains or adjusts the model frequently, perhaps every night or whenever new instances become available.
Online learning can respond quickly to changes in the data, but it introduces an important risk: new data may be poor-quality, misleading, or unusual. If bad data is repeatedly used for training, the model may gradually become worse.
A safeguard is to use a fail switch or performance threshold. The newly trained model is compared with the current production model using a fixed evaluation set. If the new model performs worse than the existing one, it is not deployed.
A system that learns continuously from uncontrolled data can deteriorate over time. For example, a model trained on social-media messages might begin producing nonsensical or offensive output if the incoming messages contain harmful or low-quality patterns. The model is reflecting the data it receives, even when those patterns are undesirable.
Think About It
Why might online learning be valuable in a rapidly changing environment, yet dangerous when the incoming data is not carefully monitored?
Predictive and Instance-Based Models
Another distinction concerns what the model does with the information it learns.
Predictive Learning
A predictive model learns to predict a target value from input features. When the target is numerical, the task is often called regression. For example, a model might predict a numerical outcome based on a set of measurements.
The model attempts to learn a general relationship between inputs and outputs and then uses that relationship to generate predictions for new observations.
Instance-Based Models
An instance-based model compares new observations with existing examples or categories. The source gives K-nearest neighbors, or KNN, as an example. In KNN, a new data point is assigned according to nearby points or the region in which it falls.
A classification system can also be viewed in this way when it places new data points into existing categories. For example, a new observation may be assigned to one of several regions based on the examples already associated with those regions.
These categories are not mutually exclusive with supervised or online learning. A model might be:
- Supervised because its examples have labels
- Instance-based because it assigns new observations to existing groups
- Online because it updates as new observations arrive
The best combination depends on the problem being solved.
Stages of a Machine-Learning Project
Building a machine-learning model is only one part of a complete project. A successful project begins with a business problem, continues through data analysis and preparation, and ends with deployment and communication.
1. Understand the Business Problem
The first stage is to define the problem clearly with the relevant stakeholders. A technical model is useful only if it helps solve a meaningful organizational problem.
The project team should determine:
- What problem needs to be solved?
- Why does the problem matter?
- What outcome should the model support?
- What data is available?
- How will success be measured?
- What constraints affect the solution?
- How will the model be used after it is built?
Stakeholders often possess important domain knowledge. For example, insurance specialists and actuaries understand the business context surrounding accident prediction. Their knowledge can help data scientists interpret variables correctly, identify realistic assumptions, and avoid solving the wrong problem.
A data scientist who focuses only on technical measures may overlook the real purpose of the project. Measures such as accuracy, root mean squared error, or the Gini index matter only when they connect to the business objective.
The first output of this stage should be a plan describing how the problem will be investigated and solved.
2. Perform Exploratory Data Analysis
After the problem is understood, the team begins exploratory data analysis, or EDA. EDA involves examining the available data to understand its structure, quality, patterns, and limitations.
The analysis may reveal:
- Which variables are available
- Whether the data actually represents the business problem
- Whether values are missing
- Whether unusual or impossible values exist
- How features relate to the target
- Whether features are related to one another
- Whether visible patterns support the proposed modeling approach
EDA is not merely a preliminary chore. It can sometimes provide enough useful information that a complex model is unnecessary. For example, dashboards and visual summaries may reveal trends that allow the business to make better decisions directly.
The team should return to stakeholders after obtaining initial insights. Stakeholders can help determine whether the findings are sensible, familiar, and relevant. Showing plots and summaries also gives them a concrete understanding of the analysis.
Forming Hypotheses
EDA supports the formation of hypotheses. A team might plot the target against individual features and ask whether a visible relationship suggests that a feature could help predict the target.
The team should also examine correlations:
- Correlation between a feature and the target
- Correlations among different features
Correlation can provide useful clues, but it does not by itself prove that a relationship is meaningful or causal. It is a tool for understanding the data and forming initial ideas.
Features should not be inserted into a model without understanding what they represent and how they relate to the business. A feature may appear statistically useful while being difficult to interpret or unsuitable for the intended application.
3. Design the ETL Process
ETL stands for Extract, Transform, and Load.
- Extract: Obtain data from raw sources.
- Transform: Clean, restructure, combine, and modify the data.
- Load: Place the prepared data into a location where it can be used for analysis or modeling.
Raw data often comes from multiple sources and may not be organized in a form suitable for a model. An ETL process helps combine those sources and consistently prepare them.
The process should be designed as an architecture or workflow rather than as a collection of one-time manual actions. If the model must be retrained later, the same transformations should be applied again. A repeatable ETL process prevents the team from rebuilding the entire preparation process from scratch.
4. Prioritize Data Quality and Quantity
A sophisticated algorithm cannot reliably compensate for poor data. If the training examples are inaccurate, incomplete, or unrepresentative, the resulting model may also be poor.
The source emphasizes that high-quality data can be more valuable than an especially advanced model. Increasing the amount of useful training data can also improve performance because the model sees more variations and can learn patterns across a wider range of situations.
For language-processing systems, for example, performance may improve as the number of words used for training increases. Different models should still be compared for the specific problem, but data quantity and quality are fundamental factors.
This leads to an important practical principle:
Data understanding and data collection should usually receive priority before extensive effort is spent on building a complex model.
Think About It
Why could a simple model trained on reliable, representative data outperform a sophisticated model trained on incomplete or poorly understood data?
5. Prepare and Clean the Data
After EDA, the team prepares the data for modeling. This stage addresses problems discovered during exploration.
Missing Values
Missing values must be examined and handled appropriately. One possible approach is imputation, which means replacing missing values using a reasonable method.
The correct approach depends on the meaning of the variable and the problem. Missing data should not simply be ignored without considering whether the absence itself contains useful information or introduces bias.
Invalid Values
The data should be checked for values that do not make sense. For example, an age variable containing negative values indicates a data-quality problem.
Possible responses include:
- Correcting the underlying data
- Removing invalid observations
- Applying minimum or maximum limits
- Imputing more reasonable values
Capping values at a minimum or maximum can prevent extreme or impossible observations from having an inappropriate influence on the model.
Feature Engineering
Feature engineering involves creating or modifying input variables so that they represent useful information for the model.
For example, separate variables such as age and gender might be combined to form a new feature that represents their joint effect. Feature engineering can also involve transforming variables, grouping values, or constructing new measurements from existing data.
In some cases, feature engineering may involve training a separate model or performing another modeling operation before the final model is built.
6. Build a Data Pipeline
All repeatable transformations should be organized into a data pipeline. A pipeline records the sequence of operations used to prepare data and allows the same sequence to be applied to future data.
A pipeline may include:
- Extracting data from sources
- Cleaning invalid values
- Handling missing values
- Combining datasets
- Creating engineered features
- Producing the final modeling dataset
Pipeline frameworks can manage dependencies between tasks. This means one operation can wait until the data it needs has been prepared. Such systems support not only data preparation but also broader modeling workflows.
The main benefit is reproducibility. When new data arrives, the team can pass it through the established process rather than relying on memory or repeating manual steps.
7. Train and Compare Models
At the modeling stage, the team trains one or more machine-learning algorithms. The available methods depend on the type of problem.
Common categories include:
- Classification, which predicts categories
- Regression, which predicts numerical values
- Clustering, which identifies groups or structures in unlabeled data
The dataset can be divided into training and testing portions. The model learns from the training data, while the testing data provides evidence about how well the model performs on data it did not use for learning.
Cross-validation can also be used. It repeatedly divides the available data into training and validation portions so that the model can be evaluated more reliably across different subsets.
Model choice should reflect the structure of the problem. Examples include:
- KNN for problems where spatial or regional relationships are important
- Decision trees for relationships that can be represented through branching decisions
- Neural networks for complex patterns
- Moving-average or recurrent neural-network approaches for time-dependent data
A model should not be selected merely because it is popular or technically advanced. The characteristics of the data and the practical requirements of the problem should guide the choice.
8. Evaluate the Model
Evaluation determines whether the model is useful and whether it behaves appropriately on new data. The evaluation metric should be agreed upon with stakeholders because the metric represents what the project is trying to optimize.
For classification problems, precision and recall are important measures:
- Precision measures how often positive predictions are correct.
- Recall measures how successfully the model finds the actual positive cases.
For other types of models, different measures may be appropriate, including root mean squared error, commonly written as RMSE, or the Gini index. The technical meaning of a metric should be explained to stakeholders so that they understand what improvement in that metric means for the business.
Evaluation should also examine whether the model is overfitting, underfitting, or achieving an appropriate balance.
Bias, Variance, Overfitting, and Underfitting
A model must learn enough structure to make useful predictions without memorizing accidental details in the training data. This creates a balance between bias and variance.
Overfitting and High Variance
Overfitting occurs when a model performs extremely well on its training data but poorly on testing data. The model has learned not only meaningful patterns but also noise or accidental details specific to the training set.
This is associated with high variance. A high-variance model is overly sensitive to the particular training sample. If the model is tested on a different dataset, its performance may decline sharply because the noise it memorized is not present in the same way.
Signs of overfitting include:
- Very high training accuracy
- Much lower testing accuracy
- Decreasing training error
- Increasing testing error as model complexity grows
Highly complex models, including complex gradient-boosting systems or neural networks, can move toward overfitting when their complexity is increased too far.
Underfitting and High Bias
Underfitting occurs when the model is too simple to capture important relationships in the data. It performs poorly on both the training and testing sets.
This is associated with high bias. In this context, bias reflects assumptions imposed by the model that prevent it from representing the actual pattern. For example, a model might assume that the relationship is flat even when the data clearly follows a curved pattern.
A high-bias model relies too heavily on an oversimplified view of the problem and fails to learn enough from the data.
The Bias-Variance Trade-Off
The goal is not to eliminate bias or variance completely. Every model makes assumptions, and every dataset contains some variation that cannot be learned perfectly.
The aim is to find a balance:
- Too much bias produces an overly simple model.
- Too much variance produces an overly sensitive model.
- A balanced model captures meaningful patterns while remaining reliable on new data.
As model complexity increases, training performance often improves. However, testing performance may eventually decline. This happens when additional complexity helps the model fit training noise rather than genuine patterns.
A model-selection process should therefore compare performance on data that was not used for training. Training performance alone is not enough to determine whether the model will work in practice.
Think About It
If a model has nearly perfect training accuracy but poor testing accuracy, what does that suggest about the patterns the model has learned?
9. Deploy the Model
Deployment is the stage in which the model is placed into a real operational environment. The model may be only one component of a much larger system, so deployment should be planned with engineers and other technical specialists.
Important deployment questions include:
- Where will the model run?
- How will new data reach it?
- How will predictions be returned to the rest of the system?
- How will the model be monitored?
- How will it be updated or replaced?
- What environment is appropriate for production use?
The model might run on a cloud-based computing instance or in a local environment, depending on the organization’s requirements. The correct deployment approach depends on the surrounding system rather than on the model alone.
Communication remains important during deployment. The team should explain the model’s findings, intended use, evaluation results, and limitations to stakeholders. A technically successful model still fails as a project if the people responsible for using it do not understand its purpose or results.
10. Monitor and Retrain the Model
Deployment is not necessarily the end of the project. A model may become less accurate as the real world changes. Two important causes are data drift and concept drift.
Data Drift
Data drift occurs when the distribution of the input features changes over time. The model may have been trained on one population or set of conditions, but later receive data with a different composition.
For example, suppose a model was trained using a broad mixture of driver ages. If the system later begins receiving many more observations from older drivers, the input distribution has changed. The model may not perform as well on this new population if it did not learn enough from similar examples during training.
The relationship between the features and target may remain the same, but the types or proportions of inputs have changed.
Concept Drift
Concept drift occurs when the relationship between the features and the target changes. A feature that was previously predictive may no longer predict the target in the same way.
Consider a model that predicts car accidents. Driver age might historically be a useful feature because younger drivers may be more likely to have accidents. If autonomous vehicles become widespread and accidents become largely independent of the driver’s age, then the previous relationship has changed. Driver age is no longer as relevant as it once was.
The distinction is:
- Data drift changes the distribution of the inputs.
- Concept drift changes the relationship between inputs and the target.
Both forms of drift can cause a model’s performance to deteriorate. Monitoring performance and retraining with newer data can help close the resulting gap.
Comprehensive Review
Machine learning allows computer systems to perform tasks without requiring every decision to be explicitly programmed. Instead, algorithms learn patterns from training data and use those patterns to make predictions about new examples.
A spam filter illustrates the basic process. It receives email text, learns from labeled examples, and predicts whether future messages are spam or not spam. This is a binary classification problem and can be built using different combinations of learning approaches.
The major learning distinctions are:
- Supervised learning: training data contains labels.
- Unsupervised learning: training data does not contain labels.
- Offline or batch learning: the model is trained periodically using collected data.
- Online learning: the model is updated frequently as new data arrives.
- Predictive learning: the model predicts a target value.
- Instance-based learning: new observations are compared with existing examples or categories.
A complete machine-learning project follows a broader process:
- Understand the business problem.
- Work with stakeholders to define success.
- Explore and understand the data.
- Form hypotheses about useful features.
- Design an ETL process.
- Clean the data and handle missing or invalid values.
- Engineer useful features.
- Create a repeatable data pipeline.
- Train and compare appropriate models.
- Evaluate them using meaningful metrics.
- Check for overfitting, underfitting, bias, and variance.
- Deploy the selected model with engineering support.
- Monitor the model and retrain it when data or relationships change.
The most important overall lesson is that machine learning is not merely the act of selecting an algorithm. The quality of the problem definition, data, preparation process, evaluation method, deployment plan, and ongoing monitoring all determine whether the final system is useful. A model becomes valuable when it learns meaningful patterns, generalizes to new data, supports a real business objective, and continues to perform as the surrounding world changes.

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