Gen AI Classroom Notes – 11/02/2025

A small story

In a small town in India, Ramesh owned a famous sweet shop known for its delicious Mysore Pak. His secret recipe, passed down through generations, was known only to him, and he guarded it fiercely. It was quite literally his “secret ingredient,” and no one else understood the exact process of making it.

To maintain the quality, Ramesh employed a worker for each step of the Mysore Pak-making process. These workers were treated like mere machines, as Ramesh feared they might steal his recipe. He never explained why they had to follow his instructions a certain way—only how to do it. However, the workers didn’t mind much because he paid them well, and they often joked about his paranoia behind his back.

Ramesh’s recipe is an algorithm—a precise set of instructions to produce Mysore Pak. The written instructions he gives to his workers act as a program, which embodies the algorithm in a way they can follow step by step. In this way, Ramesh has “programmed” his workers (the machine) to implement his algorithm to produce Mysore Pak.

There are a few key lessons in this story:

  1. Ramesh may be an excellent cook, but he treats people like machines.
  2. His workers do not need to understand why they are following the steps; they only execute the instructions.
  3. Only Ramesh, the “programmer,” understands why these steps are necessary.
preview

This is precisely how computers have been controlled since the early days, dating back to the theoretical machines envisioned by Alan Turing in the 1930s and even earlier to Charles Babbage’s Analytical Engine of the 19th century. A human designs an algorithm, converts it into a sequence of instructions (a program), and the machine executes it without understanding its purpose. It simply follows the commands it has been given.

The brilliance of Babbage and Turing was in realizing that a general-purpose machine could execute any algorithm through programs. But it was Ada Lovelace, a close associate of Babbage and widely regarded as the first computer programmer, who foresaw the boundless potential of what we now call a computer.

Loan EMI Calculator

Real-World Problem: Loan EMI Calculation

Scenario:
You take a loan from a bank, and you need to calculate the monthly EMI (Equated Monthly Installment) that you must pay. The EMI depends on:

  • Loan Amount (P)
  • Annual Interest Rate (R)
  • Loan Tenure in Months (N)

The formula to calculate EMI is:

[
EMI = \frac{P \times r \times (1 + r)^N}{(1 + r)^N – 1}
]

Where:

  • ( P ) = Loan Amount
  • ( r ) = Monthly Interest Rate (Annual Rate / 12 / 100)
  • ( N ) = Loan Tenure (in months)

Step-by-Step Approach

  1. Take input: Loan amount, interest rate, and tenure.
  2. Convert annual interest rate to monthly.
  3. Apply EMI formula to compute the monthly installment.
  4. Display the result to the user.

Python Program: Loan EMI Calculator

def calculate_emi(loan_amount, annual_interest_rate, loan_tenure_months):
    """
    Step 1: Convert annual interest rate to monthly interest rate.
    Step 2: Apply the EMI formula.
    Step 3: Return the EMI amount.
    """
    monthly_interest_rate = (annual_interest_rate / 100) / 12  # Convert to decimal
    if monthly_interest_rate == 0:  # If interest rate is 0%, simple division
        return loan_amount / loan_tenure_months

    emi = (loan_amount * monthly_interest_rate * (1 + monthly_interest_rate) ** loan_tenure_months) / \
          ((1 + monthly_interest_rate) ** loan_tenure_months - 1)

    return emi

# Taking input from user
loan_amount = float(input("Enter loan amount (₹): "))
annual_interest_rate = float(input("Enter annual interest rate (%): "))
loan_tenure_years = int(input("Enter loan tenure (years): "))

# Convert years to months
loan_tenure_months = loan_tenure_years * 12

# Calculate EMI
emi = calculate_emi(loan_amount, annual_interest_rate, loan_tenure_months)

# Display the result
print(f"\nYour Monthly EMI for ₹{loan_amount} loan at {annual_interest_rate}% for {loan_tenure_years} years is: ₹{emi:.2f} per month")

Example Output

Enter loan amount (₹): 500000
Enter annual interest rate (%): 7.5
Enter loan tenure (years): 10

Your Monthly EMI for ₹500000 loan at 7.5% for 10 years is: ₹5929.88 per month

Artificial Intelligence

Artificial Intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think, learn, and solve problems. AI encompasses various subfields, including:

  • Machine Learning (ML): Algorithms that learn from data and improve their performance.
  • Deep Learning (DL): Neural networks that mimic the human brain to process large amounts of data.
  • Generative AI: AI models capable of generating new content, such as text, images, and music.

Machine Learning

  • Machine learning builds models from data. model is an abstraction notion of something that accepts inputs and generates outputs.
  • Data is everything in AI. Models are blank slates that data must condition to make them suitable for a task. If the data is bad, the model is bad.
  • Lets findout Who is responsible for the good data
    The job roles responsible for determining whether data is good or bad in AI and machine learning include:

Job roles – Helping with Good and bad data

  1. Data Scientist
    Key Responsibility: Analyzes datasets, cleans data, and ensures that it is high-quality before training models.
    How They Check Data: Uses statistics, visualization tools (Matplotlib, Seaborn), and feature engineering to detect issues like missing values, outliers, and biases.
  2. Data Engineer
    Key Responsibility: Builds pipelines to collect, store, and preprocess data.
    How They Check Data: Ensures data consistency, integrity, and scalability while handling large datasets in distributed systems (Hadoop, Spark, Airflow).
  3. Machine Learning Engineer
    Key Responsibility: Implements and optimizes models based on cleaned and preprocessed data.
    How They Check Data: Monitors feature importance, model drift, and fairness while training AI models.
  4. Data Analyst
    Key Responsibility: Explores data for patterns and business insights.
    How They Check Data: Uses SQL, Pandas, and BI tools (Tableau, Power BI) to identify incorrect or misleading data.
  5. AI/ML Researcher
    Key Responsibility: Investigates new ways to enhance model performance.
    How They Check Data: Experiments with data augmentation, synthetic data generation, and domain adaptation.
  6. Ethical AI Specialist / Responsible AI Engineer
    Key Responsibility: Ensures AI models are fair, unbiased, and explainable.
    How They Check Data: Uses bias detection tools (Fairlearn, SHAP, LIME) to detect and mitigate bias in AI datasets.
  7. Data Governance / Compliance Officer
    Key Responsibility: Ensures data complies with privacy laws (GDPR, CCPA) and security policies.
    How They Check Data: Implements data protection, anonymization, and governance practices.

Okay we have good data what’s next

  • A model has parameters, which determine how it generates outputs. Training a model involves adjusting these parameters so that it learns to produce the correct output for a given input.
  • For training to be effective, we need a dataset that includes both inputs and their corresponding expected outputs.
  • At first glance, this might seem redundant—why teach the model to produce results we already know? The key reason is that once trained, the model will encounter new inputs for which we don’t have predefined answers.
  • This is precisely why we build models: to make reliable predictions on unknown inputs, trusting that the model will generate accurate outputs.
  • In training, we use data to teach the model to adjust its parameters to produce correct output. There is no programming because, most of the time, we have no idea what the algorithm should be. We only know or believe a relationship exists between the inputs and the desired outputs. We hope a model can approximate that relationship well enough to be useful.
preview

Lets understand this with an example

Problem Statement

Let’s predict the salary of an employee based on their years of experience using Linear Regression.


Step 1: Install Dependencies

If you haven’t installed numpy, matplotlib, and scikit-learn, install them using:

pip install numpy matplotlib scikit-learn

Step 2: Import Libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

Step 3: Sample Data (Years of Experience vs Salary)
# Sample data (Years of Experience vs Salary in ₹)
X = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).reshape(-1, 1)  # Feature (Years of Experience)
y = np.array([30000, 35000, 40000, 45000, 50000, 55000, 60000, 65000, 70000, 75000])  # Target (Salary in ₹)

Step 4: Split Data into Training & Testing Sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Step 5: Train the Linear Regression Model
model = LinearRegression()
model.fit(X_train, y_train)

Step 6: Make Predictions
y_pred = model.predict(X_test)

Step 7: Evaluate Model Performance
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse:.2f}")

print(f"Model Coefficient (Slope): {model.coef_[0]:.2f}")
print(f"Model Intercept: {model.intercept_:.2f}")

Step 8: Visualize the Regression Line
plt.scatter(X, y, color='blue', label="Actual Data")
plt.plot(X, model.predict(X), color='red', label="Regression Line")
plt.xlabel("Years of Experience")
plt.ylabel("Salary (₹)")
plt.title("Simple Linear Regression - Salary Prediction")
plt.legend()
plt.show()

Example Output
Mean Squared Error: 6250000.00
Model Coefficient (Slope): 5000.00
Model Intercept: 25000.00

The red line in the plot represents the predicted salaries based on the model.


Understanding the Model
  • The model learns the relationship between Years of Experience (X) and Salary (y).
  • The equation of the fitted line is:
    [
    Salary = 5000 \times (Years of Experience) + 25000
    ]
  • The coefficient (5000) means that for every extra year of experience, the salary increases by ₹5000.
  • The intercept (₹25000) suggests that even with 0 years of experience, the base salary is ₹25000.
alt text

More about Models

  • Models often want numeric class labels, which tells us that models don’t know what their inputs and outputs mean; they only make associations between sets of inputs and outputs. Models don’t “think” using any commonly accepted definition of the word.
  • Artificial intelligence makes frequent use of vectors and matrices (singular “matrix”).
Understanding Vectors and Matrices in AI (Simple Explanation)

In AI and Machine Learning, vectors and matrices are the basic building blocks of how computers store, process, and learn from data. Let’s break it down with real-world examples


1️⃣ What is a Vector?

A vector is just a list of numbers (an ordered sequence). It represents data points in a structured way.

Example: Student’s Exam Scores

Imagine you are a student, and you take three exams:

  • Math: 80
  • Science: 85
  • English: 90

We can represent these scores as a vector:

[
\mathbf{v} = \begin{bmatrix} 80 \ 85 \ 90 \end{bmatrix}
]

➡️ Meaning in AI:

  • A vector is like a single row or single column of data.
  • In AI, each data point (like a house’s price, a car’s speed, or an image pixel) is stored as a vector.
Example: Vectors in AI
  • Images are represented as vectors of pixel values.
  • Text processing uses word vectors to understand meaning.
  • Neural networks take input as vectors to learn patterns.

2️⃣ What is a Matrix?

A matrix is just a table of numbers (like a spreadsheet). It’s a collection of multiple vectors.

Example: Exam Scores of Multiple Students

If we have 3 students taking the same 3 exams:

[
\mathbf{M} =
\begin{bmatrix}
80 & 85 & 90 \
70 & 75 & 80 \
60 & 65 & 70
\end{bmatrix}
]

Each row is a student, and each column is a subject.

➡️ Meaning in AI:

  • A matrix stores multiple data points together.
  • In AI, we store entire datasets as matrices.
Example: Matrices in AI
  • Images are stored as matrices (rows = height, columns = width).
  • Neural networks use matrices to store weights and perform calculations.
  • Recommendation systems use matrices to track user preferences.

3️⃣ Why Vectors and Matrices Matter in AI?

AI models store and process everything using vectors and matrices:

  • Neural networks: Use matrices of weights to learn patterns.
  • Computer vision: Images are stored as pixel matrices.
  • Natural language processing: Words are represented as word vectors.

4️⃣ Summary
ConceptDefinitionReal-World Example
VectorA single list of numbersA student’s exam scores
MatrixA table of numbers (multiple vectors)A class’s exam scores

Think of vectors as individual data points and matrices as datasets!

Leave a Reply

Discover more from Direct AI Powered By Quality Thought

Subscribe now to keep reading and get access to the full archive.

Continue reading