Machine Learning Fundamentals
Fundamentals of Machine Learning
What Is Machine Learning?
Machine learning (ML) is a subset of artificial intelligence that enables computer systems to perform tasks by learning patterns from data rather than relying entirely on explicitly programmed instructions.
In a traditional software system, developers specify rules that determine what the system should do. For example:
If an email contains certain words, classify it as spam.
If a customer’s age is below a certain threshold, apply a particular rule.
If a speech signal has a particular frequency, assign it to a specific sound category.
These rule-based systems can work well for simple and stable problems, but they become difficult to design when:
The number of possible situations is very large.
The rules are complicated or constantly changing.
The relevant patterns are difficult for humans to describe.
The input data is unstructured, such as speech, images, or natural language.
Machine learning replaces many manually written rules with a process in which an algorithm learns relationships from examples.
Core idea: A machine-learning algorithm uses training data to learn patterns that allow it to make predictions or decisions about new, previously unseen data.
Training Data, Labels, and Predictions
A machine-learning system generally receives a set of examples called training data. The algorithm analyzes this data to learn a relationship between inputs and desired outputs.
Labeled Data
In labeled data, each example includes both:
The input features
The correct target or label
For example, an email dataset might contain:
The email’s text as the input
“Spam” or “not spam” as the label
The algorithm learns from these examples and attempts to predict the correct label for new emails.
Unlabeled Data
In unlabeled data, the examples contain inputs but no known target labels. The algorithm must identify patterns, groups, or structures within the data without being told the correct answers.
Generalization
After training, the model should be able to make useful predictions on new data that was not included in the training set. This ability is called generalization.
A model that merely memorizes its training examples may perform well on those examples but fail on new data. Effective machine learning requires learning patterns that apply beyond the original training set.
Example: Spam Email Detection
Spam detection is a basic example of a machine-learning classification problem.
Inputs and Outputs
Input: The email message, represented as text or as a processed representation such as tokenized text
Output: A predicted category, such as “spam” or “not spam”
Because there are two possible categories, this is a binary classification problem.
Binary Classification
Binary classification assigns an input to one of two classes.
Examples include:
Spam versus not spam
Fraudulent versus legitimate
Sick versus healthy
Approved versus rejected
A spam detector learns from previously labeled emails. It identifies patterns associated with spam and applies those patterns to new messages.
Modern spam detection can use advanced methods such as deep learning, which can learn complex patterns in language and message structure.
Traditional Rule-Based Systems
How Rule-Based Systems Work
A traditional approach begins by studying a problem and manually writing a set of rules. The system is then tested to determine whether the rules produce acceptable results.
A typical process is:
Study the problem.
Write explicit rules.
Test the rule-based system.
Examine its performance.
Revise poorly performing rules.
Deploy the system if its results are satisfactory.
This approach can be effective when the problem is simple, predictable, and governed by stable rules.
Limitations of Hard-Coded Rules
1. Complexity
A realistic system may require thousands of rules and many special cases. As the number of rules increases, the codebase becomes difficult to understand and modify.
2. Lack of Flexibility
Hard-coded systems do not automatically adapt when the environment changes. A rule that works today may become ineffective later.
For example, spammers may change:
The vocabulary used in messages
The structure of emails
The use of images
The formatting of paragraphs
The spelling of common spam-related words
A spam detector based on fixed words and rules may become obsolete when these patterns change.
3. High Maintenance Cost
Large rule-based systems are expensive and time-consuming to maintain. Developers must manually locate outdated rules, add new rules, and ensure that changes do not create conflicts elsewhere in the system.
4. Poor Coverage of New Cases
A fixed set of rules may not account for every possible input. New types of emails, images, speech patterns, or language structures can fall outside the cases anticipated by the original developers.
5. False Positives
A rule-based system may incorrectly classify legitimate inputs as negative or problematic.
In spam detection, a false positive occurs when a legitimate email is incorrectly labeled as spam. Avoiding false positives is important because users may miss important messages.
6. Difficulty Solving Complex Problems
Some problems are extremely difficult to express through explicit rules. Speech recognition is one example. Writing rules that convert every possible speech frequency, accent, pronunciation, background sound, and speaking style into accurate words would be impractical.
Machine learning is useful in such situations because it can learn complex relationships directly from examples.
Machine-Learning-Based Systems
General Process
A machine-learning approach follows a process similar to the rule-based approach but replaces manually specified rules with a learned model.
The process generally involves:
Studying the problem.
Collecting a training dataset.
Training a machine-learning algorithm.
Testing the algorithm’s predictions.
Measuring its accuracy or other performance metrics.
Investigating poor performance.
Improving the data, algorithm, or training process.
Deploying the model if its performance is acceptable.
If the model performs poorly, possible causes include:
Problems with the training data
Poor-quality or missing features
An unsuitable algorithm
Incorrect preprocessing
Overfitting
Underfitting
A mismatch between the evaluation metric and the business goal
Benefits of Machine Learning
Shorter Development Time
Machine-learning libraries make it possible to create sophisticated models with relatively little code.
For example:
Deep-learning frameworks such as TensorFlow and Keras can define neural-network architectures in a small number of lines.
Libraries such as scikit-learn provide ready-to-use implementations of linear models, decision trees, and many other algorithms.
The difficult work is not eliminated, but the implementation of standard algorithms is greatly simplified.
Easier Maintenance
Instead of maintaining thousands of individual rules, teams can improve a model by:
Updating the training data
Changing the features
Adjusting model parameters
Retraining the algorithm
Replacing the deployed model with an improved version
Improved Accuracy
Machine learning and deep learning have achieved significant performance improvements in areas such as:
Natural-language processing
Speech recognition
Image recognition
Recommendation systems
Fraud detection
Classification and prediction
Better Adaptation to New Instances
A well-designed machine-learning model can generalize to new examples. It is not limited to the exact cases encountered during development.
For example, a spam filter can learn broader patterns in language rather than depending only on a fixed list of spam words.
Offline Learning and Batch Learning
Definition
Offline learning, also called batch learning, is a training approach in which a model is trained using a collected dataset before being deployed.
The model is typically trained in a separate environment and then placed into production.
A common workflow is:
Collect a training dataset.
Train the model offline.
Evaluate its performance.
Deploy the model.
Collect additional data while the model is operating.
Periodically retrain a new model using the expanded dataset.
Replace the production model with the retrained version.
The deployed model is not continuously updated after every new example. Instead, retraining occurs periodically, often after enough new data has accumulated.
Why Batch Models Need Retraining
A model may become less accurate over time because the data or the underlying relationships in the problem have changed.
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 relationship between the features and the target may remain valid, but the types of inputs being observed become different from those used for training.
Example
Suppose an insurance model was trained mostly on data from younger drivers. Later, the company begins receiving many more applications from older drivers.
The model may perform poorly on this new population because it has not learned enough from similar examples, even if driver age remains a relevant predictor of accidents.
Effects of Data Drift
Data drift can cause:
Declining prediction accuracy
Poor performance on newly common types of inputs
Increased errors in certain population segments
A growing gap between historical model performance and current performance
To respond, a team can collect new data, analyze where performance has declined, and retrain the model using a more representative dataset.
Concept Drift
Concept drift occurs when the relationship between the input features and the target changes over time.
In this case, the model may still receive familiar-looking inputs, but the meaning or predictive value of those inputs has changed.
Example
Assume an insurance model predicts car accidents and historically finds that younger drivers are more likely to be involved in accidents. Driver age is therefore a useful feature.
If autonomous vehicles become widespread, accidents may become less dependent on the driver’s age. The relationship between age and accident risk changes, so driver age is no longer as predictive as it was before.
Difference Between Data Drift and Concept Drift
Data drift: The distribution of the inputs changes.
Concept drift: The relationship between the inputs and the target changes.
A model can experience either type of drift or both. Monitoring is necessary to determine why performance is deteriorating.
Online Learning
Definition
Online learning is a training approach in which a model is updated continuously or very frequently as new data becomes available.
Unlike batch learning, the model does not wait months or years for a large retraining cycle. It learns from new instances as they arrive.
A possible online-learning process is:
Deploy an initial model.
Receive new observations.
Incorporate the observations into the training process.
Update the model regularly, such as nightly or even more frequently.
Continue monitoring the updated model.
Online learning can be useful when the underlying data changes quickly and predictions must adapt rapidly.
Risks of Online Learning
The main risk is that poor-quality or harmful data can continually damage the model.
Potential problems include:
Incorrect labels
Biased or unrepresentative data
Malicious inputs
Spam or automated data
Sudden changes in data quality
Feedback loops that reinforce bad predictions
If the model learns directly from every new example, a short-term problem in the data can gradually cause long-term degradation.
Safeguards
A production system can include safeguards such as a fail switch or performance threshold.
For example:
Compare the newly updated model with the current production model.
Test both models on a fixed validation dataset.
Deploy the new model only if it performs at least as well as the existing model.
Reject the update if performance falls below an acceptable threshold.
This prevents automatic updates from making the system worse.
Example: A Model Trained on Social-Media Data
A model that generates text from social-media data may begin producing offensive, nonsensical, or extreme output if it continually learns from poor-quality posts or automated accounts.
This illustrates why online learning requires:
Data-quality monitoring
Validation checks
Deployment safeguards
Continuous model evaluation
Major Categories of Machine-Learning Systems
Machine-learning systems can be categorized along several independent dimensions. A single model may belong to multiple categories at once.
Supervised Learning
Supervised learning uses a labeled training dataset. The algorithm learns to predict known target values from input features.
Examples include:
Spam classification
Predicting insurance claims
Diagnosing disease
Estimating house prices
Unsupervised Learning
Unsupervised learning uses data without target labels. The algorithm attempts to discover patterns or structures on its own.
Examples include:
Grouping similar customers
Identifying natural clusters
Detecting unusual observations
Finding hidden structures in large datasets
Offline or Batch Learning
Offline learning trains the model periodically using a collected batch of data. A new model is then deployed to replace the old one.
Online Learning
Online learning updates the model continuously or frequently as new observations arrive.
Predictive Learning
A predictive model produces a prediction about a target variable.
Examples include:
Regression models that predict numerical values
Classification models that predict categories
Time-series models that forecast future values
Regression
Regression predicts a numerical quantity, such as:
Annual insurance cost
House price
Temperature
Number of expected accidents
Instance-Based Learning
Instance-based learning classifies new observations by comparing them with known examples or categories.
K-Nearest Neighbors
K-nearest neighbors (KNN) is an instance-based method. A new data point is assigned a prediction based on nearby points in the feature space.
For example, if geographic observations form distinct regions, a new point may be classified according to the region containing the most similar neighboring points.
Classification more generally can also be understood as assigning new data points to existing categories.
Combining Categories
The categories are not mutually exclusive. A single application can combine several characteristics.
For example, a spam filter could be:
Supervised, because it is trained on emails labeled spam or not spam
Instance-based, if it compares new messages with known examples
Online, if it updates itself as new labeled messages arrive
The best combination depends on the specific problem, data availability, and operational requirements.
Stages of a Machine-Learning Project
A successful machine-learning project involves much more than selecting and training an algorithm. It begins with understanding the business problem and continues through deployment and communication.
1. Understand the Business Problem
The first stage is to define the problem clearly with stakeholders.
Important activities include:
Identifying the actual business objective
Understanding who will use the model
Defining what decision the model should support
Asking questions about the problem’s scope
Understanding operational constraints
Determining what a successful outcome means
Creating a plan for solving the problem
Importance of Stakeholder Knowledge
Stakeholders often understand the business context better than the machine-learning team. They may know:
Which variables are meaningful
How current decisions are made
Which outcomes are costly
Which errors are acceptable or unacceptable
What practical constraints affect deployment
How predictions will be used
For example, actuaries can provide important domain knowledge when developing insurance models because they understand insurance risks, policies, and business processes.
Business Versus Technical Objectives
A data scientist may focus on technical measures such as:
RMSE
R-squared
Precision
Recall
Gini index
However, technical performance alone does not guarantee business value. The model must help solve the original business problem.
2. Perform Exploratory Data Analysis
Exploratory data analysis (EDA) involves examining the data to understand its quality, structure, relationships, and usefulness.
EDA can include:
Examining distributions
Identifying missing values
Detecting unusual or impossible values
Plotting targets against features
Measuring correlations
Comparing groups
Looking for trends and patterns
Checking whether the data supports the proposed business problem
EDA Can Sometimes Be the Final Product
A machine-learning model is not always necessary. EDA may produce dashboards or insights that are already valuable to the business.
For example, a set of visualizations may reveal:
Which customer groups have the highest risk
Where claims are concentrated
How outcomes vary over time
Which factors are associated with a target
If these insights answer the business question, building a complex model may add unnecessary complexity.
Communicating Early Findings
Initial findings should be shared with stakeholders. This helps determine:
Whether the analysis is addressing the correct problem
Whether the patterns make sense from a business perspective
Whether the results match known experience
Whether additional data or questions are needed
Stakeholder feedback can prevent a team from developing a technically sophisticated solution to the wrong problem.
3. Form Hypotheses
After examining the data, the team can develop initial hypotheses about which features may be predictive.
Useful activities include:
Plotting the target against individual features
Looking for possible trends or nonlinear relationships
Examining correlations between features and the target
Examining correlations among features
Identifying redundant or highly related variables
Connecting statistical patterns to business meaning
A feature should not be included in a model simply because it is available. The team should understand:
What the feature represents
How it is measured
Why it might affect the target
Whether it is available at prediction time
Whether the relationship is meaningful or accidental
What business implications follow from using it
Correlation can provide useful initial insight, but correlation alone does not prove causation or guarantee that a feature will perform well in a deployed model.
4. Design the ETL Architecture
ETL stands for:
Extract: Obtain data from raw sources.
Transform: Clean, standardize, combine, and restructure the data.
Load: Place the prepared data into a destination where it can be analyzed or used for modeling.
A well-designed ETL architecture prepares raw data for reliable analysis and model training.
Why an ETL Pipeline Matters
Without a repeatable pipeline, a team may need to manually repeat every data-preparation step whenever:
A new model is trained
New data becomes available
The model is retrained
A production prediction is required
The analysis must be reproduced
A pipeline makes the process more consistent, efficient, and reproducible.
5. Prioritize Data Understanding and Collection
Data quality and quantity are often more important than model complexity.
A powerful model cannot compensate for poor-quality data.
A simple model trained on accurate, representative, and sufficiently large data may outperform a sophisticated model trained on incomplete or biased data.
Importance of More Data
For many machine-learning applications, especially natural-language processing, adding more training examples can improve performance substantially.
More data can help a model:
Learn from more variations
Represent more population segments
Recognize rare patterns
Generalize to new cases
Learn patterns at different levels of abstraction
Different algorithms should still be compared for the particular application, but collecting and understanding good data should generally come before optimizing model complexity.
6. Prepare and Clean the Data
After EDA and data collection, the data must be prepared for modeling.
Missing Values
The team should identify missing values and determine how to handle them. Possible approaches include:
Imputing values
Creating an indicator for missingness
Removing records when appropriate
Removing features with excessive missingness
Using algorithms that can handle missing values
The correct approach depends on why values are missing and how missingness relates to the business problem.
Invalid Values
Data should be checked for values that are impossible or inconsistent with the domain.
For example, an age variable should not contain negative values. Invalid records may need to be:
Corrected
Removed
Replaced with a valid estimate
Capped at a reasonable minimum or maximum
Capping and Imputation
Capping limits extreme values to a chosen minimum or maximum. It can reduce the effect of outliers when extreme values are likely to be errors or are disproportionately influential.
Imputation replaces missing or unusable values with estimated values according to a defined method.
All such decisions should be documented and applied consistently.
Feature Engineering
Feature engineering creates or transforms input variables so that they provide more useful information to the model.
For example, age and gender might be combined into a new feature if their interaction is relevant to the business problem.
Feature engineering can involve:
Combining existing variables
Creating ratios or differences
Extracting information from dates or text
Encoding categories
Aggregating repeated observations
Transforming skewed variables
In some cases, feature engineering may involve building a separate model or process that generates useful features.
7. Build a Repeatable Data Pipeline
Every transformation used during training should be organized into a repeatable process.
A data pipeline can include:
Data extraction
Cleaning
Missing-value handling
Feature transformations
Feature engineering
Data splitting
Model training
Evaluation
The same transformations should be applied consistently to future data. This reduces errors and prevents differences between training and production processing.
Dependency-based pipeline frameworks can help organize complex workflows by ensuring that each stage runs after the data or process it depends on has been completed.
Modeling
Training and Testing
At the modeling stage, the team trains one or more machine-learning algorithms.
A common approach is to divide the available data into:
Training data: Used to learn model parameters
Testing data: Used to estimate performance on unseen examples
The test set should not be used to tune the model repeatedly, because doing so can make the reported performance overly optimistic.
Cross-Validation
Cross-validation repeatedly divides the data into training and validation portions. This provides a more reliable estimate of how the model may perform on unseen data and helps compare different modeling approaches.
Types of Models
The appropriate algorithm depends on the structure of the problem.
Classification
Classification models predict categories.
Examples include:
Spam versus not spam
Fraud versus legitimate
High risk versus low risk
Regression
Regression models predict numerical values.
Examples include:
Expected claim cost
House price
Number of accidents
Customer demand
Clustering
Clustering groups similar observations without requiring labeled target values.
Examples include:
Customer segmentation
Grouping documents by topic
Identifying geographic regions with similar behavior
Geographic or Spatial Problems
KNN may work well for some geographic problems because it uses nearby observations and can reflect spatial similarity or smoothing.
A region-based approach may be more appropriate than a simple linear relationship when nearby locations tend to behave similarly.
Graph-Structured Problems
Decision trees and neural networks may be suitable for problems involving graph-like or hierarchical relationships, depending on how the data is represented.
Time-Series Problems
Time-series data contains observations ordered over time. Models for such data should account for temporal patterns, such as:
Trends
Seasonality
Autocorrelation
Repeated patterns
Changes over time
Examples include:
Moving-average models
Recurrent neural networks
Model selection should be guided by the data structure rather than by choosing the most complex or fashionable algorithm.
Model Evaluation
Align Evaluation With Business Goals
Model performance should be communicated to stakeholders in terms they can understand.
The team should explain:
What the model is optimizing
Why the chosen metric is appropriate
How the metric relates to business value
What types of errors the model makes
What trade-offs exist between different errors
For example, if a model optimizes the Gini index, stakeholders should understand what the metric measures and why it matters for the application.
Common Evaluation Metrics
Classification Metrics
Precision: The proportion of predicted positive cases that are actually positive.
Recall: The proportion of actual positive cases that the model successfully identifies.
Precision is especially important when false positives are costly. Recall is especially important when missing a positive case is costly.
For example:
A spam filter may need to control false positives so that important emails are not discarded.
A medical screening system may prioritize recall so that as few actual cases as possible are missed.
Regression Metrics
RMSE: Root mean squared error, which measures the typical size of prediction errors while giving greater weight to large errors.
R-squared: A measure of how much variation in the target is explained by the model.
Ranking or Risk Metrics
Gini index: A measure often used to assess the discriminatory or ranking ability of predictive models, particularly in areas such as insurance and credit risk.
The metric must match the purpose of the model. A high score on an inappropriate metric does not necessarily indicate a useful model.
Overfitting, Underfitting, Bias, and Variance
Overfitting
Overfitting occurs when a model performs extremely well on training data but poorly on unseen testing data.
A typical pattern is:
Very high training accuracy
Much lower testing accuracy
Low training error
Higher testing error
An overfit model has learned not only the meaningful patterns in the training data but also random noise and accidental details.
High Variance
Overfitting is associated with high variance. A high-variance model is highly sensitive to the particular training sample used.
If the training data changes slightly, the resulting model may change substantially. Consequently, the model may fail when applied to another dataset with different noise or examples.
Complex models, including highly tuned gradient-boosting systems and neural networks, can become overfit if their complexity is not controlled.
Underfitting
Underfitting occurs when a model is too simple to capture the meaningful relationships in the data.
A typical underfit model performs poorly on:
The training data
The testing data
The model has not learned enough structure from the problem.
Possible causes include:
An overly simple algorithm
Too few features
Excessive regularization
Insufficient training
Incorrect assumptions about the relationship between variables
Bias
Bias refers to error caused by overly restrictive assumptions about the relationship between inputs and outputs.
A high-bias model imposes too much structure on the problem and ignores important information in the data. For example, a model might assume that a relationship is flat or linear even when the data clearly shows a curve.
Some bias can be useful when it reflects valid domain knowledge or helps prevent overfitting. However, excessive bias leads to underfitting.
Bias–Variance Trade-Off
The goal is to find a balance between bias and variance.
Too much bias: The model is too simple and misses important patterns.
Too much variance: The model is too complex and learns noise.
Balanced model: The model captures meaningful patterns while generalizing to new data.
As model complexity increases:
Training accuracy often increases.
Training error often decreases.
Testing accuracy may eventually decrease.
Testing error may eventually increase.
This is the typical transition from a useful model to an overfit model.
A parameter search can reveal this behavior by comparing models with different levels of complexity. The best model is not necessarily the one with the highest training accuracy; it is the one that performs reliably on unseen data and supports the business objective.
Deployment
Moving a Model Into Production
Deployment is the stage in which the trained model becomes part of a real operational system.
The data-science team should work closely with software and infrastructure engineers to determine the best deployment approach.
A model may be:
One component of a larger application
Used in real-time predictions
Used in a scheduled batch process
Hosted in the cloud
Run on a local server
Integrated into an existing data pipeline
Potential deployment environments include cloud computing instances or local production systems.
Collaboration With Engineers
Data scientists should not treat deployment as an isolated task. Engineers can help determine:
How the model will receive input data
How predictions will be returned
How the model will be stored and versioned
How performance will be monitored
How the system will scale
How failures will be handled
How retraining and updates will occur
The best deployment environment depends on the model, the surrounding system, latency requirements, security needs, and available infrastructure.
Communicating Findings
The final stage also requires communicating results to stakeholders.
A complete delivery should explain:
What problem the model addresses
What data was used
How the model was built
Which evaluation metric was selected
How well the model performs
What limitations remain
How the model will be used
What monitoring and retraining are required
A machine-learning project is successful only when the model provides reliable value in its intended business context.
Key Takeaways
Machine learning learns patterns from data instead of depending entirely on manually written rules.
Rule-based systems are often difficult to maintain, inflexible, and unable to handle novel or complex cases.
Machine-learning systems use training data to make predictions about new instances.
Spam detection is an example of supervised binary classification.
Supervised learning uses labeled data, while unsupervised learning uses unlabeled data.
Batch learning retrains models periodically using accumulated data.
Online learning updates models frequently as new data arrives but requires strong safeguards.
Data drift changes the distribution of input features.
Concept drift changes the relationship between features and targets.
Exploratory data analysis may itself provide enough business value without requiring a complex model.
Data quality, data understanding, and data collection are often more important than model sophistication.
Data preparation includes handling missing values, correcting invalid values, capping extremes, and engineering useful features.
Model selection should reflect the structure of the problem, such as classification, regression, clustering, spatial prediction, graph-based analysis, or time-series forecasting.
Evaluation metrics must be explained to stakeholders and aligned with the business goal.
Overfitting reflects high variance, while underfitting is commonly associated with high bias.
A strong machine-learning project combines technical modeling with business understanding, data engineering, evaluation, deployment, and communication.

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