1. Home
  2. Explore
  3. Computer Science
  4. Data-Driven Business with ML

Study methods

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

Data-Driven Business with ML

Machine Learning Algorithms: Comprehensive Study Notes


Need for Algorithms

Algorithms are fundamental to both human cognition and computing. Everyday activities such as walking, driving, or singing rely on the brain executing a set of pre-trained steps. This process of learning and repetition is essentially an algorithm. As a toddler, maintaining balance while walking required repeated practice; eventually the brain mastered the steps unconsciously — the same principle underpins machine learning.

Historically, algorithms have been used for decades. A notable example is Alan Turing, who decoded the encrypted Enigma messages during World War II, helping end the war. This demonstrates that algorithms are not new; they are an age-old tradition now leveraged in computer science.

In modern contexts, the explosion of data generation necessitates algorithms for processing, cleaning, and understanding massive datasets. Without algorithms, making sense of raw data would be impractical.


What Is an Algorithm?

A formal definition: An algorithm is a set of rules or processes to be followed in calculations or other problem-solving operations, especially by a computer. Algorithms are everywhere:

  • YouTube recommendation algorithm suggests videos based on your viewing history.

  • Gmail spam filter uses algorithms to classify emails as spam or legitimate.

  • Operating systems (Windows, macOS, Android) run countless algorithms continuously.


Pseudocode and Flowcharts

Algorithms can be expressed in multiple forms. Two common representations are pseudocode and flowcharts.

Simple Example: Adding Two Numbers

  • Pseudocode:

    START
    INPUT A = 10
    INPUT B = 20
    C = A + B
    OUTPUT C
    STOP
  • Flowchart: A visual representation using boxes for operations, diamonds for decisions, and arrows for flow. The start/stop are ovals, input/output are parallelograms, processing is a rectangle.

Looping Example: Print Numbers from A to B

  • Pseudocode:

    START
    INPUT A = 10
    INPUT B = 20
    WHILE A != B
        PRINT A
        A = A + 1
    STOP
  • Flowchart: Includes a decision diamond (e.g., "Is A equal to B?") with Yes/No branches. The loop continues until the condition is true.

Key Takeaway: Pseudocode is a high-level, human-readable description of an algorithm. Flowcharts provide a graphical representation using standardized symbols.


Machine Learning Overview

Machine learning is the ability for a machine to learn without being explicitly programmed for a particular task. It is a field where computers use massive amounts of data, apply algorithms, and train themselves to make predictions. The training process involves feeding data into the algorithm, allowing the machine to learn patterns and relationships on its own.

Three main types of machine learning:

  1. Supervised Learning

  2. Unsupervised Learning

  3. Reinforcement Learning


Supervised Learning

Supervised learning requires labeled data. The algorithm learns a mapping from input variables (XXX) to output variables (YYY). The goal is to approximate a mapping function so that when new input data (unseen) arrives, the model can predict the corresponding output.

  • Independent variable: The input (XXX) — the factor that influences the outcome.

  • Dependent variable: The output (YYY) — the result being predicted.

Example: Predicting whether a student passes an exam based on gender.

  • Independent variable: Gender (male/female)

  • Dependent variable: Outcome (pass/fail)

  • The model learns how the dependent variable changes with the independent variable.

Subtypes of Supervised Learning

Regression

Regression is used when the output variable is a continuous numeric value.

Example: Predicting the cost of an apple.

  • Inputs (influence factors): variety, ripeness, origin (e.g., Shimla, Washington, Kashmir)

  • Output: Price (a continuous number)

The model finds relationships between inputs and the output price.

Linear Regression

Linear regression assumes a linear relationship between dependent and independent variables. The graph is a straight line.

y=β0+β1x1+β2x2+⋯+βnxn+ϵy = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \dots + \beta_n x_n + \epsilony=β0​+β1​x1​+β2​x2​+⋯+βn​xn​+ϵ

Where yyy is the output, xix_ixi​ are inputs, βi\beta_iβi​ are coefficients, and ϵ\epsilonϵ is error.

Logistic Regression

Logistic regression is used when the dependent variable is categorical (usually binary: 0 or 1, yes or no). Despite the name, it is a classification technique.

Example: Predicting whether it will rain today.

  • Inputs: temperature, humidity, cloud cover

  • Output: binary — rain (1) or no rain (0)

The logistic regression model produces an S-shaped curve (sigmoid function) instead of a straight line. The sigmoid function maps any real-valued number to a value between 0 and 1, interpreted as a probability.

P(Y=1)=11+e−(β0+β1x1+⋯+βnxn)P(Y=1) = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x_1 + \dots + \beta_n x_n)}}P(Y=1)=1+e−(β0​+β1​x1​+⋯+βn​xn​)1​
  • Left graph (linear regression): straight line

  • Right graph (logistic regression): S-curve

Key Distinction: Linear regression outputs continuous values; logistic regression outputs probabilities for binary classification.

Classification

Classification predicts a categorical output — the algorithm assigns inputs to predefined classes.

Example: Identifying gender from facial features. The output variable is categorical (male/female), and the algorithm classifies the person based on features like beard, hair, etc.

Common algorithms: decision trees, support vector machines, k-nearest neighbors.


Unsupervised Learning

In unsupervised learning, the input data has no labels. The algorithm must find hidden structures or patterns on its own.

Example: A dataset containing images of fish and birds, but without any labels telling the machine which is which. An unsupervised algorithm can group the images into clusters: one cluster of fish, another of birds.

Clustering and K-Means Clustering

Clustering is the process of grouping similar data points together. The key requirement is:

  • High intra-cluster similarity: data points within the same cluster are very similar.

  • Low inter-cluster similarity: data points in different clusters are very different.

K-means clustering is the most simple and widely used clustering algorithm.

  • KKK stands for the number of clusters you want the algorithm to produce.

  • The algorithm assigns each data point to one of KKK clusters based on distance to the cluster's centroid (center).

Elbow Method is used to determine the optimal KKK value by plotting the within-cluster sum of squares (WCSS) against KKK and looking for an "elbow" point.

Definition: K-means clustering is an unsupervised algorithm that partitions nnn observations into kkk clusters, aiming to minimize the sum of squared distances between points and their assigned cluster centroid.


Reinforcement Learning

Reinforcement learning involves an agent that learns by interacting with an environment. The agent performs actions, observes the resulting state, and receives a reward (positive or negative). The goal is to maximize cumulative reward over time.

Example: Training a dog to shake hands

  • Agent: the dog

  • Action: giving a handshake

  • Reward: a biscuit (positive reinforcement)

  • If the dog performs the action correctly, it gets a reward; if not, no reward. The dog learns to repeat the rewarded behavior.

Example: Playing Pac-Man

  • Agent: the Pac-Man character

  • Environment: the 2D game space with dots, ghosts, and walls

  • Actions: move up, down, left, right

  • Rewards: eating dots (positive), touching a ghost (negative)

  • The agent learns the best actions by exploring and exploiting over many game plays.

Reinforcement Learning Cycle: Agent → Action → Environment → New State + Reward → Agent updates policy → Repeat.


Demo: K-Means Clustering (Python)

This demonstration uses Google Colab (a Jupyter notebook environment hosted on Google Cloud). The libraries used include:

  • numpy, pandas for data handling

  • matplotlib for visualization

  • scikit-learn for machine learning (specifically KMeans from sklearn.cluster)

Steps:

  1. Generate synthetic data using make_blobs from sklearn.datasets — 300 samples, 4 clusters.

  2. Use the Elbow Method (WCSS) to determine the optimal number of clusters.

  3. Apply K-means clustering with K=4K=4K=4.

  4. Visualize the clusters and mark the centroids (red dots).

The algorithm successfully groups the data into four distinct clusters and identifies the center of each cluster.


Demo: Logistic Regression for Heart Disease Prediction

This demo uses the Framingham Heart Study dataset (from Framingham, Massachusetts) to predict 10-year coronary heart disease (CHD) risk.

Steps:

  1. Import libraries: pandas, numpy, matplotlib, seaborn, scikit-learn.

  2. Load the dataset (CSV file upload to Colab).

  3. Explore the data: columns include male (binary), age, current smoker, cigarettes per day, prevalent stroke, diabetes, total cholesterol, systolic blood pressure, diastolic blood pressure, BMI, heart rate, glucose, and TenYearCHD (dependent binary variable).

  4. Handle missing values by dropping rows (about 12% of data — acceptable loss).

  5. Perform Exploratory Data Analysis (EDA): plot histograms and pair plots to understand distributions and relationships.

  6. Use logistic regression from statsmodels or sklearn.linear_model to build the model. The dependent variable is TenYearCHD.

  7. Perform backward elimination (selecting statistically significant features based on p-values) to refine the model.

  8. Output regression summary including odds ratios, confidence intervals, and p-values.

  9. Split data into training (e.g., 70%) and testing (30%) sets.

  10. Evaluate model performance: accuracy ~88.14%, with additional metrics:

    • True Positive Rate: ~4%

      • True Negative Rate: ~99%

      • Positive Predictive Value: ~80%

      • Negative Predictive Value: ~88%

      • Misclassification rate: ~11.86%

The model is able to predict heart disease risk with good accuracy, demonstrating how machine learning can aid in medical diagnostics.

Key Insight: Logistic regression is particularly suited for binary classification problems like disease prediction, where the outcome is a yes/no question.


Summary of Key Concepts

  • Algorithm: A set of step-by-step rules for solving a problem.

  • Supervised Learning: Learns from labeled data to map inputs to outputs.

  • Unsupervised Learning: Finds hidden patterns in unlabeled data.

  • Reinforcement Learning: Agent learns through trial and error with rewards.

  • Regression (Linear/Logistic): Predicts continuous or binary outcomes.

  • Classification: Assigns inputs to discrete categories.

  • Clustering (K-means): Groups similar data points without labels.

  • Centroid: The center point of a cluster in k-means.

  • Sigmoid Function: Used in logistic regression to output probabilities.

  • Elbow Method: Technique to choose the optimal number of clusters.

Machine learning algorithms are powerful tools for extracting insights from data, enabling automated decision-making across industries — from recommendation systems to healthcare diagnostics.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent