Python Basics for Generative AI
Python Basics for Generative AI
It has a vast ecosystem of libraries for AI and machine learning (e.g., NumPy,
Pandas, scikit-learn, TensorFlow, PyTorch).
Python is widely used in industry and academia for data science, AI, and
automation due to its flexibility and strong community support
Installing Python
Most computers do not come with Python pre-installed, but installation is
straightforward:
During installation, ensure you check the box to "Add Python to PATH" for
easy access from the command line
Jupyter Notebook:
A web-based tool for writing and running Python code in “cells.” Great for
experimentation and data analysis.
Google Colab:
print("Hello, World!")
Hello, World!
In Jupyter or Colab, enter the code in a cell and press Shift+Enter to run it
Python Syntax
Python uses indentation (spaces or tabs) to define code blocks.
Variables
Variables store data values. You do not need to declare their type.
Data Types
String: Text, e.g., "Hello"
greeting = "Hi"
year = 2025
pi = 3.1415
is_student = True
print("Welcome to Python!")
a = 10
b=3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
Practice Exercise
Write a script that:
Adds them,
Basic if Statement
Executes a block if the condition is True :
x = 10
if x > 5:
print("x is greater than 5")
if-else Statement
Executes one block if the condition is True , another if False :
if-elif-else Statement
Checks multiple conditions in sequence:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C")
Nested if Statements
You can nest if statements inside each other for complex logic.
For Loop
Used for iterating over a sequence (list, tuple, string, etc.):
Use Cases:
While Loop
Executes as long as a condition is True :
i=1
while i < 6:
print(i)
i += 1
Use Cases:
Running until a specific event occurs (e.g., guessing games, event loops)
continue : Skip the current iteration and continue with the next.
else : Optional; runs if the loop completes normally (not via break ).
Example:
for i in range(5):
if i == 3:
break
print(i)
The else block will not execute if the loop is exited with break
1. Lists
Definition: Ordered, mutable collection. Allows duplicates.
Basic Operations:
Add: my_list.append(4)
Remove: my_list.remove(2)
Iterate:
pythonfor item in my_list:
print(item)
2. Tuples
Definition: Ordered, immutable collection. Allows duplicates.
Basic Operations:
Access: my_tuple[1]
Count: my_tuple.count(2)
Index: my_tuple.index(3)
3. Sets
Definition: Unordered, mutable collection of unique elements.
Basic Operations:
Add: my_set.add(4)
Remove: my_set.remove(2)
Membership: 2 in my_set
Iterate:
4. Dictionaries
Definition: Unordered (ordered as of Python 3.7+), mutable collection of key-
value pairs.
Basic Operations:
Add/Update: my_dict['c'] = 3
Remove: my_dict.pop('b')
Access: my_dict['a']
Comparison Table
Feature List Tuple Set Dictionary
def greet():
print("Hello, World!")
greet() # Output: Hello, World!
Purpose:
Functions help organize code, promote reuse, and improve readability
Arguments:
Values passed to the function when it is called.
Types of Parameters:
3. Return Values
Returning Values:
Use the return statement to send a result back to the caller. If no return is
specified, the function returns None by default.
def square(x):
return x * x
result = square(4) # result is 16
def stats(numbers):
return min(numbers), max(numbers)
mn, mx = stats([1, 2, 3])
# mn = 1, mx = 3
Functions can return any object, including lists, dictionaries, or even other
functions456.
4. Scope in Python
Local Scope:
Variables defined inside a function are local and accessible only within that
function.
def foo():
x = 10 # local to foo
print(x)
Global Scope:
Variables defined outside any function are global and accessible throughout
the file.
x = 20
def bar():
print(x) # accesses global x
bar()
Nonlocal Scope:
Used in nested functions to refer to variables in the enclosing function.
def outer():
x = "outer"
def inner():
nonlocal x
x = "inner"
inner()
print(x) # Output: inner
outer()
Variable Shadowing:
If a variable with the same name exists in both local and global scope, the
local variable takes precedence inside the function
import math
Standard Libraries:
Python comes with a rich set of standard modules, such as math , random ,
datetime , os , and sys .
Custom Modules:
You can create your own modules by saving functions in a .py file and
importing them
Reading Files:
Writing Files:
Best Practice:
Use with statement to automatically close files
Mode Description
String Operations
Common String Methods:
Formatting Strings:
Sample Code:
count_words('[Link]', 'word_count.txt')
Commonly used for: data analysis, scientific computing, and as the base for
other libraries like Pandas and SciPy.
From lists:
import numpy as np
a = [Link]([1, 2, 3, 4, 5, 6])
Multi-dimensional arrays:
print(a[0]) # 1
Slicing:
c. Basic Operations
Element-wise operations:
Aggregations:
a = [Link]([1, 2, 3, 4])
print([Link]()) # 10
b = [Link]([[1, 1], [2, 2]])
print([Link](axis=0)) # array([3, 3]) # sum over rows
print([Link](axis=1)) # array([2, 4]) # sum over columns
arr = [Link]([
[1, 2, 3],
[4, 5, 6]
])
11
22
Reshaping:
What is Pandas?
Pandas is a Python library built on top of NumPy, designed for data
manipulation and analysis.
From a dictionary:
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = [Link](data)
b. Accessing Data
Select a column:
print(df['Name'])
Slicing rows:
Filter rows:
Drop a column:
df = [Link]('Salary', axis=1)
[Link]()
[Link](0)
[Link]()
Aggregation:
df['Age'].mean()
[Link]('Name').sum()
Sorting:
Handle the missing data {'A': [1, 2, [Link]], 'B': [5, [Link], [Link]]}
Why it matters: Clean data leads to more accurate analysis and insights.
Messy data can cause errors, misleading results, or make analysis impossible.
Example:
import pandas as pd
Data Filtering
Definition: Filtering means selecting rows that meet certain conditions,
helping you focus on relevant data
Example:
Data Sorting
Definition: Sorting arranges your data by the values in one or more columns,
making it easier to spot patterns or outliers35.
Example:
2. Clean the data (remove duplicates, fix names, handle missing values).
3. Filter the data (e.g., select students with high scores, products with sales
above a threshold).
5. Draw simple conclusions (e.g., who has the highest score? How many
products sold more than 10 units?).
Example:
import pandas as pd
# 1. Load data
data = {
'Student': ['Alice', 'Bob', 'Alice', 'Charlie', 'David'],
'Score': [85, 90, 85, None, 75]
# 2. Clean data
df = df.drop_duplicates()
df['Score'] = df['Score'].fillna(df['Score'].mean())
In-Class Activity
Give students a small CSV or dictionary-based dataset.
Remove duplicates
Python’s most popular libraries for visualization are Matplotlib and Seaborn
2. Introduction to Matplotlib
Matplotlib is a foundational plotting library in Python, offering flexibility to
create a wide variety of static, animated, and interactive plots
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
[Link](x, y)
[Link]('Simple Line Plot')
[Link]('X Axis')
[Link]('Y Axis')
[Link]()
You can customize colors, line styles, and add titles/labels easily
Pie Chart:
Scatter Plot:
x = [1, 2, 3, 4, 5]
y = [5, 7, 4, 6, 5]
[Link](x, y)
[Link]("Scatter Plot Example")
[Link]("X Value")
[Link]("Y Value")
[Link]()
Introduction to Seaborn
Seaborn is built on top of Matplotlib and provides a higher-level, more user-
friendly interface for creating attractive statistical graphics
It works seamlessly with Pandas DataFrames and comes with better default
styles and color palettes
data = [1, 2, 2, 3, 3, 3, 4, 4, 5]
[Link](data)
[Link]("Histogram Example")
[Link]()
Scatter Plot:
tips = sns.load_dataset("tips")
[Link](x="total_bill", y="tip", data=tips)
[Link]("Total Bill vs Tip")
[Link]()
Line Plot:
fmri = sns.load_dataset("fmri")
[Link](x="timepoint", y="signal", data=fmri)
[Link]("FMRI Signal Over Time")
[Link]()
Seaborn: Simpler code for statistical plots, better default styles, and works
well for quick exploratory analysis
Hands-On Practice
Exercise Ideas:
Use Seaborn to plot a scatter plot from the built-in "tips" dataset.
The process involves feeding large amounts of data to algorithms, which then
optimize their internal parameters to minimize errors and make accurate
predictions or classifications
Supervised Learning
Definition: The algorithm is trained on labeled data, meaning each input
comes with a known output.
Goal: Learn a mapping from inputs to outputs so it can predict the output for
new, unseen data.
Use Cases: Email spam detection, image classification, credit scoring, medical
diagnosis
Unsupervised Learning
Definition: The algorithm is given data without explicit labels and must find
patterns or groupings on its own.
Reinforcement Learning
Definition: An agent learns to make decisions by interacting with an
environment, receiving rewards or penalties for actions.
2. Data Collection: Gather relevant and high-quality data from various sources.
6. Model Training: Fit the model to the training data, adjusting parameters to
minimize errors.
9. Deployment: Integrate the trained model into production systems for real-
world use.
What is Scikit-learn?
Scikit-learn (sklearn) is a popular open-source Python library for machine
learning.
It provides simple and efficient tools for data mining and data analysis,
supporting both supervised and unsupervised learning.
Scikit-learn is widely used in industry and academia due to its ease of use,
extensive documentation, and active community support.
Key Features
Ready-to-use algorithms for classification, regression, clustering, and more.
# Load dataset
iris = load_iris()
X, y = [Link], [Link]
4. Make Predictions
y_pred = [Link](X_test)
# Load dataset
boston = load_boston()
X, y = [Link], [Link]
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=
# Train model
reg = LinearRegression()
[Link](X_train, y_train)
Key Takeaways:
Machine learning enables systems to learn from data and make predictions.
Supervised and unsupervised learning are the two main types, each with
distinct use cases.
Mathematical Model:y=β0+β1x+ϵ
For simple linear regression (one predictor), the model is:
y=β0+β1x+ϵy = \beta_0 + \beta_1 x + \epsilon
where:
Goal:
Find β0\beta_0β0 and β1\beta_1β1 that minimize the sum of squared residuals
(differences between observed and predicted yyy) — this is called the
Ordinary Least Squares (OLS) method.
Example:
import numpy as np
x_mean = [Link](x)
y_mean = [Link](y)
y_pred = B0 + B1 * x
print(f"Slope: {B1}, Intercept: {B0}")
print("Predicted values:", y_pred)
b) Using Scikit-learn
Import LinearRegression from sklearn.linear_model .
Example:
model = LinearRegression()
[Link](X, y)
print("Intercept:", model.intercept_)
print("Coefficient:", model.coef_)
y_pred = [Link](X)
print("Predictions:", y_pred)
Example:
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
def predict(x):
return slope * x + intercept
[Link](x, y)
[Link](x, y_pred, color='red')
[Link]()
print(f"MSE: {mse}")
print(f"R-squared: {r2}")
Logistic Regression
Purpose:
Used for binary classification problems (output is categorical: 0 or 1).
Theory:σ(z)=1+e−z1
Instead of predicting continuous values, logistic regression predicts the
probability that an input belongs to a class using the logistic (sigmoid)
function:
σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}
where z=β0+β1x1+ ⋯+βpxpz = \beta_0 + \beta_1 x_1 + \cdots + \beta_p
x_pz=β0+β1x1+ ⋯+βpxp.
Output:
A probability between 0 and 1, which is thresholded (commonly at 0.5) to
assign class labels.
Use Cases:
Spam detection, disease diagnosis, customer churn prediction.
Decision Trees
Definition:
A tree-like model of decisions that splits data based on feature values to
classify or predict outcomes.
How it Works:
Advantages:
Easy to interpret, handles both numerical and categorical data, non-linear
relationships.
Limitations:
Can overfit, sensitive to small data changes.
# Load data
iris = load_iris()
X, y = [Link], [Link]
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=
# Train model
model = LogisticRegression()
[Link](X_train, y_train)
How It Works:
2. Expectation Step: Assign each data point to the nearest centroid based on
Euclidean distance.
Objective:
Challenges:
Elbow Method:
Plot SSE against different values of K to find the "elbow" point where adding
more clusters yields diminishing returns.
Benefits:
# Load dataset
data = load_iris()
X = [Link]
# Standardize features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Plot clusters
[Link](X_pca[:, 0], X_pca[:, 1], c=clusters, cmap='viridis')
[Link]('Principal Component 1')
[Link]('Principal Component 2')
[Link]('K-Means Clustering with PCA')
[Link]()
1. Accuracy
Proportion of correct predictions (both true positives and true negatives) over
total predictions.
2. Precision
3. Recall (Sensitivity)
Measures how many actual positives were correctly
[Link]=TP+FNTP
Recall=TPTP+FN\text{Recall} = \frac{TP}{TP + FN}
4. F1-Score
Harmonic mean of precision and recall, balancing
both.F1=2×Precision+RecallPrecision×Recall
F1=2×Precision×RecallPrecision+RecallF1 = 2 \times \frac{\text{Precision}
\times \text{Recall}}{\text{Precision} + \text{Recall}}
5. Confusion Matrix
6. Cross-Validation
Technique to assess model generalization by splitting data into multiple
train/test folds.
Activation Functions:
Introduce non-linearity; common types include:
ReLU (Rectified Linear Unit): Outputs zero for negative inputs, linear for
positive.
Layers:
Step-by-step example:
import tensorflow as tf
from [Link] import layers, models
# Load dataset
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# Preprocess data
X_train = X_train.reshape(-1, 28*28).astype('float32') / 255
X_test = X_test.reshape(-1, 28*28).astype('float32') / 255
# Build model
model = [Link]([
[Link](128, activation='relu', input_shape=(784,)),
[Link](64, activation='relu'),
[Link](10, activation='softmax')
])
# Compile model
[Link](optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train model
[Link](X_train, y_train, epochs=10, batch_size=32, validation_split=0.2)
# Evaluate model
test_loss, test_acc = [Link](X_test, y_test)
print(f"Test accuracy: {test_acc:.4f}")
Explanation:
Introduction to Generative AI
Key Difference:
Traditional AI is reactive and task-oriented, excelling at analyzing and predicting
within set boundaries. Generative AI is proactive, capable of producing new,
creative content by learning from existing data
Summary
Generative AI represents a shift from AI systems that simply analyze or classify
data to those that can create entirely new content, opening up new possibilities in
creativity, productivity, and problem-solving across industries
import openai
client = OpenAI(
response = [Link](
model="o4-mini",
instructions="You are a concise assistant.",
input="Explain the difference between a list and a tuple in Python.",
)
print(response.output_text)
4. Practice Exercise
Try generating:
Summary
Generative AI enables machines to create new content, setting it apart from
traditional, rule-based AI.
Stable Diffusion:
Example Workflow:
Retrieve the image URL from the response and display or download it.
Colab Notebooks:
Google Colab notebooks allow running Stable Diffusion without local setup,
with GPU acceleration available on Colab Pro.
These tools often allow prompt refinement, image upscaling, outpainting, and
blending modes for creative control.
GitHub Copilot
An AI-powered code completion tool integrated into code editors (e.g., VS
Code).
OpenAI Codex
The underlying model powering Copilot.
Practical Exercises
Exercise 1: Generate a function from a docstring prompt.
Prompt: "Write a Python function to check if a number is prime."
Expected output: Function code implementing prime check.
Best Practices
Always review generated code for correctness and security.
LLMs (like GPT, Gemini) are trained on vast but static datasets. Their
knowledge is frozen at training time and may be outdated or incomplete.
Example:
Ask ChatGPT: “Who won the 2024 Olympics?” (It can’t answer accurately
if trained before 2024.)
Discussion:
How it Works:
3. Generate: The LLM uses both its training and the fetched context to
answer the user’s query.
Diagram:
User Query → Retriever (search) → Relevant Docs → LLM (with docs as conte
Demo:
Hybrid Search: Combines both, often with a re-ranker for best results.
Vector Databases:
Multi-modal Retrieval:
Not just text—can retrieve images, audio, etc. using the same principles.
LlamaIndex:
Obtain API keys for your LLM provider (OpenAI, Gemini, etc.).
Use a few sample text files, PDFs, or URLs as your knowledge base.
qa = RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=db.as_retriever()
)
Optional:
Use LlamaIndex’s Data Connectors to pull in data from PDFs, SQL, APIs, etc..
Suggested Steps:
3. Connect to an LLM.
Challenge:
Try modifying the retriever (e.g., switch from keyword to semantic search).
Project Ideas:
1. AI Art Generator for Game Assets (Using Stable Diffusion)
Description: Build a simple app that generates game art assets (characters,
backgrounds, items) from text prompts using Stable Diffusion.
Skills: Prompt engineering, API integration or local model usage, image saving
and display.
Why: Great for learning image generation basics and creating usable assets
for your own game projects.
Reference: Many beginners start with Stable Diffusion v1.5 or SDXL models
and user-friendly UIs like Fooocus or InvokeAI
Why: Learn how to integrate powerful generative AI models into web apps and
handle asynchronous API responses.
Why: Learn code generation with LLMs and practical API usage for developer
tools.
Why: Explore generative AI for NLP and content creation, useful for blogs,
marketing, or education.
Tools: APIs for each model, React or Vue frontend, [Link] or Python
backend.
Tools: Stable Diffusion or DALL-E API, Pillow (Python imaging), Flask or React.
Tools: Stable Diffusion with control models, web frontend, backend API
integration.
Why: Practical use case for social apps or games, combining AI with user
inputs.
Logistic regression is primarily used for binary classification leveraging the logistic function to predict probabilities, making it suitable for interpretable linear decision boundaries. Decision trees create a tree-like model to make decisions by splitting data on feature values and can handle non-linear relationships. Each is preferred based on the problem’s complexity, with logistic regression used for simplicity and interpretability, and decision trees for more complex, non-linear relationships .
Generative AI like OpenAI Codex is transforming code generation and software development by allowing developers to produce code snippets, complete functions, or generate entire programs from natural language prompts. This accelerates development cycles, reduces boilerplate coding tasks, and aids in learning new API frameworks, thus enhancing productivity and creativity in software development .
Hyperparameter tuning involves optimizing the hyperparameters of learning algorithms to improve model performance significantly. It ensures that the model fits the data as well as possible without overfitting or underfitting, which is crucial for achieving optimal predictive accuracy .
Supervised learning requires labeled data, where each input comes with a known output, and the objective is to predict the output for new, unseen data by learning a mapping from inputs to outputs. Conversely, unsupervised learning operates on unlabeled data, aiming to discover hidden structures or relationships without explicit labels .
K-Means clustering aims to partition data into K distinct clusters based on feature similarity, commonly used for customer segmentation and anomaly detection. In contrast, PCA focuses on dimensionality reduction by identifying the principal components that capture the most variance in the data, typically applied for feature reduction and visualization .
Generative AI enables systems to learn from existing data and create new content, distinct from analysis or classification tasks. It has wide applications such as text generation for chatbots and content writing, image generation in artwork and style transfer, code generation, music composition, and personalized recommendations in various industries .
Reinforcement learning differs as it involves an agent making decisions within an environment to maximize cumulative rewards over time, contrasting with supervised learning’s focus on learning from labeled examples and unsupervised learning’s aim of finding patterns without labels. It finds applications in robotics, game playing, and autonomous vehicles, among others .
Model evaluation is a critical step in the machine learning workflow that assesses how well a model performs using metrics such as accuracy, precision, recall, and RMSE on validation or test data. This step ensures that the model's predictions are reliable and valid outside the training dataset, guiding necessary adjustments before deployment .
Text-to-image models like DALL-E use a CLIP model to map text and images into a shared semantic space, while Stable Diffusion creates images from random noise, refining them to match text prompts through a diffusion process. The key differences lie in their initialization techniques, with DALL-E using pre-trained models for semantic understanding and Stable Diffusion employing iterative denoising guided by text .
Matplotlib offers more control and customization, making it suitable for creating publication-quality graphics and unique plot types. Seaborn, on the other hand, provides simpler code for statistical plots and better default styles, which makes it more effective for quick exploratory data analysis .