0% found this document useful (0 votes)
8 views44 pages

23AD601 - Advance Python Lab Manual Updated

The document outlines the Master Lab Manual for the Advanced Python course under the Department of Artificial Intelligence and Data Science, detailing the institute's vision, mission, and educational objectives. It includes a comprehensive lab syllabus with a list of experiments designed to enhance students' programming skills, data manipulation, and machine learning techniques using Python. The manual also maps course outcomes to program outcomes and specific outcomes, emphasizing the integration of theoretical knowledge with practical applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views44 pages

23AD601 - Advance Python Lab Manual Updated

The document outlines the Master Lab Manual for the Advanced Python course under the Department of Artificial Intelligence and Data Science, detailing the institute's vision, mission, and educational objectives. It includes a comprehensive lab syllabus with a list of experiments designed to enhance students' programming skills, data manipulation, and machine learning techniques using Python. The manual also maps course outcomes to program outcomes and specific outcomes, emphasizing the integration of theoretical knowledge with practical applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

REGULATION 2023

23AD601 – ADVANCED PYTHON

MASTER LAB MANUAL


INDEX

Page
S/N. Content
Number

1. Institute Vision Mission 3

2. Department Vision, Mission, PEO’s, PO’s and PSO’s 4

3. Lab Syllabus 7

4. List of Experiments with COs, POs, and PSOs 9

5. Lab Experiments
1. Program using iterators, generators, and decorators in
10
Python.
2. Implement object-oriented concepts with inheritance,
14
polymorphism, and exception handling.
3. Perform data manipulation operations using NumPy and
17
Pandas.
4. Visualize data using Matplotlib and Seaborn libraries. 22
5. Implement classification and regression models using
27
Scikit-learn.
6. Apply clustering techniques using K-Means and evaluate
31
results.
7. Access and process data from web APIs using the requests
35
module.
8. Connect Python with a SQLite database and perform
38
CRUD operations.
9. Develop a simple data application using Flask or Streamlit
42
framework.

Page 2 of 44
INSTITUTE VISION

 To develop students with intellectual curiosity and technical expertise to meet the global needs.

INSTITUTE MISSION

 To achieve academic excellence by offering quality technical education using best teaching
techniques.
 To improve Industry – Institute interactions and expose industrial atmosphere.
 To develop interpersonal skills along with value based education in a dynamic learning

environment.
 To explore solutions for real time problems in the society.

Page 3 of 44
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

VISION
 To develop AI professionals of international relevance to meet the industry and
societal needs with future technologies.

MISSION
 To collaborate with industry and provide the state-of-the-art infrastructural facilities,
with a conducive teaching-learning ambience.
 To instill in the students the knowledge for world class technical competence,
entrepreneurial skill and a spirit of innovation in the area of Artificial Intelligence and
Data Science to solve real world problems.
 To encourage students to pursue higher education and research.
 To inculcate right attitude with discipline and develop industry ready professionals for
serving the society.
PROGRAM EDUCATIONAL OBJECTIVES
Graduates will be able to
 Utilize their proficiencies in the fundamental knowledge of basic sciences, mathematics,
Artificial Intelligence, data science, and statistics to build systems that require
management and analysis of large volumes of data.
 Advance their technical skills to pursue pioneering research in the field of AI and Data
Science and create disruptive and sustainable solutions for the welfare of ecosystems.
 Think logically, pursue lifelong learning and collaborate with an ethical attitude in a
Multidisciplinary team.
 Design and model AI-based solutions to critical problem domains in the real world.
 Exhibit innovative thoughts and creative ideas for an effective contribution towards the
economy building.

Page 4 of 44
PROGRAM OUTCOMES
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
PO3: Design / development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
PO4: Conduct investigations of complex problems: Use research based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the knowledge
of, and need for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.

Page 5 of 44
PO11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES


At the end of the program students will be able to

PSO 1: Develop and implement AI-based processes for effective decision-making in diverse
domains, including business and governance, by integrating domain-specific knowledge and
advanced techniques.

PSO 2: Utilize data analysis to derive actionable insights and foresights, enabling the
solution of complex business and engineering problems.

PSO 3: Apply theoretical knowledge of AI and Data Analytics, along with practical tools and
techniques, to address societal problems, demonstrating proficiency in data analytics,
visualization, and project coordination skills.

Page 6 of 44
Lab Syllabus

23AD601 ADVANCED PYTHON L T P C


2 0 2 3

Course Objectives

 To teach advanced Python programming features for writing efficient and modular
code.

 To enable students to handle, preprocess, and visualize data using Python libraries.

 To introduce machine learning techniques and model building using Python


frameworks.

 To develop skills in automation, API integration, web scraping, and database


connectivity.

 To guide students in creating, testing, and deploying complete Python applications.

List of Experiments

1. Program using iterators, generators, and decorators in Python.

2. Implement object-oriented concepts with inheritance, polymorphism, and exception


handling.

3. Perform data manipulation operations using NumPy and Pandas.

4. Visualize data using Matplotlib and Seaborn libraries.

5. Implement classification and regression models using Scikit-learn.

6. Apply clustering techniques using K-Means and evaluate results.

7. Access and process data from web APIs using the requests module.

8. Connect Python with a SQLite database and perform CRUD operations.

9. Develop a simple data application using Flask or Streamlit framework.

Page 7 of 44
Course Outcomes

Knowledge
COs Course Outcomes
Level
Describe advanced Python features such as iterators, generators, decorators, Understand
CO1
and OOP concepts. (K2)
Perform data cleaning, manipulation, and visualization using NumPy, Apply
CO2
Pandas, and visualization libraries. (K3)
Build and evaluate basic machine learning models using Scikit-learn, Apply
CO3
TensorFlow, or PyTorch. (K3)
Implement automation tasks, API integration, web scraping, and database Analyze
CO4
operations using Python tools. (K4)
Create test, and deploy Python applications using frameworks like Flask, Analyze
CO5
Streamlit, and FastAPI. (K4)

Mapping Table Mapping of COs with POs and PSOs

COs/ PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO PSO


POs 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
CO1 3 2 2 1 2 - - - - 1 - 1 3 2 2
CO2 2 3 2 2 3 - - - - 1 - 1 3 3 2
CO3 2 3 3 3 3 - - - - 1 - 1 3 3 3

CO4 2 2 3 3 3 - - - - 2 - 1 2 3 3
CO5 2 3 3 3 3 - - 2 3 3 2 2 3 3 3
Mapping: 1-Low, 2-Medium, 3-High (Mapping value based on usage of Action verbs in each CO)

Page 8 of 44
List of Experiments with COs, POs & PSOs

Exp.
Name of the Experiment COs POs PSOs
No.
Program using iterators, generators, and
1. CO1 1, 2, 3, 4, 5, 10& 12 1, 2 & 3
decorators in Python.
Implement object-oriented concepts with
2. inheritance, polymorphism, and exception CO1 1, 2, 3, 4, 5, 10& 12 1, 2 & 3
handling.
Perform data manipulation operations
3. CO2 1, 2, 3, 4, 5, 10& 12 1, 2 & 3
using NumPy and Pandas.
Visualize data using Matplotlib and
4. CO2 1, 2, 3, 4, 5, 10& 12 1, 2 & 3
Seaborn libraries.
Implement classification and regression
5. CO3 1, 2, 3, 4, 5, 10& 12 1, 2 & 3
models using Scikit-learn.
Apply clustering techniques using K-
6. CO3 1, 2, 3, 4, 5, 10& 12 1, 2 & 3
Means and evaluate results.
Access and process data from web APIs
7. CO4 1, 2, 3, 4, 5, 10& 12 1, 2 & 3
using the requests module.
Connect Python with a SQLite database
8. CO4 1, 2, 3, 4, 5, 10& 12 1, 2 & 3
and perform CRUD operations.
Develop a simple data application using
9. CO5 1, 2, 3, 4, 5,8,9,10,11& 12 1, 2 & 3
Flask or Streamlit framework.
Total: 30 Hours

Page 9 of 44
[Link]
PROGRAM USING ITERATORS, GENERATORS, AND
Date: DECORATORS IN PYTHON

Aim:

To write a Python program that demonstrates the use of decorators, iterators, and
generators.

Algorithm:

Step 1: Start by defining a decorator function that prints a message before and after the
execution of the given function.
Step 2: Create a CountIterator class that initializes a counter from 1 and increments it up
to a limit n.
Step 3: Implement the __iter__() and __next__() methods to make the class work as an
iterator that stops at n.
Step 4: Define a generator function that uses yield to produce even numbers from 2 to
2n.
Step 5: Create a function run_simple_examples() that prints outputs from both the
iterator and the generator.
Step 6: Apply the decorator to this function so additional messages run before and after
the function executes.
Step 7: Call the decorated function, which triggers the decorator and displays iterator
values and generator values.

Program:

# ---------------------------

# Simple Decorator

# ---------------------------

def simple_decorator(func):

def wrapper():

Page 10 of 44
print("Before the function runs")

func()

print("After the function runs")

return wrapper

# ---------------------------

# Simple Iterator

# ---------------------------

class CountIterator:

def __init__(self, n):

self.n = n

self.i = 1

def __iter__(self):

return self

def __next__(self):

if self.i <= self.n:

val = self.i

self.i += 1

return val

else:

raise StopIteration

# ---------------------------

# Simple Generator

# ---------------------------

def simple_generator(n):

Page 11 of 44
for i in range(1, n+1):

yield i*2 # generate even numbers

# ---------------------------

# Using Decorator

# ---------------------------

@simple_decorator

def run_simple_examples():

print("Iterator example (count 1 to 5):")

for num in CountIterator(5):

print(num, end=" ")

print("\nGenerator example (even numbers 1 to 5):")

for num in simple_generator(5):

print(num, end=" ")

print()

# Run the function

run_simple_examples()

Page 12 of 44
Output:

Before the function runs

Iterator example (count 1 to 5):

12345

Generator example (even numbers 1 to 5):

2 4 6 8 10

After the function runs

Result:
Thus, the Python program successfully demonstrates the concept of decorators,
iterators, and generators.

Page 13 of 44
[Link]
IMPLEMENT OBJECT-ORIENTED CONCEPTS WIT INHERITANCE,
Date: POLYMORPHISM, AND EXCEPTION HANDLING

Aim:

To implement object-oriented programming concepts in Python using inheritance,


polymorphism, and exception handling, and to demonstrate how derived classes override
base class methods and how errors are handled gracefully.

Algorithm:

Step 1: Define a base class Animal with an initializer to set the animal’s name and a speak() method
that raises NotImplementedError to enforce polymorphism.
Step 2: Create derived classes Dog and Cat that inherit from Animal and override the
speak() method with their specific sound.
Step 3: Define a function animal_sound() that takes an object and attempts to call its speak()
method inside a try block.
Step 4: Use an except block to catch NotImplementedError and display a meaningful error
message.
Step 5: Create objects of the derived classes (Dog and Cat) and also an object of the base
class (Animal).
Step 6: Store all created objects in a list to demonstrate polymorphism using a common
reference type.
Step 7: Loop through the list and call the animal_sound() function for each object to display
overridden method outputs and handle exceptions for unsupported methods.
Program:

# ---------------------------
# Base Class
# ---------------------------
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):

Page 14 of 44
# Polymorphism: different animals speak differently
raise NotImplementedError("Subclass must implement this method")
# ---------------------------
# Derived Classes (Inheritance)
# ---------------------------
class Dog(Animal):
def speak(self):
return f"{[Link]} says Woof!"
class Cat(Animal):
def speak(self):
return f"{[Link]} says Meow!"
# ---------------------------
# Exception Handling Example
# ---------------------------
def animal_sound(animal):
try:
print([Link]())
except NotImplementedError as e:
print(f"Error: {e}")
# ---------------------------
# Using the Classes
# ---------------------------
dog = Dog("Buddy")
cat = Cat("Kitty")
animal = Animal("Unknown") # Base class object
# Demonstrating polymorphism
animals = [dog, cat, animal]
for a in animals:
animal_sound(a)

Page 15 of 44
Output:

Buddy says Woof!


Kitty says Meow!
Error: Subclass must implement this method

Result:
Thus, the program correctly implements inheritance, polymorphism, and exception
handling.

Page 16 of 44
[Link]
PERFORM DATA MANIPULATION OPERATIONS USING
Date: NUMPY AND PANDAS

Aim:

To perform data manipulation operations using NumPy and Pandas in Python, including
array creation, reshaping, mathematical operations, DataFrame creation, filtering, column
operations, and aggregation.

Algorithm:

Step 1: Import the required libraries NumPy and Pandas for numerical and data manipulation
operations.
Step 2: Create a NumPy array and perform operations such as reshaping, arithmetic
modifications, and computing statistical values like sum and mean.
Step 3: Create a Pandas DataFrame using a dictionary containing Name, Age, and Salary
fields.
Step 4: Display the DataFrame and view specific portions using functions like head() and
info().
Step 5: Select specific columns (e.g., Name) from the DataFrame for examination.
Step 6: Apply filtering to retrieve rows that satisfy a condition (e.g., Age > 30).
Step 7: Add a new column (Bonus) and perform grouping and aggregation to calculate the
mean salary grouped by Age.

Program:

# ---------------------------
# Import libraries
# ---------------------------
import numpy as np
import pandas as pd
# ---------------------------
# NumPy Operations
# ---------------------------

Page 17 of 44
# Create a NumPy array
arr = [Link]([1, 2, 3, 4, 5, 6])
print("Original NumPy array:", arr)
# Array reshaping
arr_reshaped = [Link](2, 3)
print("Reshaped array (2x3):\n", arr_reshaped)
# Basic operations
print("Array + 10:", arr + 10)
print("Array squared:", arr**2)
print("Sum of array elements:", [Link]())
print("Mean of array elements:", [Link]())
# ---------------------------
# Pandas Operations
# ---------------------------
# Create a DataFrame
data = {
"Name": ["Alice", "Bob", "Charlie", "David", "Eva"],
"Age": [25, 30, 35, 40, 22],
"Salary": [50000, 60000, 70000, 80000, 45000]
}
df = [Link](data)
print("\nOriginal DataFrame:\n", df)
# Viewing data
print("\nFirst 3 rows:\n", [Link](3))
print("\nDataFrame info:")
print([Link]())
# Selecting columns
print("\nNames column:\n", df["Name"])

Page 18 of 44
# Filtering rows
print("\nEmployees with Age > 30:\n", df[df["Age"] > 30])
# Adding a new column
df["Bonus"] = df["Salary"] * 0.1
print("\nDataFrame after adding Bonus column:\n", df)
# Grouping and aggregation
age_mean = [Link]("Age")["Salary"].mean()
print("\nMean Salary by Age:\n", age_mean)

Output:

Original NumPy array: [1 2 3 4 5 6]


Reshaped array (2x3):
[[1 2 3]
[4 5 6]]
Array + 10: [11 12 13 14 15 16]
Array squared: [ 1 4 9 16 25 36]
Sum of array elements: 21
Mean of array elements: 3.5

Original DataFrame:
Name Age Salary
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 35 70000
3 David 40 80000
4 Eva 22 45000

First 3 rows:
Name Age Salary
0 Alice 25 50000

Page 19 of 44
1 Bob 30 60000
2 Charlie 35 70000

DataFrame info:
<class '[Link]'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Name 5 non-null object
1 Age 5 non-null int64
2 Salary 5 non-null int64
dtypes: int64(2), object(1)
memory usage: 252.0+ bytes
None

Names column:
0 Alice
1 Bob
2 Charlie
3 David
4 Eva
Name: Name, dtype: object

Employees with Age > 30:


Name Age Salary
2 Charlie 35 70000
3 David 40 80000

DataFrame after adding Bonus column:

Page 20 of 44
Name Age Salary Bonus
0 Alice 25 50000 5000.0
1 Bob 30 60000 6000.0
2 Charlie 35 70000 7000.0
3 David 40 80000 8000.0
4 Eva 22 45000 4500.0

Mean Salary by Age:


Age
22 45000.0
25 50000.0
30 60000.0
35 70000.0
40 80000.0
Name: Salary, dtype: float64

Result:
Thus,the program successfully demonstrates key data manipulation operations using
NumPy and Pandas.

Page 21 of 44
[Link]
VISUALIZE DATA USING MATPLOTLIB AND SEABORN
Date: LIBRARIES

Aim:

To visualize data using Matplotlib and Seaborn libraries in Python by creating line plots,
bar charts, scatter plots, and heatmaps for effective graphical representation of data.

Algorithm:

Step 1: Import the required libraries: Matplotlib for basic plotting, Seaborn for advanced
visualizations, and Pandas/Numpy for handling sample data.
Step 2: Create a sample dataset containing Month, Sales, and Profit values and store it in a
Pandas DataFrame.
Step 3: Use Matplotlib to create a line plot showing Sales and Profit trends across months
with markers, labels, grid, and legend.
Step 4: Generate a Seaborn bar plot to visualize monthly sales distribution.
Step 5: Create a Seaborn scatter plot to represent the relationship between Sales and Profit
with color coding for months.
Step 6: Calculate the correlation between Sales and Profit and visualize it using a Seaborn
heatmap with annotations.
Step 7: Display all plots using [Link]() to visualize the data graphically.

Program:

# ---------------------------
# Import Libraries
# ---------------------------
import [Link] as plt
import seaborn as sns
import pandas as pd
import numpy as np
# ---------------------------

Page 22 of 44
# Create Sample Data
# ---------------------------
data = {
"Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
"Sales": [200, 250, 300, 280, 350, 400],
"Profit": [50, 70, 90, 80, 100, 120]
}
df = [Link](data)
# ---------------------------
# Matplotlib Visualization
# ---------------------------
[Link](figsize=(8,5))
[Link](df["Month"], df["Sales"], marker='o', linestyle='-', color='b', label="Sales")
[Link](df["Month"], df["Profit"], marker='s', linestyle='--', color='g', label="Profit")
[Link]("Monthly Sales and Profit")
[Link]("Month")
[Link]("Amount ($)")
[Link]()
[Link](True)
[Link]()
# ---------------------------
# Seaborn Visualization
# ---------------------------
# Bar plot for Sales
[Link](figsize=(8,5))
[Link](x="Month", y="Sales", data=df, palette="viridis")
[Link]("Monthly Sales (Bar Plot)")
[Link]()
# Scatter plot for Sales vs Profit

Page 23 of 44
[Link](figsize=(8,5))
[Link](x="Sales", y="Profit", data=df, hue="Month", s=100, palette="deep")
[Link]("Sales vs Profit (Scatter Plot)")
[Link]()
# Heatmap for correlation
[Link](figsize=(5,4))
[Link](df[["Sales", "Profit"]].corr(), annot=True, cmap="coolwarm")
[Link]("Correlation Heatmap")
[Link]()

Output:

/tmp/[Link]: FutureWarning:

Passing `palette` without assigning `hue` is deprecated and will be removed in v0.14.0.
Assign the `x` variable to `hue` and set `legend=False` for the same effect.

Page 24 of 44
[Link](x="Month", y="Sales", data=df, palette="viridis")

Page 25 of 44
Result:
Thus, the program effectively demonstrates various data visualization techniques
using Matplotlib and Seaborn libraries.

Page 26 of 44
[Link]
IMPLEMENT CLASSIFICATION AND REGRESSION
Date: MODELS USING SCIKIT-LEARN

Aim:

To implement and evaluate classification and regression machine learning models using
the Scikit-learn library. The program demonstrates model training, testing, prediction, and
performance evaluation using accuracy, RMSE, and R² metrics.

Algorithm:

Step 1: Import required libraries from NumPy, Pandas, and Scikit-learn, including datasets, models,
train-test split, and evaluation metrics.
Step 2: Load the Iris dataset for classification and split it into training and testing sets.
Step 3: Train two classification models—Random Forest Classifier and Support Vector
Classifier (SVC)—and generate predictions on the test set.
Step 4: Evaluate classification performance using accuracy score for both models.
Step 5: Load the California Housing dataset for regression and split it into train and test sets.
Step 6: Train two regression models—Linear Regression and Random Forest Regressor—
and generate predictions on the test data.
Step 7: Evaluate regression performance using RMSE (Root Mean Squared Error) and R²
Score for both regression models.

Program:

# ---------------------------
# Import Libraries
# ---------------------------
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from [Link] import accuracy_score, mean_squared_error, r2_score
# Classification Models

Page 27 of 44
from [Link] import load_iris
from [Link] import RandomForestClassifier
from [Link] import SVC
# Regression Models
from [Link] import fetch_california_housing
from sklearn.linear_model import LinearRegression
from [Link] import RandomForestRegressor
# ---------------------------
# 1. Classification Example
# ---------------------------
# Load Iris dataset
iris = load_iris()
X = [Link]
y = [Link]
# Split into train and test

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,


random_state=42)
# Random Forest Classifier
rf_clf = RandomForestClassifier()
rf_clf.fit(X_train, y_train)
y_pred_rf = rf_clf.predict(X_test)
# Support Vector Classifier
svc_clf = SVC()
svc_clf.fit(X_train, y_train)
y_pred_svc = svc_clf.predict(X_test)
# Accuracy
print("Classification Results:")
print("Random Forest Accuracy:", accuracy_score(y_test, y_pred_rf))
print("SVC Accuracy:", accuracy_score(y_test, y_pred_svc))

Page 28 of 44
print("\n")
# ---------------------------
# 2. Regression Example
# ---------------------------
# Load California Housing dataset
housing = fetch_california_housing()
X = [Link]
y = [Link]
# Split into train and test

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,


random_state=42)
# Linear Regression
lin_reg = LinearRegression()
lin_reg.fit(X_train, y_train)
y_pred_lr = lin_reg.predict(X_test)
# Random Forest Regressor
rf_reg = RandomForestRegressor()
rf_reg.fit(X_train, y_train)
y_pred_rf = rf_reg.predict(X_test)
# Evaluate Regression
print("Regression Results:")
print("Linear Regression RMSE:", [Link](mean_squared_error(y_test, y_pred_lr)))
print("Linear Regression R2 Score:", r2_score(y_test, y_pred_lr))

print("Random Forest Regression RMSE:", [Link](mean_squared_error(y_test,


y_pred_rf)))
print("Random Forest Regression R2 Score:", r2_score(y_test, y_pred_rf))

Page 29 of 44
Output:

Classification Results:
Random Forest Accuracy: 1.0
SVC Accuracy: 1.0
Regression Results:
Linear Regression RMSE: 0.7284008391515455
Linear Regression R2 Score: 0.595770232606166
Random Forest Regression RMSE: 0.5043786423715607
Random Forest Regression R2 Score: 0.8061790162707501

Result:
Thus, the program correctly implements and evaluates machine learning classification
and regression models using Scikit-learn.

Page 30 of 44
[Link]
APPLY CLUSTERING TECHNIQUES USING K-MEANS AND
Date: EVALUATE RESULTS

Aim:

To apply the K-Means clustering algorithm on a dataset, visualize the clustered output, and
evaluate the clustering performance using metrics such as Inertia and Silhouette Score.

Algorithm:

Step 1: Import the necessary libraries including NumPy, Pandas, Matplotlib, KMeans,
silhouette_score, and make_blobs to generate sample data.
Step 2: Generate synthetic dataset using make_blobs() with a specified number of samples
and cluster centers to simulate real-world clustering data.
Step 3: Visualize the raw data points using a scatter plot to understand the distribution
before clustering.
Step 4: Apply the K-Means clustering algorithm by specifying the number of clusters and
fitting the model to the dataset.
Step 5: Predict the cluster labels for all data points using fit_predict().
Step 6: Evaluate clustering performance using:
 Inertia (measures how internally coherent clusters are; lower is better)
 Silhouette Score (measure of cluster separation; closer to 1 is better)
Step 7: Visualize the final clusters along with their centroids using a colored scatter plot to
observe clustering patterns.

Program:

# --------------------------
# Import Libraries
# --------------------------
import numpy as np
import pandas as pd
import [Link] as plt
from [Link] import KMeans

Page 31 of 44
from [Link] import silhouette_score
from [Link] import make_blobs
# --------------------------
# Create Sample Data
# --------------------------
X, y_true = make_blobs(n_samples=300,
centers=4,
cluster_std=0.60,
random_state=42)

# Plot raw data


[Link](X[:,0], X[:,1], s=30)
[Link]("Raw Data Points")
[Link]()
# --------------------------
# Apply K-Means Clustering
# --------------------------
kmeans = KMeans(n_clusters=4, random_state=42)
y_kmeans = kmeans.fit_predict(X)
# --------------------------
# Evaluate Clustering
# --------------------------
# 1. Inertia (lower = better)
print("K-Means Inertia:", kmeans.inertia_)
# 2. Silhouette Score (-1 to 1; higher = better)
sil_score = silhouette_score(X, y_kmeans)
print("Silhouette Score:", sil_score)
# --------------------------
# Visualize Clusters

Page 32 of 44
# --------------------------
[Link](X[:,0], X[:,1], c=y_kmeans, cmap='viridis', s=30)
[Link](kmeans.cluster_centers_[:,0],
kmeans.cluster_centers_[:,1],
s=200,
c='red',
marker='X',
label="Centroids")

[Link]("K-Means Clustering Results")


[Link]()
[Link]()

Output:

K-Means Inertia: 203.89074684058335

Page 33 of 44
Silhouette Score: 0.8756469540734731

Result:
Thus, the program correctly applies K-Means clustering, evaluates performance, and
visualizes the resulting clusters.

Page 34 of 44
[Link]
ACCESS AND PROCESS DATA FROM WEB APIS USING THE
Date: REQUESTS MODULE

Aim:

To access and process data from a web API using the requests module in Python, retrieve
JSON responses, extract useful information, and perform basic data processing operations
such as filtering and counting.

Algorithm:

Step 1: Import the requests module, which is used to send HTTP requests to web APIs.
Step 2: Define the URL of a public API endpoint (JSONPlaceholder in this case) and send
a GET request to retrieve data.
Step 3: Check the status code of the HTTP response to ensure the request was successful
(status code 200).
Step 4: Convert the received API response into JSON format for further processing.
Step 5: Display the first item from the JSON response to validate the retrieved structure.
Step 6: Extract specific fields (such as post titles) from each item in the JSON response and
display a subset of them.
Step 7: Process the JSON data by counting the number of posts created by each user
(userId) and printing the results.

Program:

# -----------------------------------------
# Import required module
# -----------------------------------------
import requests
# -----------------------------------------
# Step 1: Send GET request to a public API
# Using JSONPlaceholder (free fake API)
# -----------------------------------------

Page 35 of 44
url = "[Link]
response = [Link](url)
# -----------------------------------------
# Step 2: Check if request was successful
# -----------------------------------------
if response.status_code == 200:
print("Request successful!\n")
else:
print("Error:", response.status_code)

# -----------------------------------------
# Step 3: Convert response to JSON
# -----------------------------------------
data = [Link]()
# Show first item
print("First Post:\n", data[0], "\n")
# -----------------------------------------
# Step 4: Process Data
# (Extract Post Titles)
# -----------------------------------------
titles = [item['title'] for item in data]
print("List of Post Titles:\n")
for i, t in enumerate(titles[:5]):
print(f"{i+1}. {t}")
# -----------------------------------------
# Step 5: Count posts by userId
# -----------------------------------------
post_count = {}
for item in data:

Page 36 of 44
user = item['userId']
post_count[user] = post_count.get(user, 0) + 1
print("\nNumber of Posts Per User:\n", post_count)

Output:

Request successful!
First Post:
{'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio
reprehenderit', 'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et
cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet
architecto'}
List of Post Titles:
1. sunt aut facere repellat provident occaecati excepturi optio reprehenderit
2. qui est esse
3. ea molestias quasi exercitationem repellat qui ipsa sit aut
4. eum et est occaecati
5. nesciunt quas odio

Number of Posts Per User:


{1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10, 7: 10, 8: 10, 9: 10, 10: 10}

Result:
Thus, the program effectively illustrates web API consumption and basic JSON data
processing in Python.

Page 37 of 44
[Link]
CONNECT PYTHON WITH A SQLITE DATABASE AND PERFORM
Date: CRUD OPERATIONS

Aim:

To connect Python with an SQLite database and perform fundamental CRUD


operations—Create, Read, Update, and Delete—using the sqlite3 module.

Algorithm:

Step 1: Import the sqlite3 module and establish a connection to the SQLite database. If the
database file does not exist, it will be created automatically.

Step 2: Create a cursor object to execute SQL commands.

Step 3: Execute a SQL query to create a table (students) with fields such as id, name, age,
and grade, ensuring it is created only if it does not already exist.

Step 4: Perform the INSERT (Create) operation by adding multiple student records into the
table and commit the changes to the database.

Step 5: Perform the SELECT (Read) operation to fetch all records from the students table and
display them.

Step 6: Execute the UPDATE operation to modify an existing record (e.g., updating Bob’s
grade) and retrieve updated data to verify changes.

Step 7: Perform the DELETE operation to remove a specific record from the table, display
the final dataset, and then close the database connection.

Program:

# -----------------------------------------
# Import SQLite library
# -----------------------------------------
import sqlite3
# -----------------------------------------
# Step 1: Connect to SQLite Database

Page 38 of 44
# If file doesn't exist, it will be created.
# -----------------------------------------
conn = [Link]("[Link]")
# Create a cursor object
cur = [Link]()
# -----------------------------------------
# Step 2: Create a Table
# -----------------------------------------
[Link]("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER,
grade TEXT
)
""")
print("Table created successfully!")
# -----------------------------------------
# Step 3: INSERT (Create)
# -----------------------------------------
[Link]("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
("Alice", 20, "A"))
[Link]("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
("Bob", 22, "B"))
[Link]("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
("Charlie", 21, "A"))
[Link]() # Save changes
print("Data inserted successfully!")
# -----------------------------------------

Page 39 of 44
# Step 4: SELECT (Read)
# -----------------------------------------
[Link]("SELECT * FROM students")
rows = [Link]()
print("\nAll Students:")
for row in rows:
print(row)
# -----------------------------------------
# Step 5: UPDATE (Update a record)
# -----------------------------------------
[Link]("UPDATE students SET grade = ? WHERE name = ?", ("A+", "Bob"))
[Link]()
print("\nRecord updated successfully!")
# Display updated data
[Link]("SELECT * FROM students")
print("Updated Data:")
for row in [Link]():
print(row)
# -----------------------------------------
# Step 6: DELETE (Delete a record)
# -----------------------------------------
[Link]("DELETE FROM students WHERE name = ?", ("Charlie",))
[Link]()
print("\nRecord deleted successfully!")
# Display final data
[Link]("SELECT * FROM students")
print("Final Data:")
for row in [Link]():
print(row)

Page 40 of 44
# -----------------------------------------
# Close the connection
# -----------------------------------------
[Link]()
print("\nDatabase connection closed.")

Output:

Table created successfully!


Data inserted successfully!

All Students:
(1, 'Alice', 20, 'A')
(2, 'Bob', 22, 'B')
(3, 'Charlie', 21, 'A')
Record updated successfully!
Updated Data:
(1, 'Alice', 20, 'A')
(2, 'Bob', 22, 'A+')
(3, 'Charlie', 21, 'A')
Record deleted successfully!
Final Data:
(1, 'Alice', 20, 'A')
(2, 'Bob', 22, 'A+')
Database connection closed.

Result:
Thus, the program effectively performs Create, Read, Update, and Delete operations
on an SQLite database using Python.

Page 41 of 44
[Link]
DEVELOP A SIMPLE DATA APPLICATION USING FLASK OR
STREAMLIT FRAMEWORK
Date:

Aim:

To develop a simple data application is using a web framework to upload and display
CSV data in tabular form using Python.

Algorithm:

Step 1: Install the required Python libraries (gradio and pandas) in the Google Colab
environment.
Step 2: Import the necessary modules and define a function to read and display the uploaded
CSV file.
Step 3: Create a simple user interface using the Gradio framework with a file upload option
and data display component.
Step 4: Launch the application to generate a public URL for accessing the web interface.
Step 5: Upload a CSV file through the web interface to view its contents in tabular format.

Program:

STEP 1: Install Libraries:


!pip install gradio pandas

STEP 2: Program Code

import gradio as gr

import pandas as pd

def show_csv(file):

if file is None:

return "Please upload a CSV file"

df = pd.read_csv([Link])

return df

app = [Link](

fn=show_csv,

Page 42 of 44
inputs=[Link](label="Upload CSV File"),

outputs=[Link](label="CSV Data"),

title="Simple Data Application",

description="Upload a CSV file to display its data"

[Link]()

STEP 3: Open the App

Running on public URL: [Link]

STEP 4: Upload CSV File

Page 43 of 44
Output:

Result:
Thus, the simple data application was successfully developed and executed using the
Gradio framework. The application allows the user to upload a CSV file and displays the data
in a tabular format through a public web interface.

Page 44 of 44

You might also like