1. Home
  2. Explore
  3. Computer Science
  4. Machine Learning Course Introduction

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Machine Learning Course Introduction

Machine Learning: Comprehensive Study Notes

1. What Is Machine Learning?

Machine learning (ML) is a subfield of artificial intelligence that enables computers to learn patterns from data and use those patterns to make predictions or decisions.

Traditional computer programs require explicit instructions for every task. In machine learning, a programmer provides data and an algorithm, and the system learns a model that improves when exposed to additional data.

Machine learning enables computers to make data-driven decisions without being explicitly programmed for every individual task.

Examples of machine learning

  • Self-driving vehicles

  • Voice assistants such as Siri and Google Assistant

  • Facial and biometric recognition

  • Fraud detection in banking

  • Medical diagnosis

  • Product recommendations

  • Speech recognition

  • Spam filtering

  • Weather and sales prediction

General machine-learning workflow

  1. Collect relevant data.

  2. Clean and prepare the data.

  3. Split the data into training and testing portions.

  4. Train a machine-learning algorithm.

  5. Use the trained algorithm to generate predictions.

  6. Evaluate the predictions.

  7. Retrain or improve the model if its performance is inadequate.

  8. Deploy the model when its performance is acceptable.

  9. Monitor and retrain the model as new data becomes available.

A model may be trained using labeled data or unlabeled data, depending on the learning method.


2. Artificial Intelligence, Machine Learning, and Deep Learning

These three terms are related but not interchangeable.

Artificial intelligence

Artificial intelligence (AI) is the broadest concept. It refers to systems designed to perform tasks that normally require human intelligence, such as:

  • Reasoning

  • Planning

  • Perception

  • Language understanding

  • Decision-making

  • Problem-solving

AI may use rules, search algorithms, expert systems, machine learning, or deep learning.

Machine learning

Machine learning is a subset of AI. It focuses on allowing systems to learn patterns from data rather than relying only on manually written rules.

Machine learning can:

  • Extract patterns from data

  • Adapt when the data changes

  • Make predictions on previously unseen examples

  • Improve performance through training

Deep learning

Deep learning is a subset of machine learning based on multilayer artificial neural networks. It is especially useful for complex data such as:

  • Images

  • Audio

  • Video

  • Natural language

  • Large-scale sensor data

Deep-learning systems automatically learn increasingly abstract features from raw data.

Relationship

Artificial Intelligence⊃Machine Learning⊃Deep Learning\text{Artificial Intelligence} \supset \text{Machine Learning} \supset \text{Deep Learning}Artificial Intelligence⊃Machine Learning⊃Deep Learning

Main differences

Data requirements

  • Machine learning: Often works well with small or medium-sized datasets.

  • Deep learning: Usually requires very large datasets to perform effectively.

Feature engineering

  • Machine learning: Experts often identify and manually construct useful features.

  • Deep learning: Neural networks automatically learn features from raw data.

Hardware

  • Machine learning: Can often run on standard computers.

  • Deep learning: Commonly requires powerful GPUs because training involves extensive matrix operations.

Problem-solving approach

  • Machine learning: Complex problems are often divided into smaller subproblems.

  • Deep learning: A single end-to-end model may learn the complete mapping from input to output.

Training time

  • Machine learning: Usually trains relatively quickly.

  • Deep learning: May require hours, days, or weeks of training.

Interpretability

  • Machine learning: Models such as decision trees and linear regression are relatively easy to interpret.

  • Deep learning: Neural networks are often difficult to explain because their internal representations are complex.

Testing time

Deep-learning models may take longer to train but can make predictions quickly once trained. Some traditional algorithms, such as K-nearest neighbors, may require increasing amounts of computation during prediction.


3. The Three Major Types of Machine Learning

Machine learning is commonly divided into:

  1. Supervised learning

  2. Unsupervised learning

  3. Reinforcement learning


Supervised Learning

4. Definition of Supervised Learning

Supervised learning uses labeled data. Each training example contains:

  • Input variables, represented by XXX

  • An expected output, represented by YYY

The algorithm learns a mapping function:

Y=f(X)Y = f(X)Y=f(X)

The goal is to approximate fff well enough that the model can predict YYY for a new input XXX.

In supervised learning, a known answer guides the algorithm during training.

Training example structure

A training instance may contain:

  • Image pixels

  • Database values

  • Audio-frequency measurements

  • Text features

  • Sensor readings

The expected output may be:

  • A category, such as “duck” or “not duck”

  • A number, such as a predicted house price

Why it is called supervised learning

The process resembles a teacher supervising a student:

  1. The model makes a prediction.

  2. The prediction is compared with the known answer.

  3. The model is corrected.

  4. The process repeats until performance is acceptable.

Examples

  • Recognizing apples in images

  • Classifying ducks and non-ducks

  • Recognizing speech commands

  • Predicting creditworthiness

  • Predicting hospital readmission

  • Identifying biometric users

  • Predicting weather conditions


5. Supervised Learning Tasks

Classification

Classification predicts a discrete category or class.

Examples:

  • Male or female

  • Spam or not spam

  • Disease or no disease

  • Apple, orange, or banana

  • Survived or did not survive

The output may be binary:

Y∈{0,1}Y \in \{0,1\}Y∈{0,1}

or multiclass, where more than two categories are possible.

Regression

Regression predicts a continuous numerical value.

Examples:

  • House price

  • Temperature

  • Weight

  • Sales revenue

  • Number of future claims

A simple linear regression model has the form:

y=mx+cy = mx + cy=mx+c

where:

  • yyy is the predicted output

  • xxx is the input

  • mmm is the slope

  • ccc is the intercept


6. Common Supervised-Learning Algorithms

Linear regression

Used to predict continuous values by fitting a line or hyperplane to data.

Logistic regression

Used primarily for classification. It produces a probability between 000 and 111, usually using a sigmoid function:

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

A threshold is then used to convert the probability into a class:

  • Probability ≥0.5\geq 0.5≥0.5: class 111

  • Probability <0.5< 0.5<0.5: class 000

Decision trees

Decision trees classify or predict data through a series of questions.

Random forests

A random forest combines many decision trees and aggregates their predictions. This often improves accuracy and stability.

Support vector machines

Support vector machines identify an optimal boundary between classes by maximizing the margin between the boundary and the closest training points.

Naive Bayes

Naive Bayes is a probabilistic classifier based on Bayes’ theorem. It assumes that features are conditionally independent given the class.

K-nearest neighbors

K-nearest neighbors predicts a new observation based on the classes of its closest training examples.


7. Applications of Supervised Learning

Speech automation

Voice assistants are trained using examples of spoken commands and their correct interpretations.

Weather prediction

Historical relationships between conditions such as temperature, humidity, and cloud cover can be used to predict future weather variables.

Biometrics

A system can be trained using fingerprints, iris patterns, or other biometric examples and later verify a person’s identity.

Banking

A credit-risk model can learn from delinquent and non-delinquent customers to predict whether a new applicant is likely to repay.

Healthcare

A regression or classification model can use treatment history and patient characteristics to predict readmission or disease risk.

Retail

Supervised models can identify frequent itemsets and association rules from transaction histories.


Unsupervised Learning

8. Definition of Unsupervised Learning

Unsupervised learning uses input data without known output labels.

The data consists only of XXX:

X→discover structureX \rightarrow \text{discover structure}X→discover structure

The goal is to find hidden patterns, natural groupings, or probability distributions within the data.

In unsupervised learning, the algorithm discovers structure without a teacher or predefined correct answer.

Clustering

The most common unsupervised task is clustering, in which similar observations are grouped together.

For example, an algorithm may group fruits according to:

  • Color

  • Shape

  • Size

  • Texture

  • Weight

The algorithm can identify that some observations are similar, but it may not know that a particular group represents apples or oranges.

Examples

  • Segmenting customers by behavior

  • Grouping images by visual similarity

  • Categorizing MRI scans

  • Recommending products based on purchasing patterns

  • Grouping people according to age, gender, or behavior

  • Organizing football players based on jerseys or playing style


9. Common Unsupervised-Learning Algorithms

K-means clustering

K-means assigns observations to one of KKK clusters according to their distance from cluster centroids.

Hierarchical clustering

Hierarchical clustering builds a tree-like structure of clusters.

Apriori algorithm

Apriori discovers frequent itemsets and association rules in transactional data.

Fuzzy C-means

Fuzzy C-means allows an observation to belong to multiple clusters with different membership values.


10. Applications of Unsupervised Learning

Banking

Customers can be segmented according to behavioral characteristics and transaction patterns.

Healthcare

MRI scans can be grouped as normal or abnormal based on learned image features.

Retail

Collaborative-filtering models can recommend products based on similar customers’ purchasing histories.


Reinforcement Learning

11. Definition of Reinforcement Learning

Reinforcement learning (RL) trains an agent to choose actions in an environment in order to maximize cumulative reward.

The agent is not given the correct answer for each situation. Instead, it learns through trial and error.

Reinforcement learning is learning through interaction, rewards, and penalties.

Main components

  • Agent: The learner or decision-maker

  • Environment: The world in which the agent operates

  • State: The current condition of the environment

  • Action: A possible decision available to the agent

  • Reward: Feedback received after an action

  • Policy: The strategy used to select actions

  • Value: The expected long-term reward of a state

  • Action value: The expected long-term reward of taking a particular action in a particular state

Reinforcement-learning cycle

  1. The environment provides the current state.

  2. The agent selects an action.

  3. The environment changes.

  4. The agent receives a reward or penalty.

  5. The agent updates its knowledge.

  6. The cycle continues until a terminal state is reached.

Exploration and exploitation

  • Exploration: Trying unfamiliar actions to learn more about the environment.

  • Exploitation: Choosing the best-known action based on current knowledge.

A successful agent balances exploration and exploitation.

Reward maximization

The objective is to maximize cumulative reward, not necessarily the immediate reward. Future rewards may be discounted using a factor γ\gammaγ:

0≤γ≤10 \leq \gamma \leq 10≤γ≤1
  • A small γ\gammaγ emphasizes immediate rewards.

  • A large γ\gammaγ gives more importance to future rewards.


12. Examples of Reinforcement Learning

Animal training

In classical conditioning, a dog may eventually associate a bell with food. The repeated association reinforces a particular response.

Games

An agent playing a game learns by receiving rewards for successful actions and penalties for losing or making poor decisions.

Banking

A call-center system can learn which offer is most effective based on whether customers accept or reject previous offers.

Healthcare

A system can learn treatment strategies for different emergency cases through a Markov decision process.

Retail

Dynamic-pricing systems can adjust prices according to customers’ responses to previous offers.

Robotics

Robots can learn routes through warehouses or factories by receiving rewards for reaching desired locations efficiently.


13. Markov Decision Processes and Q-learning

A Markov decision process (MDP) provides a mathematical framework for decision-making where outcomes are partly random and partly controlled by the agent.

An MDP contains:

  • States

  • Actions

  • Transition probabilities

  • Rewards

  • A policy

Bellman equation

The Bellman equation expresses the value of a state in terms of immediate reward and future value:

V(s)=max⁡a[R(s,a)+γV(s′)]V(s) = \max_a \left[R(s,a) + \gamma V(s')\right]V(s)=maxa​[R(s,a)+γV(s′)]

For stochastic environments, transition probabilities are included:

V(s)=max⁡a[R(s,a)+γ∑s′P(s′∣s,a)V(s′)]V(s) = \max_a \left[ R(s,a) + \gamma \sum_{s'} P(s' \mid s,a)V(s') \right]V(s)=maxa​[R(s,a)+γ∑s′​P(s′∣s,a)V(s′)]

Q-learning

Q-learning estimates the value of taking an action aaa in state sss:

Q(s,a)=R(s,a)+γmax⁡a′Q(s′,a′)Q(s,a) = R(s,a) + \gamma \max_{a'} Q(s',a')Q(s,a)=R(s,a)+γmaxa′​Q(s′,a′)

A learning-rate parameter α\alphaα controls how quickly new information replaces old knowledge:

Qnew(s,a)=Qold(s,a)+α[R(s,a)+γmax⁡a′Q(s′,a′)−Qold(s,a)]Q_{\text{new}}(s,a) = Q_{\text{old}}(s,a) + \alpha \left[ R(s,a) + \gamma \max_{a'}Q(s',a') - Q_{\text{old}}(s,a) \right]Qnew​(s,a)=Qold​(s,a)+α[R(s,a)+γmaxa′​Q(s′,a′)−Qold​(s,a)]

Q-learning is useful for route planning, robotics, games, and automated decision systems.


Statistics and Probability for Machine Learning

14. Data

Data consists of facts, measurements, observations, or statistics collected for reference or analysis.

Data can be:

  • Collected

  • Measured

  • Analyzed

  • Visualized

  • Modeled statistically

Qualitative data

Qualitative data describes characteristics that are not naturally numerical.

Nominal data

Nominal data has categories with no inherent order.

Examples:

  • Gender

  • Race

  • Eye color

  • Country

Ordinal data

Ordinal data has categories with a meaningful order.

Examples:

  • Poor, average, good

  • Small, medium, large

  • Satisfaction ratings

Quantitative data

Quantitative data is numerical and can be measured objectively.

Discrete data

Discrete data contains a finite or countable set of values.

Examples:

  • Number of students

  • Number of cars

  • Number of purchases

Continuous data

Continuous data can take infinitely many values within a range.

Examples:

  • Height

  • Weight

  • Temperature

  • Time

Variables

  • Independent variable: A variable used as an input or predictor.

  • Dependent variable: A variable whose value depends on one or more predictors.

  • Categorical variable: A variable containing category labels.

  • Continuous variable: A variable containing numerical values over a continuous range.


15. Statistics

Statistics is the branch of applied mathematics concerned with collecting, analyzing, interpreting, and presenting data.

Statistics supports machine learning by helping to:

  • Understand datasets

  • Estimate unknown quantities

  • Measure variation

  • Test hypotheses

  • Evaluate models

  • Quantify uncertainty


16. Population and Sample

Population

A population is the complete set of individuals, objects, or events being studied.

Sample

A sample is a subset of the population selected for analysis.

A good sample should represent the important characteristics of the population.

Studying a sample is often necessary because examining an entire population may be impractical, expensive, or time-consuming.


17. Sampling Techniques

Probability sampling

Every member of the population has a known probability of selection.

Random sampling

Every population member has an equal chance of being selected.

Systematic sampling

Every nnnth record is selected after choosing a starting point.

Stratified sampling

The population is divided into subgroups called strata based on a shared characteristic. Random samples are then taken from each stratum.

Non-probability sampling

The source also identified:

  • Quota sampling

  • Judgment sampling

  • Convenience sampling

These methods do not give every member a known or equal probability of selection.


Descriptive and Inferential Statistics

18. Descriptive Statistics

Descriptive statistics summarize and describe the main characteristics of a dataset.

They include:

  • Tables

  • Graphs

  • Measures of center

  • Measures of spread

Inferential statistics

Inferential statistics uses a sample to make estimates, predictions, or conclusions about a population.

Examples include:

  • Confidence intervals

  • Hypothesis tests

  • Point estimates

  • Margin of error


19. Measures of Central Tendency

Mean

The mean is the arithmetic average:

xˉ=∑i=1nxin\bar{x} = \frac{\sum_{i=1}^{n}x_i}{n}xˉ=n∑i=1n​xi​​

The mean can be strongly affected by outliers.

Median

The median is the middle value after sorting the data.

  • With an odd number of observations, it is the central observation.

  • With an even number of observations, it is the average of the two central observations.

The median is less affected by extreme values than the mean.

Mode

The mode is the most frequently occurring value.

A dataset may have:

  • One mode

  • Multiple modes

  • No mode


20. Measures of Spread

Range

The range is:

Range=Maximum−Minimum\text{Range} = \text{Maximum} - \text{Minimum}Range=Maximum−Minimum

Quartiles

Quartiles divide ordered data into four sections.

  • Q1Q_1Q1​: First quartile, approximately the 25th percentile

  • Q2Q_2Q2​: Second quartile, the median

  • Q3Q_3Q3​: Third quartile, approximately the 75th percentile

Interquartile range

The interquartile range measures the spread of the middle half of the data:

IQR=Q3−Q1IQR = Q_3 - Q_1IQR=Q3​−Q1​

Deviation

The deviation of an observation from the population mean is:

xi−μx_i - \muxi​−μ

Population variance

σ2=1N∑i=1N(xi−μ)2\sigma^2 = \frac{1}{N} \sum_{i=1}^{N}(x_i-\mu)^2σ2=N1​∑i=1N​(xi​−μ)2

Sample variance

s2=1n−1∑i=1n(xi−xˉ)2s^2 = \frac{1}{n-1} \sum_{i=1}^{n}(x_i-\bar{x})^2s2=n−11​∑i=1n​(xi​−xˉ)2

The denominator uses n−1n-1n−1 for sample variance to reduce estimation bias.

Standard deviation

Standard deviation is the square root of variance:

σ=σ2\sigma = \sqrt{\sigma^2}σ=σ2​

or, for a sample,

s=s2s = \sqrt{s^2}s=s2​

A small standard deviation means values are close to the mean. A large standard deviation means the values are more dispersed.


21. Entropy and Information Gain

Entropy

Entropy measures uncertainty or impurity in a dataset.

For a binary classification problem:

H(S)=−∑i=1cpilog⁡2(pi)H(S) = -\sum_{i=1}^{c}p_i\log_2(p_i)H(S)=−∑i=1c​pi​log2​(pi​)

where pip_ipi​ is the proportion of observations belonging to class iii.

Properties:

  • Entropy is 000 when all observations belong to one class.

  • Entropy is highest when classes are evenly mixed.

  • For two classes, maximum entropy occurs when each class has probability 0.50.50.5.

Information gain

Information gain measures how much uncertainty is reduced by splitting data using an attribute:

IG(S,A)=H(S)−∑v∈Values(A)∣Sv∣∣S∣H(Sv)IG(S,A) = H(S) - \sum_{v\in Values(A)} \frac{|S_v|}{|S|} H(S_v)IG(S,A)=H(S)−∑v∈Values(A)​∣S∣∣Sv​∣​H(Sv​)

Decision trees generally choose the attribute with the greatest information gain for the next split.


22. Confusion Matrix

A confusion matrix evaluates a classification model by comparing actual and predicted classes.

Components

  • True positive (TP): The model predicts positive and the actual class is positive.

  • True negative (TN): The model predicts negative and the actual class is negative.

  • False positive (FP): The model predicts positive but the actual class is negative.

  • False negative (FN): The model predicts negative but the actual class is positive.

Accuracy

Accuracy=TP+TNTP+TN+FP+FN\text{Accuracy} = \frac{TP+TN}{TP+TN+FP+FN}Accuracy=TP+TN+FP+FNTP+TN​

Precision

Precision=TPTP+FP\text{Precision} = \frac{TP}{TP+FP}Precision=TP+FPTP​

Precision measures how many predicted positives are actually positive.

Recall

Recall=TPTP+FN\text{Recall} = \frac{TP}{TP+FN}Recall=TP+FNTP​

Recall measures how many actual positives were correctly identified.

F1 score

F1=2⋅Precision⋅RecallPrecision+RecallF_1 = 2\cdot \frac{\text{Precision}\cdot\text{Recall}} {\text{Precision}+\text{Recall}}F1​=2⋅Precision+RecallPrecision⋅Recall​

The F1 score balances precision and recall.


Probability

23. Probability Fundamentals

Probability measures how likely an event is to occur.

For equally likely outcomes:

P(E)=Number of favorable outcomesTotal number of outcomesP(E) = \frac{\text{Number of favorable outcomes}} {\text{Total number of outcomes}}P(E)=Total number of outcomesNumber of favorable outcomes​

Probability satisfies:

0≤P(E)≤10 \leq P(E) \leq 10≤P(E)≤1

The probabilities of all mutually exclusive outcomes sum to 111.

Random experiment

A process whose outcome cannot be predicted with certainty.

Sample space

The set of all possible outcomes.

Event

One or more outcomes of a random experiment.

Types of events

Disjoint events

Events that cannot occur simultaneously.

Example: A single card cannot be both a king and a queen.

Non-disjoint events

Events that can occur simultaneously.

Example: A student can score highly in both statistics and probability.


24. Probability Distributions

Probability density function

A probability density function (PDF) describes the likelihood of values for a continuous random variable.

Important properties:

  • The curve is continuous over its range.

  • The total area under the curve is 111.

  • The probability that a variable lies between aaa and bbb is the area under the curve between those values.

Normal distribution

The normal or Gaussian distribution is symmetric around its mean.

It is determined primarily by:

  • Mean μ\muμ, which determines the center

  • Standard deviation σ\sigmaσ, which determines the spread

A large standard deviation produces a wider, shorter curve. A small standard deviation produces a narrower, taller curve.

Central limit theorem

The central limit theorem states that the sampling distribution of the mean approaches a normal distribution when the sample size is sufficiently large, even if the original population is not normally distributed.

The accuracy depends on:

  • Sample size

  • Shape of the underlying population


25. Marginal, Joint, and Conditional Probability

Marginal probability

The probability of an event without considering another event.

Example:

P(heart)=1352P(\text{heart})=\frac{13}{52}P(heart)=5213​

Joint probability

The probability that two events occur together:

P(A∩B)P(A\cap B)P(A∩B)

Example: Drawing a card that is both red and a four.

Conditional probability

The probability of event BBB given that event AAA has occurred:

P(B∣A)=P(A∩B)P(A)P(B\mid A) = \frac{P(A\cap B)}{P(A)}P(B∣A)=P(A)P(A∩B)​

For independent events:

P(A∩B)=P(A)P(B)P(A\cap B)=P(A)P(B)P(A∩B)=P(A)P(B)

26. Bayes’ Theorem

Bayes’ theorem relates conditional probabilities:

P(A∣B)=P(B∣A)P(A)P(B)P(A\mid B) = \frac{P(B\mid A)P(A)}{P(B)}P(A∣B)=P(B)P(B∣A)P(A)​

Terms:

  • P(A)P(A)P(A): Prior probability

  • P(B∣A)P(B\mid A)P(B∣A): Likelihood

  • P(B)P(B)P(B): Evidence

  • P(A∣B)P(A\mid B)P(A∣B): Posterior probability

Bayes’ theorem is used in:

  • Spam filtering

  • Medical diagnosis

  • Document classification

  • Weather prediction

  • Fraud detection

  • Naive Bayes classification


Inferential Statistics

27. Point and Interval Estimation

Point estimation

A point estimate uses sample data to estimate one value of a population parameter.

Example: The sample mean estimates the population mean.

  • Estimator: The function used to calculate the estimate

  • Estimate: The numerical result produced by the estimator

Common estimation approaches include:

  • Method of moments

  • Maximum likelihood estimation

  • Bayesian estimation

  • Best unbiased estimation

Interval estimation

An interval estimate provides a range of plausible values for a population parameter.

It is generally more informative than a single point estimate because it communicates uncertainty.


28. Confidence Interval

A confidence interval is a range expected to contain a population parameter at a specified confidence level.

For example, a 99% confidence interval from 100100100 to 200200200 indicates that the estimation procedure has a high level of confidence that the population value lies within that range.

The confidence level describes the reliability of the interval-producing method; it does not mean that a fixed parameter has a literal probability of changing after the interval is calculated.

Margin of error

The margin of error measures the maximum expected distance between a point estimate and the population parameter at a given confidence level.

A common form is:

E=zcσnE = z_c\frac{\sigma}{\sqrt{n}}E=zc​n​σ​

where:

  • EEE is the margin of error

  • zcz_czc​ is the critical value

  • σ\sigmaσ is the standard deviation

  • nnn is the sample size

Confidence-interval procedure

  1. Choose a sample statistic.

  2. Select a confidence level.

  3. Find the critical value.

  4. Calculate the margin of error.

  5. Construct the interval around the point estimate.


29. Hypothesis Testing

Hypothesis testing determines whether sample evidence supports a claim about a population.

Main steps

  1. State the null hypothesis.

  2. State the alternative hypothesis.

  3. Define an analysis plan.

  4. Analyze the sample data.

  5. Calculate a test statistic or probability.

  6. Compare the result with a significance threshold.

  7. Reject or fail to reject the null hypothesis.

  8. Interpret the result in context.

Null hypothesis

The null hypothesis represents the default assumption, such as no effect, no difference, or no bias.

Alternative hypothesis

The alternative hypothesis represents the conclusion supported when the evidence is sufficiently inconsistent with the null hypothesis.

A common significance threshold is 0.050.050.05. If the probability of observing the result under the null hypothesis is below the threshold, the null hypothesis is rejected.


Linear Regression

30. Regression Analysis

Regression analysis studies the relationship between a dependent variable and one or more independent variables.

Uses include:

  • Measuring the strength of predictors

  • Forecasting effects

  • Predicting trends and future values

Linear regression model

For one independent variable:

y=mx+cy = mx+cy=mx+c

For multiple predictors:

y=β0+β1x1+β2x2+⋯+βnxny = \beta_0+\beta_1x_1+\beta_2x_2+\cdots+\beta_nx_ny=β0​+β1​x1​+β2​x2​+⋯+βn​xn​

Best-fit line

The best-fit line minimizes the difference between actual and predicted values.

A common error measure is the sum of squared errors:

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

where yiy_iyi​ is the actual value and y^i\hat{y}_iy^​i​ is the predicted value.

Least-squares method

The least-squares method chooses coefficients that minimize the total squared error.

For a simple linear model, the slope can be expressed as:

m=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2m= \frac{\sum_i(x_i-\bar{x})(y_i-\bar{y})} {\sum_i(x_i-\bar{x})^2}m=∑i​(xi​−xˉ)2∑i​(xi​−xˉ)(yi​−yˉ​)​

The intercept is:

c=yˉ−mxˉc=\bar{y}-m\bar{x}c=yˉ​−mxˉ

31. Evaluating Linear Regression

Coefficient of determination

The R2R^2R2 value measures how closely observations fit the regression model:

R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2R^2 = 1- \frac{\sum_i(y_i-\hat{y}_i)^2} {\sum_i(y_i-\bar{y})^2}R2=1−∑i​(yi​−yˉ​)2∑i​(yi​−y^​i​)2​

Interpretation:

  • R2R^2R2 near 111: predictions explain much of the variation.

  • R2R^2R2 near 000: predictions explain little of the variation.

A low R2R^2R2 is not always unacceptable. In fields involving human behavior, outcomes may be inherently difficult to predict.

Gradient descent

Gradient descent is an optimization technique that repeatedly adjusts model parameters to reduce the error function.

The parameters move in the direction of the negative gradient until the error is minimized or reaches an acceptable value.

Applications

  • Predicting sales from marketing expenditure

  • Estimating house prices

  • Studying the effect of price on demand

  • Predicting insurance claims

  • Forecasting trends

  • Estimating health-related risk


Logistic Regression

32. Logistic Regression

Logistic regression is a supervised-learning classification algorithm used when the output is categorical, especially binary.

Examples:

  • Yes or no

  • True or false

  • Disease or no disease

  • Purchase or no purchase

  • Survive or not survive

Unlike linear regression, logistic regression maps inputs to a probability using a sigmoid curve.

Logistic regression model

The linear combination is:

z=β0+β1x1+⋯+βnxnz=\beta_0+\beta_1x_1+\cdots+\beta_nx_nz=β0​+β1​x1​+⋯+βn​xn​

The probability is:

P(Y=1∣X)=11+e−zP(Y=1\mid X)=\frac{1}{1+e^{-z}}P(Y=1∣X)=1+e−z1​

A threshold converts the probability into a class.

Linear versus logistic regression

Linear regression

  • Predicts continuous values.

  • Uses a straight-line relationship.

  • Output can take values outside the interval [0,1][0,1][0,1].

  • Evaluated using measures such as R2R^2R2 and mean squared error.

Logistic regression

  • Predicts categorical values.

  • Uses a sigmoid function.

  • Produces probabilities between 000 and 111.

  • Evaluated using accuracy, precision, recall, F1 score, ROC curves, and confusion matrices.

Applications

  • Weather classification

  • Disease prediction

  • Fraud detection

  • Customer purchase prediction

  • Titanic survival analysis

  • Spam detection


Decision Trees and Random Forests

33. Decision Trees

A decision tree represents decisions graphically through nodes and branches.

Terminology

  • Root node: The first and highest node.

  • Internal node: A decision point.

  • Branch: A path resulting from a decision.

  • Leaf node: A final prediction.

  • Parent node: A node that produces child nodes.

  • Child node: A node produced by another node.

  • Splitting: Dividing data according to a condition.

  • Pruning: Removing unnecessary branches to reduce complexity.

Advantages

  • Easy to understand

  • Easy to visualize

  • Handles categorical and numerical features

  • Requires relatively little preprocessing

  • Provides interpretable rules

Decision-tree construction

  1. Begin with the complete dataset at the root.

  2. Consider possible questions about the features.

  3. Select the question that best separates the classes.

  4. Split the data into child nodes.

  5. Repeat recursively.

  6. Stop when further splitting is unnecessary.

  7. Optionally prune the tree.

Split-selection criteria

  • Gini impurity

  • Information gain

  • Variance reduction

  • Chi-square significance

Gini impurity

Gini impurity measures the probability that a randomly selected observation would be incorrectly classified if assigned according to the class distribution of its node.

For class probabilities pip_ipi​:

Gini(S)=1−∑ipi2Gini(S)=1-\sum_i p_i^2Gini(S)=1−∑i​pi2​

A pure node has Gini impurity 000.


34. Random Forests

A random forest is an ensemble of decision trees.

Each tree is trained using:

  • A random sample of observations

  • A random subset of features

The final prediction is generally obtained by majority voting for classification or averaging for regression.

Why random forests work

A single tree may have high variance or may overfit. Combining many diverse trees reduces the influence of individual errors.

Random-forest procedure

  1. Select random subsets of data.

  2. Select random subsets of features.

  3. Train a decision tree on each subset.

  4. Repeat to create many trees.

  5. Combine the predictions of all trees.

  6. Use majority voting or averaging.

Advantages

  • Strong predictive performance

  • Works for classification and regression

  • Handles large datasets

  • Requires limited preprocessing

  • Performs implicit feature selection

  • Can be trained in parallel

  • More resistant to overfitting than a single tree

  • Can handle complex nonlinear relationships

Applications

  • Credit-risk detection

  • Medical diagnosis

  • Land-use classification

  • Customer churn prediction

  • Marketing analysis


K-Nearest Neighbors

35. K-nearest Neighbors

K-nearest neighbors (KNN) predicts the class of a new observation based on the classes of its closest training examples.

Procedure

  1. Select a value of KKK.

  2. Calculate the distance between the new point and training points.

  3. Select the KKK closest points.

  4. Count the classes among those neighbors.

  5. Assign the most common class to the new point.

For K=1K=1K=1, the new point receives the class of its single closest neighbor.

Distance measures

Euclidean distance

For points P1P_1P1​ and P2P_2P2​:

d(P1,P2)=∑i(xi−yi)2d(P_1,P_2) = \sqrt{\sum_i(x_i-y_i)^2}d(P1​,P2​)=∑i​(xi​−yi​)2​

Manhattan distance

d(P1,P2)=∑i∣xi−yi∣d(P_1,P_2) = \sum_i|x_i-y_i|d(P1​,P2​)=∑i​∣xi​−yi​∣

Choosing KKK

A small KKK may make the model sensitive to noise. A large KKK may smooth away important local patterns. Cross-validation can help select an appropriate value.

Why KNN is called a lazy learner

KNN does not build a complex model during training. It stores the training data and performs most computation when a prediction is requested.

Applications

  • Recommendation systems

  • Image recognition

  • Handwriting recognition

  • Document similarity

  • Video recognition

  • Fraud-pattern detection

  • Automated retail checkout


Naive Bayes

36. Naive Bayes Classification

Naive Bayes is a probabilistic classification algorithm based on Bayes’ theorem.

It assumes that features are conditionally independent given the class. This assumption is often unrealistic, but the algorithm can still perform very well.

General principle

For a class CCC and features XXX:

P(C∣X)∝P(C)∏iP(xi∣C)P(C\mid X) \propto P(C)\prod_i P(x_i\mid C)P(C∣X)∝P(C)∏i​P(xi​∣C)

The class with the greatest posterior probability is selected.

Types

Gaussian Naive Bayes

Used when continuous features are assumed to follow a normal distribution.

Multinomial Naive Bayes

Used for discrete counts, especially word counts in text classification.

Bernoulli Naive Bayes

Used for binary features, such as whether a word appears or does not appear in a document.

Applications

  • Spam filtering

  • News classification

  • Text classification

  • Medical diagnosis

  • Weather prediction

  • Object classification

Strengths

  • Simple to implement

  • Fast to train and predict

  • Effective for large datasets

  • Performs well in text classification

  • Works even with relatively small training datasets


Support Vector Machines

37. Support Vector Machines

A support vector machine (SVM) is a supervised-learning algorithm that separates classes using a decision boundary called a hyperplane.

Main concepts

  • Hyperplane: The boundary separating classes.

  • Support vectors: The closest observations to the hyperplane.

  • Margin: The distance between the hyperplane and the closest support vectors.

The optimal hyperplane maximizes the margin.

Nonlinear data and kernels

Some datasets cannot be separated using a straight line. A kernel function transforms the data into a higher-dimensional feature space where a separating hyperplane may exist.

Features

  • Used for classification and regression

  • Effective in high-dimensional spaces

  • Can classify nonlinear data through kernels

  • Often works well with small and medium-sized datasets

Applications

  • Face recognition

  • Cancer classification

  • Image classification

  • Text categorization

  • Pattern recognition


Jupyter Notebook and Python Tools

38. Jupyter Notebook

A Jupyter Notebook is an interactive environment used to combine:

  • Python code

  • Explanatory text

  • Mathematical expressions

  • Visualizations

  • Tables

  • Outputs

A notebook records an analysis process similarly to a laboratory notebook.

Notebook structure

A notebook contains:

  • Metadata

  • Notebook-format information

  • A list of cells

Cells may contain:

  • Python code

  • Markdown text

  • Raw text

  • Output

Typical workflow

  1. Create a notebook for a project.

  2. Import libraries.

  3. Load data.

  4. Explore and visualize the data.

  5. Clean and transform the data.

  6. Train models.

  7. Evaluate results.

  8. Record conclusions and explanations.

Common tools

  • Anaconda: A distribution containing Python and common data-science packages.

  • Anaconda Navigator: A graphical interface for managing applications and environments.

  • pandas: Data manipulation and analysis.

  • NumPy: Numerical computation.

  • Matplotlib: Visualization.

  • Seaborn: Statistical visualization.

  • scikit-learn: Machine-learning algorithms and utilities.

Security

Jupyter notebooks can execute arbitrary code. Shared notebooks should therefore be treated carefully. HTML, JavaScript, and outputs may require trust verification, and notebooks should not be executed if their contents are untrusted.


Machine-Learning Projects and Evaluation

39. Iris Classification Project

The Iris dataset contains:

  • 150150150 flower observations

  • Four numerical features

  • Three species:

    • Iris setosa

    • Iris versicolor

    • Iris virginica

Typical workflow:

  1. Load the dataset.

  2. Inspect its dimensions and rows.

  3. Calculate summary statistics.

  4. Check class frequencies.

  5. Create box plots and histograms.

  6. Examine pairwise relationships.

  7. Split data into training and validation sets.

  8. Train several algorithms.

  9. Compare cross-validation accuracy.

  10. Evaluate the strongest model on unseen data.

Models commonly compared include:

  • Logistic regression

  • Linear discriminant analysis

  • KNN

  • Decision trees

  • Naive Bayes

  • SVM

A validation split may reserve approximately 20%20\%20% of the dataset for final evaluation, while cross-validation repeatedly divides the remaining data into training and testing folds.

40. Titanic Survival Project

A Titanic dataset may contain:

  • Passenger identifier

  • Survival outcome

  • Passenger class

  • Name

  • Gender

  • Age

  • Number of siblings or spouses

  • Number of parents or children

  • Ticket

  • Fare

  • Cabin

  • Port of embarkation

Typical steps:

  1. Import libraries.

  2. Load the dataset.

  3. Explore survival counts.

  4. Compare survival by gender.

  5. Compare survival by passenger class.

  6. Examine age and fare distributions.

  7. Identify missing values.

  8. Drop or impute unsuitable columns.

  9. Convert categorical variables into numerical dummy variables.

  10. Split data into training and test sets.

  11. Train logistic regression.

  12. Evaluate with a classification report and confusion matrix.

41. SUV Purchase Prediction

An SUV-purchase dataset may contain:

  • User ID

  • Gender

  • Age

  • Estimated salary

  • Purchase outcome

Age and salary can serve as independent variables, while purchase status is the dependent variable.

Because age and salary may have very different scales, standardization can improve model behavior:

z=x−μσz=\frac{x-\mu}{\sigma}z=σx−μ​

Association Rule Mining and Apriori

42. Market-Basket Analysis

Market-basket analysis identifies products that frequently occur together in transactions.

Example:

  • Customers who buy bread may also buy butter.

  • Customers who buy a laptop may also buy a laptop bag.

Association rule

An association rule has the form:

A⇒BA \Rightarrow BA⇒B

This means that transactions containing AAA often also contain BBB.

Support

Support measures how frequently AAA and BBB occur together:

Support(A⇒B)=Transactions containing A and BTotal transactionsSupport(A\Rightarrow B) = \frac{\text{Transactions containing }A\text{ and }B} {\text{Total transactions}}Support(A⇒B)=Total transactionsTransactions containing A and B​

Confidence

Confidence measures how often BBB appears when AAA appears:

Confidence(A⇒B)=Support(A∪B)Support(A)Confidence(A\Rightarrow B) = \frac{Support(A\cup B)} {Support(A)}Confidence(A⇒B)=Support(A)Support(A∪B)​

Lift

Lift measures how much more often AAA and BBB occur together than would be expected if they were independent:

Lift(A⇒B)=Support(A∪B)Support(A) Support(B)Lift(A\Rightarrow B) = \frac{Support(A\cup B)} {Support(A)\,Support(B)}Lift(A⇒B)=Support(A)Support(B)Support(A∪B)​
  • Lift >1>1>1: Positive association

  • Lift =1=1=1: Approximate independence

  • Lift <1<1<1: Negative association

Apriori algorithm

Apriori uses the principle that every subset of a frequent itemset must also be frequent.

Procedure:

  1. Find frequent one-item sets.

  2. Remove itemsets below minimum support.

  3. Generate larger candidate itemsets.

  4. Remove candidates containing infrequent subsets.

  5. Repeat until no larger frequent sets remain.

  6. Generate rules from the frequent itemsets.

  7. Filter rules using confidence and lift.

Applications include:

  • Product recommendations

  • Promotional offers

  • Store layout

  • Cross-selling

  • Customer behavior analysis


Machine-Learning Engineering

43. Role of a Machine-Learning Engineer

A machine-learning engineer develops systems that learn from data and make predictions or decisions with limited explicit programming.

Typical responsibilities include:

  • Transforming data-science prototypes into working systems

  • Designing machine-learning pipelines

  • Selecting algorithms

  • Preparing datasets

  • Developing machine-learning applications

  • Running experiments

  • Performing statistical analysis

  • Tuning models

  • Evaluating performance

  • Retraining models

  • Extending libraries and frameworks

  • Monitoring new research and tools

44. Technical Skills

Programming

Important languages and tools include:

  • Python

  • R

  • Java

  • C++

  • SQL

  • Hadoop-related technologies

Python is widely used because of its libraries for data analysis, visualization, and machine learning.

Mathematics

Important topics include:

  • Linear algebra

  • Vectors

  • Matrices

  • Matrix multiplication

  • Calculus

  • Derivatives

  • Integrals

  • Partial differentiation

  • Gradient descent

  • Convex optimization

  • Probability

  • Statistics

Machine learning

A strong engineer should understand:

  • Regression

  • Classification

  • Clustering

  • Decision trees

  • Random forests

  • SVMs

  • Neural networks

  • Reinforcement learning

  • Model evaluation

Signal processing

Useful topics include:

  • Feature extraction

  • Fourier transforms

  • Time-frequency analysis

  • Wavelets

  • Spectral methods

Natural-language processing

Relevant skills include:

  • Text preprocessing

  • Tokenization

  • Sentiment analysis

  • Text summarization

  • Language modeling

  • Speech and audio analysis

Neural networks and deep learning

Knowledge may include:

  • Artificial neurons

  • Multilayer networks

  • Convolutional neural networks

  • Recurrent architectures

  • Representation learning

  • Model optimization

45. Professional and Soft Skills

Industry knowledge

A machine-learning solution must address a real business or scientific problem. Understanding the industry helps identify useful variables, constraints, risks, and opportunities.

Communication

Engineers must explain technical results to nontechnical teams such as management, sales, and marketing.

Rapid prototyping

Machine-learning development requires quickly testing:

  • Models

  • Features

  • Hyperparameters

  • Data-processing strategies

  • Experimental ideas

Continuous learning

The field changes rapidly. Engineers should follow:

  • Research papers

  • Technical blogs

  • Conferences

  • Framework updates

  • New algorithms

  • Open-source projects

Additional useful areas

  • Computer vision

  • Physics

  • Robotics

  • Reinforcement learning

  • Distributed computing

  • Cloud technologies

46. Resume and Career Preparation

A machine-learning resume commonly includes:

  • Career objective

  • Technical skills

  • Nontechnical skills

  • Education

  • Certifications

  • Professional experience

  • Machine-learning projects

Useful projects should demonstrate practical abilities such as:

  • Data cleaning

  • Visualization

  • Feature engineering

  • Model training

  • Evaluation

  • Deployment

  • Neural-network or AI applications

A strong portfolio shows that the candidate can move from raw data to a tested, interpretable, and useful solution.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent