1. Home
  2. Explore
  3. Computer Science
  4. Machine Learning Basics

Study methods

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

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:

  1. Data Collection – Gather relevant data from various sources

  2. Data Wrangling – Clean and convert raw data into a usable format

    • Handling missing values, wrong values, inconsistent formats

    • Often the most time-consuming step

  3. Data Analysis – Select and filter data required for the model

  4. Train the Algorithm – Use the training dataset so the algorithm learns patterns and rules

  5. Test the Algorithm – Evaluate model accuracy using a separate test dataset

  6. 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 XXX and output variable YYY 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=a+bXY = a + bXY=a+bX
  • YYY = dependent variable (what we predict)

  • aaa = y-intercept (value of YYY when X=0X = 0X=0)

  • bbb = slope (change in YYY per unit change in XXX)

  • XXX = 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:

    1. Import libraries (NumPy, Pandas, Matplotlib, Seaborn)

    2. Load data, split into independent (XXX) and dependent (YYY) variables

    3. Plot correlation heatmap to see feature relationships

    4. Use train_test_split to split data (e.g., 67% train, 33% test)

    5. Import LinearRegression from scikit-learn

    6. Fit model on training data (lm.fit(X_train, y_train))

    7. Predict on test data (lm.predict(X_test))

    8. Plot scatter of actual vs. predicted values to evaluate fit

The model learns parameters (slope mmm and intercept ccc in y=mx+cy = mx + cy=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 −∞-\infty−∞ to +∞+\infty+∞ to a value between 0 and 1.

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

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:

Y=b0+b1X+b2X2+b3X3+…Y = b_0 + b_1X + b_2X^2 + b_3X^3 + \dotsY=b0​+b1​X+b2​X2+b3​X3+…

Demo: Breast Cancer Dataset (Wisconsin)

  • Goal: Predict whether a tumor is benign (0) or malignant (1)

  • Features: radius, texture, perimeter, area, smoothness, etc.

  • Steps:

    1. Load data, drop unnecessary columns (ID, unnamed)

    2. Map diagnosis column: M → 1, B → 0

    3. Plot diagnosis frequency, correlation heatmap

    4. Select features (e.g., texture_mean, perimeter_mean, smoothness_mean, compactness_mean, symmetry_mean)

    5. Split into train/test (30% test)

    6. Use LogisticRegression from scikit-learn

    7. Fit model, predict, check accuracy (~91%)

    8. Also use DecisionTreeClassifier for 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:

    1. Load data, convert status to categorical

    2. Drop unnecessary columns (ID, name, date, time, latitude, longitude)

    3. Split into train/test (70/30)

    4. Use RandomForestClassifier with 100 estimators

    5. Fit, predict, check accuracy (~95.66%)

    6. 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∣E)=P(E∣H)⋅P(H)P(E)P(H | E) = \frac{P(E | H) \cdot P(H)}{P(E)}P(H∣E)=P(E)P(E∣H)⋅P(H)​
  • P(H)P(H)P(H) = prior probability of hypothesis

  • P(E∣H)P(E | H)P(E∣H) = probability of evidence given hypothesis

  • P(H∣E)P(H | E)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)P(\text{Rain}|\text{Yes}) \times P(\text{High}|\text{Yes}) \times P(\text{Weak}|\text{Yes}) \times P(\text{Yes})P(Rain∣Yes)×P(High∣Yes)×P(Weak∣Yes)×P(Yes)

  • Calculate likelihood of No similarly

  • Normalize to get probabilities: P(Yes)=0.55P(\text{Yes}) = 0.55P(Yes)=0.55, P(No)=0.45P(\text{No}) = 0.45P(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:

    1. Load data

    2. Split into train/test (20% test)

    3. Use GaussianNB from scikit-learn

    4. Fit, predict, accuracy ≈ 95.54%

    5. 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 (kkk).

Algorithm steps:

  1. Decide the number of clusters kkk

  2. Initialize kkk centroids (randomly or cleverly)

  3. Calculate the Euclidean distance from each point to each centroid

  4. Assign each point to the closest centroid (forming kkk clusters)

  5. Recalculate centroids as the mean of points in each cluster

  6. Repeat steps 3–5 until centroids converge (no change or minimal change)

How to choose kkk? – The elbow method:

  • Compute the sum of squared errors (SSE) for different values of kkk

  • Plot kkk vs. SSE; the "elbow" point where SSE decreases abruptly is the optimal kkk

Pros:

  • Simple and understandable

  • Items automatically assigned to clusters

Cons:

  • Must define kkk 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:

    1. Load data, select director Facebook likes and actor 3 Facebook likes

    2. Use KMeans from scikit-learn with k=5k = 5k=5

    3. Fit data, find cluster centers and labels

    4. Plot clusters; notice cluster 0 and cluster 3 are very close, indicating possible suboptimal kkk

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 ccc (number of clusters) – same issue as kkk

  • 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:

  1. Put each data point in its own cluster

  2. Combine the two closest clusters into one

  3. 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)=Transactions containing both A and BTotal transactions\text{Support}(A \cup B) = \frac{\text{Transactions containing both A and B}}{\text{Total transactions}}Support(A∪B)=Total transactionsTransactions containing both A and B​
  • Confidence – how often A and B occur together given the number of times A occurs

    Confidence(A⇒B)=Support(A∪B)Support(A)\text{Confidence}(A \Rightarrow B) = \frac{\text{Support}(A \cup B)}{\text{Support}(A)}Confidence(A⇒B)=Support(A)Support(A∪B)​
  • Lift – strength of the rule over random occurrence

    Lift(A⇒B)=Support(A∪B)Support(A)×Support(B)\text{Lift}(A \Rightarrow B) = \frac{\text{Support}(A \cup B)}{\text{Support}(A) \times \text{Support}(B)}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:

  1. Build list of itemsets of size 1 with support ≥ min support

  2. Generate candidate itemsets of size 2 from frequent size-1 itemsets; compute support; keep those meeting min support

  3. Repeat for larger sizes: generate candidates, prune those with any subset that is not frequent (apriori principle), compute support

  4. Stop when no more candidate itemsets can be generated

  5. Generate rules: for each frequent itemset III, consider all subsets sss. Rule s⇒(I−s)s \Rightarrow (I - s)s⇒(I−s) is valid if confidence ≥ min confidence

Demo: Online Retail Dataset

  • Goal: Find relationships between items purchased in France

  • Steps:

    1. Load data, clean (remove spaces, drop non-invoice rows, remove credit transactions)

    2. Consolidate items into one row per invoice (pivot table)

    3. Convert quantities to binary (1 if > 0, else 0)

    4. Use apriori from mlxtend with min support 0.07

    5. Generate association rules with association_rules (metric = lift, threshold = 1)

    6. 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 (aaa)

All possible steps the agent can take

State (sss)

Current condition returned by the environment

Reward (RRR)

Instant feedback from the environment to appraise the last action

Policy (π\piπ)

The strategy the agent uses to determine the next action based on current state

Value (VVV)

Expected long-term return (with discount)

Action-Value (QQQ)

Similar to value, but also depends on the current action

Reward Maximization

The agent aims to maximize cumulative discounted reward:

Gt=∑k=0∞γkRt+k+1G_t = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1}Gt​=∑k=0∞​γkRt+k+1​
  • γ\gammaγ (gamma) is the discount factor between 0 and 1

    • Small γ\gammaγ → large discount (rewards far in the future are less important)

    • Large γ\gammaγ → 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−ϵ1 - \epsilon1−ϵ: exploit (choose the best known action)

  • With probability ϵ\epsilonϵ: explore (choose a random action)

Markov Decision Process (MDP)

The mathematical framework for reinforcement learning. It consists of:

  • Set of states SSS

  • Set of actions AAA

  • Reward function RRR

  • Policy π\piπ

  • Transition function TTT (probability that action aaa in state sss leads to s′s'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(s, a)Q(s,a).

Q-learning update rule:

Q(s,a)←R(s,a)+γ⋅max⁡a′Q(s′,a′)Q(s, a) \leftarrow R(s, a) + \gamma \cdot \max_{a'} Q(s', a')Q(s,a)←R(s,a)+γ⋅maxa′​Q(s′,a′)
  • sss = current state

  • aaa = action taken

  • R(s,a)R(s, a)R(s,a) = immediate reward

  • s′s's′ = next state

  • max⁡a′Q(s′,a′)\max_{a'} Q(s', a')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:

  1. Set γ=0.8\gamma = 0.8γ=0.8, initialize QQQ matrix to zeros

  2. Choose random initial state (e.g., room 1)

  3. From current state, select an action (e.g., go to room 5)

  4. Compute QQQ update using the formula

  5. Repeat for many episodes (iterations) until QQQ converges

  6. The optimal path can be extracted: e.g., from room 2, go to room 3 → room 1 → room 5

Python Implementation

  • Define RRR matrix as a NumPy array

  • Initialize QQQ matrix with zeros

  • Loop over 10,000 iterations:

    • From current state, get available actions

    • Choose random action

    • Compute next state

    • Update QQQ using the formula

  • After convergence, normalize QQQ (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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent