Machine Learning Basics
Machine Learning Study Notes
What is Data Science?
Data science (also called data-driven science) is an interdisciplinary field that uses scientific methods, processes, and systems to extract knowledge or insights from data in various forms — structured or unstructured. It studies where information comes from, what it represents, and how it can be turned into a valuable resource for creating business and IT strategies.
Data science employs techniques from mathematics, statistics, information science, and computer science. It can be applied even to small data sets, though many associate it with big data.
Key pillars of data science
Statistics – foundational methods for data analysis
Programming languages – Python, R, SAS
Software and deployment tools – used to bundle models and present findings
Machine learning – the core topic of these notes
Big data – large-scale data processing technologies
What is Machine Learning?
Machine learning is an application of artificial intelligence that provides systems the ability to automatically learn and improve from experience without being explicitly programmed. Instead of writing explicit rules, the computer uses data to find patterns and make decisions.
Machine learning is a class of data-driven algorithms: unlike traditional programs, it is the data that determines the correct answer.
Features of machine learning
Uses data to detect patterns and adjust program actions accordingly
Focuses on programs that can teach themselves to grow and change when exposed to new data
Enables computers to find hidden insights using iterative algorithms
Automates analytical model building
Traditional programming vs. machine learning
Aspect | Traditional Programming | Machine Learning |
|---|---|---|
Input | Data + Program | Data + Expected Output |
Process | Computer executes instructions | Computer learns from data, finds patterns |
Output | Hard-coded result | Model that can make predictions |
Adaptation | Needs manual code changes | Retrains with new data automatically |
Applications of Machine Learning
🗺️ Navigation (Google Maps)
Google Maps combines real-time user location data, historical traffic patterns, and machine learning to predict traffic and suggest the fastest routes. Every user provides location and average speed, which helps the system adjust routes dynamically.
👥 Social Media (Facebook)
Automatic friend tag suggestions – Facebook uses DeepFace, a machine learning project for face recognition.
When uploading a photo, the system detects faces, matches them to the database, and suggests tags.
Alt text generation – Images are automatically described (e.g., "image may contain: sky, grass, outdoor, nature").
🚗 Transportation & Commuting (Uber)
Provides personalized experiences: automatic detection of frequent destinations (home, office)
Uses historic trip data and machine learning algorithms for accurate ETA predictions
Uber saw a 26% improvement in delivery and pickup accuracy after implementing ML
🎤 Virtual Personal Assistants
Use speech recognition, speech-to-text conversion, natural language processing, and text-to-speech
Respond to voice or text queries (e.g., "What is my schedule for tomorrow?")
Now embedded in chatbots for food ordering, online training, and commuting apps
🛒 Product Recommendation (Amazon)
Tracks user search history and browsing behavior
Shows ads for items the user viewed across different sites
35% of Amazon's revenue is generated by product recommendations
🚘 Self-Driving Cars (Tesla)
Tesla uses unsupervised learning algorithms (powered by Nvidia hardware)
The model learns from data collected from other vehicles and drivers (sensors, IoT)
McKinsey estimates the autonomous vehicle market will be worth $750 billion
🌐 Google Translate
Google Neural Machine Translation (GNMT) uses neural machine learning
Works with thousands of languages and dictionaries
Employs natural language processing techniques: POS tagging, named entity recognition, chunking
💲 Dynamic Pricing (Uber, airlines)
Machine learning enables pricing solutions to track buying trends and set competitive prices
Uber uses a model called GeoSurge for surge pricing based on demand
📺 Online Video Streaming (Netflix)
Collects massive data: when you pause, rewind, fast-forward, what content you watch on weekdays vs. weekends, ratings (~4M per day), searches (~3M per day), browsing behavior
Uses recommender systems and machine learning to personalize suggestions
Drives high customer retention
Market Trend of Machine Learning
Significant growth occurred around 2016, driven by two factors:
Big data became widely available (the raw material needed for ML)
Hardware advancements provided the computational power to train complex models
Before 2016, the ideas existed but lacked sufficient data and computing resources
Machine Learning Life Cycle
A typical ML project follows six steps:
Data Collection – Gather relevant data from various sources
Data Wrangling – Clean and convert raw data into a usable format
Handling missing values, wrong values, inconsistent formats
Often the most time-consuming step
Data Analysis – Select and filter data required for the model
Train the Algorithm – Use the training dataset so the algorithm learns patterns and rules
Test the Algorithm – Evaluate model accuracy using a separate test dataset
Deployment & Optimization – Deploy the model in production; monitor performance and retrain if needed
Fitting a model means the algorithm learns the relationship between predictors and outcomes to predict future values.
Types of Fitting
Underfitting – Model is too simple and does not capture the data pattern well
Appropriate fit – Model generalizes well
Overfitting – Model has low error on training data but does not generalize to new data
Python Libraries for Machine Learning
Library | Purpose |
|---|---|
Matplotlib | Visualization (bar charts, scatter plots, line charts, histograms) |
Seaborn | Statistical visualizations (heatmaps, distributions) – built on Matplotlib |
Scikit-learn | Simple, efficient tools for data mining and analysis – most famous ML library |
Pandas | Data wrangling, manipulation, aggregation, and visualization |
NumPy | Numerical Python – operations on n-dimensional arrays and matrices, mathematical functions |
Types of Machine Learning
Machine learning is divided into three main types:
📚 Supervised Learning
Input variable X and output variable Y are provided. The algorithm learns a mapping function from input to output. The process is like a teacher supervising the learning.
Example: Face detection – the model is trained with labeled images (face / not face); testing uses labeled data to measure accuracy.
📚 Unsupervised Learning
The data has no labels. The model must find patterns, groupings, or clusters on its own based on statistical properties.
Example: Clustering fruits by color and shape – the algorithm groups similar items without being told what each group represents.
📚 Reinforcement Learning
An agent learns by interacting with an environment. It takes actions and receives rewards (positive or negative). The agent learns from consequences, not explicit teaching.
Example: A baby learning to walk – positive reward (reaching candy), negative reward (falling). The agent finds the best path to maximize rewards.
Supervised Learning Algorithms
Linear Regression
Used to estimate real (continuous) values such as house prices, number of calls, total sales.
The simple linear regression model is:
Y = dependent variable (what we predict)
a = y-intercept (value of Y when X=0)
b = slope (change in Y per unit change in X)
X = independent variable
Correlation measures the mutual relationship between variables. It is used to create correlation plots (e.g., using Seaborn heatmaps).
The regression line is the single line that best fits the data points (minimizing overall distance from points to the line).
Demo: Boston Housing Dataset
Goal: Predict housing prices based on features like crime rate, rooms, distance to employment centers
Steps:
Import libraries (NumPy, Pandas, Matplotlib, Seaborn)
Load data, split into independent (X) and dependent (Y) variables
Plot correlation heatmap to see feature relationships
Use
train_test_splitto split data (e.g., 67% train, 33% test)Import
LinearRegressionfrom scikit-learnFit model on training data (
lm.fit(X_train, y_train))Predict on test data (
lm.predict(X_test))Plot scatter of actual vs. predicted values to evaluate fit
The model learns parameters (slope m and intercept c in y=mx+c) that best define the problem.
Logistic Regression
Used when the output is discrete / binary (0 or 1, yes/no, true/false).
Example: Predicting whether a candidate wins an election (win/lose)
Why not linear regression? A linear model can produce values below 0 or above 1, and it cannot be formulated as a single formula for discrete outputs.
The logistic regression curve is a sigmoid curve (S-curve). It converts any value from −∞ to +∞ to a value between 0 and 1.
A threshold is set (e.g., 0.4). Values above the threshold are rounded to 1, below to 0.
Polynomial regression is used for nonlinear data that cannot be predicted with a linear model:
Demo: Breast Cancer Dataset (Wisconsin)
Goal: Predict whether a tumor is benign (0) or malignant (1)
Features: radius, texture, perimeter, area, smoothness, etc.
Steps:
Load data, drop unnecessary columns (ID, unnamed)
Map diagnosis column: M → 1, B → 0
Plot diagnosis frequency, correlation heatmap
Select features (e.g., texture_mean, perimeter_mean, smoothness_mean, compactness_mean, symmetry_mean)
Split into train/test (30% test)
Use
LogisticRegressionfrom scikit-learnFit model, predict, check accuracy (~91%)
Also use
DecisionTreeClassifierfor comparison
Decision Trees
A tree-like structure where:
Internal nodes represent tests on attributes
Branches represent outcomes of tests
Leaf nodes represent class labels (decisions)
Decision trees work for both categorical and continuous variables.
Example: Play Tennis Dataset
Attributes: Outlook (Sunny, Overcast, Rainy), Humidity (High, Normal), Wind (Weak, Strong)
Process: Starting from root, split data based on attributes until pure subsets are obtained
Final tree: If Outlook is Overcast → Play; if Sunny → check Humidity; if Rainy → check Wind
Random Forest
An ensemble classifier made of many decision trees. Each tree votes for a class; the final decision is based on majority vote.
Advantages over decision trees:
More accurate
Efficient on large datasets
Handles thousands of input variables without deletion
Provides estimates of variable importance
Random forest generally gives better prediction and accuracy than a single decision tree.
Demo: Hurricanes and Typhoons Dataset (1851–2014)
Goal: Classify storms into categories (TD, TS, HU, EX, ST, SS, LO, DB)
Steps:
Load data, convert status to categorical
Drop unnecessary columns (ID, name, date, time, latitude, longitude)
Split into train/test (70/30)
Use
RandomForestClassifierwith 100 estimatorsFit, predict, check accuracy (~95.66%)
Compare with
DecisionTreeClassifier(~95.57%) – random forest slightly better
Naive Bayes
A classification technique based on Bayes' theorem with the assumption of independence between predictors. Despite the assumption, it is surprisingly powerful.
Naive Bayes assumes that the presence of a particular feature in a class is unrelated to the presence of any other feature.
Bayes' Theorem
P(H) = prior probability of hypothesis
P(E∣H) = probability of evidence given hypothesis
P(H∣E) = posterior probability
Conditional probability: The probability of an event happening given that it has some relationship to one or more other events.
Example: Play Tennis using Naive Bayes
Given a day with Outlook=Rain, Humidity=High, Wind=Weak
Calculate likelihood of Yes: P(Rain∣Yes)×P(High∣Yes)×P(Weak∣Yes)×P(Yes)
Calculate likelihood of No similarly
Normalize to get probabilities: P(Yes)=0.55, P(No)=0.45
Model predicts 55% chance of play
Industrial Use Cases
News categorization
Spam filtering (classify email as spam or ham)
Weather prediction
Demo: Run or Walk Dataset
Kinematic data from mobile sensors (acceleration, gyroscope)
Steps:
Load data
Split into train/test (20% test)
Use
GaussianNBfrom scikit-learnFit, predict, accuracy ≈ 95.54%
Generate confusion matrix and classification report
Scikit-learn is the most important library for ML in Python – it contains all these algorithms ready to use.
Unsupervised Learning Algorithms
When data are unstructured and unlabeled, unsupervised learning clusters data into classes based on statistical properties.
No labels or responses – the algorithm must find structure
The goal is to determine intrinsic groupings in unlabeled data
Clustering
The process of dividing a dataset into groups of similar data points.
Types of Clustering
Type | Description | Example |
|---|---|---|
Exclusive (Hard) Clustering | Each item belongs to exactly one cluster | K-Means |
Overlapping (Soft) Clustering | Each item can belong to multiple clusters with degrees of membership | Fuzzy C-Means |
Hierarchical Clustering | Clusters have a parent-child, tree-like structure | Agglomerative / Divisive |
Use Cases
Marketing – discovering customer groups (e.g., high callers, heavy internet users)
Insurance – identifying high-risk policyholders
Oil exploration – analyzing seismic data
Recommendation systems – grouping movies or products
K-Means Clustering
An algorithm that groups similar data points into a predefined number of clusters (k).
Algorithm steps:
Decide the number of clusters k
Initialize k centroids (randomly or cleverly)
Calculate the Euclidean distance from each point to each centroid
Assign each point to the closest centroid (forming k clusters)
Recalculate centroids as the mean of points in each cluster
Repeat steps 3–5 until centroids converge (no change or minimal change)
How to choose k? – The elbow method:
Compute the sum of squared errors (SSE) for different values of k
Plot k vs. SSE; the "elbow" point where SSE decreases abruptly is the optimal k
Pros:
Simple and understandable
Items automatically assigned to clusters
Cons:
Must define k beforehand (difficult if unknown)
All items forced into a cluster, even if they don't belong
Sensitive to noisy data and outliers
Results depend on initial centroid placement
Demo: Movie Dataset
Goal: Group 5000 movies into clusters based on Facebook likes (director, actor 3)
Steps:
Load data, select director Facebook likes and actor 3 Facebook likes
Use
KMeansfrom scikit-learn with k=5Fit data, find cluster centers and labels
Plot clusters; notice cluster 0 and cluster 3 are very close, indicating possible suboptimal k
Fuzzy C-Means Clustering
An extension of k-means where each data point can belong to more than one cluster with a degree of membership (between 0 and 1). The sum of memberships for a point across all clusters must equal 1.
Affinity is proportional to distance from the point to the cluster center
Useful for gene expression where genes are involved in multiple functions
Pros:
Allows data points to be in multiple clusters (more realistic)
Cons:
Must define c (number of clusters) – same issue as k
Must determine membership cutoff value (time-consuming)
Sensitive to initial centroid assignment
Non-deterministic algorithm (different runs may give different results)
Hierarchical Clustering
Builds a hierarchy of clusters either bottom-up (agglomerative) or top-down (divisive) without requiring the number of clusters beforehand.
Agglomerative algorithm:
Put each data point in its own cluster
Combine the two closest clusters into one
Repeat step 2 until all points are in a single cluster
Pros:
No assumption about the number of clusters required
May correspond to meaningful taxonomies
Cons:
Once two clusters are combined, it cannot be undone
Very slow for large datasets
Association Rule Mining & Market Basket Analysis
Used by retailers to uncover associations between items that are bought together.
Example: People who buy bread also tend to buy butter. Retailers can then offer a discount on eggs to customers who buy bread and butter.
Key concepts:
Support – fraction of transactions containing item A and B together
Support(A∪B)=Total transactionsTransactions containing both A and BConfidence – how often A and B occur together given the number of times A occurs
Confidence(A⇒B)=Support(A)Support(A∪B)Lift – strength of the rule over random occurrence
Lift(A⇒B)=Support(A)×Support(B)Support(A∪B)Lift > 1 indicates a strong positive association (items appear together more often than by chance)
A Priori Algorithm
Uses frequent itemsets (itemsets that meet a minimum support threshold) to generate association rules. It is based on the principle: A subset of a frequent itemset must also be frequent.
Steps:
Build list of itemsets of size 1 with support ≥ min support
Generate candidate itemsets of size 2 from frequent size-1 itemsets; compute support; keep those meeting min support
Repeat for larger sizes: generate candidates, prune those with any subset that is not frequent (apriori principle), compute support
Stop when no more candidate itemsets can be generated
Generate rules: for each frequent itemset I, consider all subsets s. Rule s⇒(I−s) is valid if confidence ≥ min confidence
Demo: Online Retail Dataset
Goal: Find relationships between items purchased in France
Steps:
Load data, clean (remove spaces, drop non-invoice rows, remove credit transactions)
Consolidate items into one row per invoice (pivot table)
Convert quantities to binary (1 if > 0, else 0)
Use
apriorifrom mlxtend with min support 0.07Generate association rules with
association_rules(metric = lift, threshold = 1)Filter for high lift (> 6) and high confidence (> 0.8) to find strongest rules
Reinforcement Learning
A type of machine learning where an agent learns to behave in an environment by performing actions and observing rewards.
No training dataset with expected outputs – the agent learns from its own experience (trial and error)
Key Definitions
Term | Description |
|---|---|
Agent | The reinforcement learning algorithm that learns |
Environment | The world the agent moves through |
Action (a) | All possible steps the agent can take |
State (s) | Current condition returned by the environment |
Reward (R) | Instant feedback from the environment to appraise the last action |
Policy (π) | The strategy the agent uses to determine the next action based on current state |
Value (V) | Expected long-term return (with discount) |
Action-Value (Q) | Similar to value, but also depends on the current action |
Reward Maximization
The agent aims to maximize cumulative discounted reward:
γ (gamma) is the discount factor between 0 and 1
Small γ → large discount (rewards far in the future are less important)
Large γ → small discount (future rewards matter more)
Example: A fox wants to eat meat without being eaten by a tiger. Meat near the tiger is discounted because of the risk.
Exploration vs. Exploitation
Exploitation – using known information to maximize rewards
Exploration – trying new actions to discover potentially better rewards
Epsilon-Greedy Algorithm
With probability 1−ϵ: exploit (choose the best known action)
With probability ϵ: explore (choose a random action)
Markov Decision Process (MDP)
The mathematical framework for reinforcement learning. It consists of:
Set of states S
Set of actions A
Reward function R
Policy π
Transition function T (probability that action a in state s leads to s′)
The agent must take actions to transition from start state to end state, maximizing cumulative rewards.
Example: Shortest Path Problem
Nodes A, B, C, D; edges have costs
Goal: Find the cheapest path from A to D
State = current node
Action = traverse an edge
Reward = negative cost (or cost to minimize)
Optimal policy: A → C → D (cost = 20)
Q-Learning
A popular reinforcement learning algorithm that learns an optimal action-value function Q(s,a).
Q-learning update rule:
s = current state
a = action taken
R(s,a) = immediate reward
s′ = next state
maxa′Q(s′,a′) = maximum Q-value for next state
Example: Five Rooms and Outside
Rooms 0–4 inside a building, Room 5 is outside
Goal: Reach room 5 (outside)
Rewards: Direct doors to room 5 have reward 100; others have 0; invalid moves have -1
Algorithm steps:
Set γ=0.8, initialize Q matrix to zeros
Choose random initial state (e.g., room 1)
From current state, select an action (e.g., go to room 5)
Compute Q update using the formula
Repeat for many episodes (iterations) until Q converges
The optimal path can be extracted: e.g., from room 2, go to room 3 → room 1 → room 5
Python Implementation
Define R matrix as a NumPy array
Initialize Q matrix with zeros
Loop over 10,000 iterations:
From current state, get available actions
Choose random action
Compute next state
Update Q using the formula
After convergence, normalize Q (divide by max value)
The learned policy shows the optimal path to reach the goal
Reinforcement learning is about an agent learning the most optimal path to maximize reward through millions of interactions with the environment.
This concludes the comprehensive notes on machine learning. Key takeaways:
Machine learning automates pattern discovery from data
Three main types: supervised, unsupervised, reinforcement
Essential Python libraries: scikit-learn, pandas, numpy, matplotlib, seaborn
Each algorithm has specific use cases, strengths, and weaknesses
Practical implementation involves data collection, cleaning, model training, testing, and deployment

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