BIT252 Artificial Intelligence

Artificial IntelligenceUnit 516 min read

Machine Learning Basics: Models, Algorithms, and Real-World Impact

Unit 5 of Artificial Intelligence covers the core principles of machine learning—supervised/unsupervised learning, neural networks, backpropagation, and reinforcement learning—with real-world examples from Nepalese apps (eSewa, Daraz) and global tech (Google, WhatsApp). You’ll learn mathematical models of neurons, lear

TAKEAWAYS:

  • Machine learning is a subset of AI where systems learn from data (labeled or unlabeled) to improve performance without explicit programming.
  • Supervised learning uses labeled data (e.g., spam emails) to train models like decision trees or neural networks, while unsupervised learning finds hidden patterns (e.g., customer segmentation).
  • A neuron’s mathematical model is , where is an activation function (e.g., sigmoid, ReLU), and learning adjusts weights via backpropagation to minimize error.
  • Reinforcement learning (RL) uses rewards/punishments (e.g., Pathao’s delivery routing) to train agents via Q-learning or policy gradients.
  • Overfitting (memorizing training data) vs. underfitting (ignoring patterns) are key pitfalls; techniques like cross-validation or regularization help balance them.
  • Real-world applications include fraud detection (Khalti’s transaction monitoring), recommendation systems (Daraz’s product suggestions), and autonomous navigation (NTC’s traffic signal optimization).

1. What Is Machine Learning?

Machine learning (ML) is a data-driven approach where algorithms learn patterns from examples (data) to make predictions or decisions. Unlike traditional programming, ML models improve with experience (more data).

Types of Machine Learning

mindmap
  root((Machine Learning))
    Supervised Learning
      "Labeled Data (Input → Output)"
      Examples: Spam detection, House price prediction
    Unsupervised Learning
      "Unlabeled Data (Find Hidden Patterns)"
      Examples: Customer segmentation, Anomaly detection
    Reinforcement Learning
      "Learn by Rewards/Punishments"
      Examples: Game AI (AlphaGo), Robotics

Key Definitions

  • Feature: Input variable (e.g., age, income in a loan approval model).
  • Label: Output variable (e.g., "approved" or "rejected" for a loan).
  • Hypothesis: A function that maps inputs to outputs (e.g., ).
  • Loss Function: Measures how wrong the model’s prediction is (e.g., Mean Squared Error for regression).

2. Supervised Learning: Learning from Labeled Data

Supervised learning trains models on input-output pairs (e.g., emails labeled "spam" or "not spam").

-5-4-3-2-112345-112345xyDecision Boundary (Linear SVM)Class AClass B
Linear SVM decision boundary for binary classification

How It Works

  1. Training: The model learns from labeled data (e.g., 1000 emails with spam labels).
  2. Prediction: The model predicts labels for new, unseen data (e.g., a new email).
  3. Evaluation: Metrics like accuracy, precision, or F1-score measure performance.

Example: Loan Approval (Nepalese Bank Scenario)

Problem: A bank wants to predict whether a customer will repay a loan. Data:

Age Income (₹) Loan_Status (Label)
25 30,000 Approved
40 80,000 Approved
30 20,000 Rejected

Model: A decision tree (or logistic regression) learns rules like:

  • If Income > 50,000 → Approved
  • Else if Age > 35 → Approved
  • Else → Rejected

Visual: Decision Tree for Loan Approval

Income > 50,000?ApprovedAge > 35?Rejected
Decision tree for loan approval (Nepalese bank scenario)

Common Algorithms

Algorithm Use Case Example in Nepal
Linear Regression Predicting continuous values Predicting Daraz product prices
Logistic Regression Binary classification (yes/no) Khalti fraud detection
Decision Trees Rule-based classification NTC traffic signal optimization
Support Vector Machines (SVM) High-dimensional data NEPSE stock trend analysis

3. Unsupervised Learning: Finding Hidden Patterns

Unsupervised learning works with unlabeled data to discover structures (e.g., grouping similar customers).

Key Techniques

  1. Clustering: Groups similar data points (e.g., K-Means).
    • Example: Daraz groups customers by purchasing behavior to target ads.
  2. Dimensionality Reduction: Simplifies data (e.g., PCA for image compression).
  3. Association Rule Learning: Finds relationships (e.g., "Customers who buy X also buy Y").

Example: Customer Segmentation (eSewa Users)

Data: Transaction history of eSewa users (unlabeled). Goal: Group users by spending habits.

Algorithm: K-Means Clustering (K=3 groups):

  1. Randomly assign 3 centroids (Group 1, 2, 3).
  2. Assign each user to the nearest centroid.
  3. Recalculate centroids until groups stabilize.

Result:

  • Group 1: High spenders (₹50,000+/year).
  • Group 2: Moderate spenders (₹20,000–₹50,000).
  • Group 3: Low spenders (<₹20,000).

Visual: K-Means Clustering


4. Neural Networks: The Brain of ML

Neural networks mimic the human brain’s structure: layers of interconnected nodes (neurons).

Mathematical Model of a Neuron

A single neuron’s output:

  • : Input features (e.g., pixel values in an image).
  • : Weights (learned parameters).
  • : Bias (adjusts the activation threshold).
  • : Activation function (e.g., sigmoid, ReLU).

Activation Functions

Function Output Range Use Case
Sigmoid (0, 1) Binary classification (e.g., spam)
ReLU Hidden layers (speeds up training)
Tanh (-1, 1) Normalized outputs

Example: Handwritten Digit Recognition (MNIST Dataset)

Problem: Classify digits (0–9) from grayscale images (28×28 pixels). Network Architecture:

Input Layer (784 neurons) → Hidden Layer (128 neurons, ReLU) → Output Layer (10 neurons, Softmax)

Softmax Output: Probabilities for each digit (e.g., 95% "5", 5% "3").

Visual: Neural Network for MNIST

28x28 ImageReLU → SoftmaxInput Layer (784)Hidden Layer (128)Output Layer (10)
Neural network architecture for MNIST digit recognition (simplified)

Backpropagation: How Neurons Learn

  1. Forward Pass: Compute output and loss (e.g., cross-entropy loss).
  2. Backward Pass: Adjust weights using the chain rule to minimize loss.
    • Learning Rate (): Step size for weight updates (e.g., ).
    • Gradient Descent: .

Example: Training a Neuron for OR Gate

Input (x₁, x₂) Output (y) Target (t) Loss (MSE) Updated
(0, 0) 0.1 0 0.01 -0.2 0.98
(0, 1) 0.6 1 0.16 0.8 1.82
(1, 0) 0.6 1 0.16 0.8 2.66
(1, 1) 0.9 1 0.01 0.2 2.88

5. Reinforcement Learning: Learning by Trial and Error

RL trains agents to make sequential decisions by rewarding good actions and punishing bad ones.

022.54567.590Episode 110Episode 1050Episode 10090Reward Score
RL learning curve: cumulative rewards over training episodes

Key Components

  • Agent: The learner (e.g., a robot, AI in a game).
  • Environment: The world the agent interacts with (e.g., a chessboard).
  • State: Current situation (e.g., "rook at (a1)").
  • Action: Possible moves (e.g., "move rook to (a2)").
  • Reward: Feedback (e.g., +10 for checkmate, -1 for losing a piece).

Example: Pathao Delivery Routing

Problem: Find the fastest route for a delivery. RL Approach:

  1. State: Current location, traffic data, delivery time.
  2. Action: Turn left/right or continue straight.
  3. Reward: -1 per minute delayed, +100 for successful delivery.

Algorithm: Q-Learning

  • Q-Table: Stores expected rewards for state-action pairs.
  • Update Rule:
    • : Learning rate.
    • : Discount factor (future rewards matter less).

Visual: Q-Learning for Pathao

startTurn LeftWaitGo StraightHomeTraffic Light RedTraffic Light GreenDestination
Q-Learning state transitions for Pathao delivery routing

6. Challenges in Machine Learning

Challenge Cause Solution
Overfitting Model memorizes training data Use validation sets, regularization
Underfitting Model too simple Add features, use complex models
High Variance Sensitive to data changes Cross-validation, ensemble methods
Bias-Variance Tradeoff Balance between under/overfitting Regularization, early stopping

Example: Overfitting in Daraz’s Recommendation System

  • Problem: Model predicts exact past purchases perfectly but fails on new users.
  • Solution: Use dropout (randomly deactivate neurons during training) or L2 regularization.

In the Real World

  1. eSewa’s Fraud Detection

    • Idea: Supervised learning (logistic regression) flags suspicious transactions.
    • How: Trained on labeled data (fraudulent vs. legitimate payments). Uses features like transaction amount, time, and user history.
    • Impact: Reduces false positives (legitimate transactions blocked) and false negatives (fraud missed).
  2. Pathao’s Dynamic Pricing

    • Idea: Reinforcement learning adjusts fares based on demand and driver availability.
    • How: The agent (Pathao’s algorithm) learns to maximize driver earnings and rider satisfaction by tweaking prices in real-time.
    • Example: During peak hours, fares increase by 20% to incentivize more drivers.
  3. NTC’s Traffic Signal Optimization

    • Idea: Unsupervised learning (clustering) groups similar traffic patterns.
    • How: Sensors collect data on vehicle flow at intersections. K-Means clusters identify high-congestion times, and signals adjust dynamically.
    • Result: Reduces wait times by 15% in Kathmandu’s busy areas.
  4. Google’s Search Ranking

    • Idea: Neural networks (Transformers) process user queries and rank results.
    • How: BERT (Bidirectional Encoder Representations from Transformers) understands context (e.g., "bank" as a financial institution vs. a river).
    • Nepalese Tie: Used by Google Nepal to rank local businesses like restaurants or tailors.
  5. WhatsApp’s Spam Filter

    • Idea: Supervised learning (Naive Bayes classifier) labels messages as spam.
    • How: Trained on millions of messages marked "spam" or "not spam." Features include keywords (e.g., "free offer"), sender reputation, and message frequency.

7. Worked Example: Predicting House Prices (Linear Regression)

Problem: Predict house prices in Lalitpur based on area (sq. ft.) and number of bedrooms.

Data:

Area (sq. ft.) Bedrooms Price (₹ lakhs)
1000 2 15
1500 3 25
2000 2 30

Model: Linear regression .

Steps:

  1. Normalize Data: Scale features to [0, 1].
    • Area:
    • Bedrooms:
  2. Compute Weights (using gradient descent):
    • Initialize , , .
    • Update rule: .
  3. After 100 iterations:
    • , , .
    • Equation: .

Prediction: For a 1200 sq. ft. house with 2 bedrooms:

Visual: Linear Regression Fit

50010001500200025005101520253035xyActual Prices (₹ lakhs)Predicted: Price = 12×Area + 10 + 2
Linear regression fit for house price prediction (simplified)

8. Exam Tip: How to Score Full Marks

  1. Define Clearly: Always start with precise definitions (e.g., "Machine learning is a subset of AI where systems learn from data...").
  2. Use Math Where Needed: For neuron models or backpropagation, show equations step-by-step.
  3. Compare Algorithms: Use tables to contrast supervised vs. unsupervised learning or linear regression vs. decision trees.
  4. Real-World Links: Tie examples to Nepalese contexts (e.g., Khalti’s fraud detection, Daraz’s recommendations).
  5. Diagrams > Words: Draw neural networks, decision trees, or Q-tables to visualize concepts.
  6. Common Pitfalls:
    • Don’t confuse learning rate () with epochs (training iterations).
    • Clarify overfitting (model too complex) vs. underfitting (model too simple).
  7. Past Exam Patterns:
    • Short Questions: Define terms like "backpropagation" or "reinforcement learning."
    • Long Questions: Explain algorithms (e.g., K-Means) with a step-by-step example.
    • Applications: Always link to real-world systems (e.g., "How would you use supervised learning in eSewa?").

9. Practice Questions (Based on Past Exams)

  1. Describe learning by analogy with an example.

    • Answer: Learning by analogy transfers knowledge from a known domain to a new one. Example: If a model learns to detect cats in images, it can apply similar features (whiskers, ears) to detect lions by analogy.
  2. Express the mathematical model of a neuron and explain backpropagation.

    • Answer:
      • Neuron: .
      • Backpropagation: Adjusts weights using the chain rule to minimize loss via gradient descent.
  3. How does reinforcement learning use rewards and punishments? Give an example.

    • Answer: RL uses rewards to encourage desired actions and punishments to discourage bad ones. Example: In Pathao, a successful delivery (+100 reward) reinforces the route-taking action, while delays (-1 per minute) penalize inefficient paths.
  4. What is the role of the learning rate in gradient descent?

    • Answer: The learning rate () controls the step size during weight updates. A high may overshoot minima; a low slows convergence. Typical values: 0.001–0.1.

10. Summary Table: ML Paradigms Compared

Feature Supervised Learning Unsupervised Learning Reinforcement Learning
Data Type Labeled (Input → Output) Unlabeled Sequential interactions
Goal Predict labels Find hidden patterns Maximize cumulative reward
Algorithms Regression, SVM, Decision Trees K-Means, PCA, Clustering Q-Learning, Policy Gradients
Example in Nepal Khalti fraud detection Daraz customer segmentation Pathao delivery routing
Key Challenge Overfitting Interpreting clusters Exploring large state spaces

Based on the TU BIT syllabus for Artificial Intelligence (BIT252), unit 5.

Discussion

Loading…