0% found this document useful (0 votes)
29 views29 pages

X-AI - Practical Lab Manual

The document is a lab manual for an Artificial Intelligence course at Velammal Vidyalaya for the academic year 2025-2026. It includes a detailed index of practical exercises covering various topics such as basic programming, data science, computer vision, and natural language processing, along with algorithms, code snippets, and conclusions for each practical. The manual aims to provide students with hands-on experience in implementing AI concepts through practical applications.

Uploaded by

TVIS Juniors
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views29 pages

X-AI - Practical Lab Manual

The document is a lab manual for an Artificial Intelligence course at Velammal Vidyalaya for the academic year 2025-2026. It includes a detailed index of practical exercises covering various topics such as basic programming, data science, computer vision, and natural language processing, along with algorithms, code snippets, and conclusions for each practical. The manual aims to provide students with hands-on experience in implementing AI concepts through practical applications.

Uploaded by

TVIS Juniors
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

VELAMMAL VIDYALAYA

ARTIFICIAL INTELLIGENCE

LAB MANUAL

2025-2026
VELAMMAL VIDYALAYA

ARTIFICIAL INTELLIGENCE

SUBMITED BY:
NAME :
CLASS :
BATCH :

Subject code: 417

INTERNAL MARKS:
PRACTICAL VIVA

EXTERNAL EXAMINAR:

INTERNAL EXAMINAR :
INDEX

SL DATE PROGRAM TOPIC PAGE


1 05.09.25 Practical 1: To Find the Greater Number

2 19.09.25 Practical 2: Check Whether a Number is Even or Odd

3 26.09.25 Practical 3: To Count Positive, Negative, and Zero


Numbers

4 06.10.25 Practical 4: To Display a Simple Bar Chart Using


Matplotlib

5 15.10.25 Practical 5 : Bar Chart – Students’ Marks (User Input)

Practical 6 : (Data Science ) Prediction of Palmer


6 25.10.25
Penguins Species

7 29.10.25 Practical 7 : (Data Science ) Student Performance


Analysis

8 05.11.25 Practical 8 : (Data Science ) Predicting Student


Performance using Study Hours

9 10.11.25 Practical 9 : (Computer Vision )Convert Color Image to


Grayscale

10 15.11.25 Practical 10 :(Computer Vision ) Rotate an Image

11 25.11.25 Practical 11 :(Computer Vision ) Flip an Image


(horizontally & vertically)

12 28.11.25 Practical 12 :Natural Language Processing (NLP) Word


Count Frequency

13 05.12.25 Practical 13 :NLP using Stemming (Porter Stemmer)

14 09.12.25 Practical 14 : Sentiment Analysis using NLP

15 10.12.25 Practical 15 :Bag of Words (BoW) Model using


CountVectorizer
Practical 1: To Find the Greater Number
Aim:
To write a Python program to find the greater of two numbers using an if-else statement.

Algorithm:

1. Start
2. Input two numbers a and b
3. Compare a and b
4. If a > b, print "a is greater"
5. Else print "b is greater"
6. Stop

Program:

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))

if a > b:
print(a, "is greater")
else:
print(b, "is greater")

Output:

Enter first number: 25


Enter second number: 18
25is greater

Conclusion:
The program successfully compares two numbers and displays the greater one.
Practical 2: Check Whether a Number is Even or Odd
Aim:
To check whether a given number is even or odd.

Algorithm:

1. Start
2. Input a number n
3. If n % 2 == 0, print “Even”
4. Else print “Odd”
5. Stop

Program:

n = int(input("Enter a number: "))

if n % 2 == 0:
print(n, "is Even")
else:
print(n, "is Odd")

Output:

Enter a number: 15
15is Odd

Conclusion:

The program correctly checks if a number is even or odd.


Practical 3: To Count Positive, Negative, and Zero Numbers
Aim:
To count how many numbers are positive, negative, or zero in a list.

Algorithm:

1. Start
2. Input numbers into a list
3. Initialize counters for positive, negative, and zero
4. Loop through list and check each number
5. Print counts
6. Stop

Program:

nums = [2, -5, 0, 7, -1, 0, 4]


pos = neg = zero = 0

for n innums:
if n >0:
pos += 1
elif n <0:
neg += 1
else:
zero += 1

print("Positive:", pos)
print("Negative:", neg)
print("Zero:", zero)

Output:

Positive: 3
Negative: 2
Zero: 2

Conclusion:
The program correctly counts the number of positive, negative, and zero values.
Practical 4: To Display a Simple Bar Chart Using Matplotlib
Aim:
To visualize students’ marks using a bar chart.

Algorithm:

1. Start
2. Import matplotlib.pyplot
3. Store names and marks in lists
4. Use plt.bar() to plot the chart
5. Label the axes and show chart

Program:

importmatplotlib.pyplotasplt

students = ['Amit', 'Riya', 'Karan', 'Neha']


marks = [85, 90, 78, 88]

plt.bar(students, marks, color='orange')


plt.title("Students' Marks")
plt.xlabel("Students")
plt.ylabel("Marks")
plt.show()
Output:
(Displays a bar chart with student names on X-axis and marks on Y-axis)

Conclusion:
The bar chart is successfully displayed using matplotlib.
Practical 5 :Bar Chart – Students’ Marks (User Input)
Aim:
To plot a bar chart of students’ marks entered by the user.

Algorithm:
1. Start
2. Ask the user for number of students
3. Take names and marks as input
4. Plot a bar chart using plt.bar()

Program:

importmatplotlib.pyplotasplt

n = int(input("Enter number of students: "))


names = []
marks = []

foriinrange(n):
name = input(f"Enter name of student {i+1}: ")
mark = int(input(f"Enter marks of {name}: "))
names.append(name)
marks.append(mark)

plt.bar(names, marks, color='skyblue')


plt.title("Students' Marks Chart")
plt.xlabel("Students")
plt.ylabel("Marks")
plt.show()
Example Output:

Conclusion:
The program successfully plots a bar chart of user-entered student marks.
Practical 6 : (Data Science ) Prediction of Palmer Penguins Species
Aim:
To predict the species of penguins based on their features using a statistical model.

Algorithm:

1. Import the dataset.


2. Explore data (check for null values, summary).
3. Visualize features using a chart.
4. Split data into training and testing sets.
5. Train a model (Decision Tree / Logistic Regression).
6. Predict species and evaluate accuracy.

Code :

# Import libraries
import pandas as pd
fromsklearn.model_selection import train_test_split
fromsklearn.tree import DecisionTreeClassifier
fromsklearn.metrics import accuracy_score
importmatplotlib.pyplot as plt

# Load dataset
url = "https://raw.githubusercontent.com/allisonhorst/palmerpenguins/main/inst/extdata/
penguins.csv"
df = pd.read_csv(url)

# Drop missing values


df.dropna(inplace=True)

# Select features and labels


X = df[['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']]
y = df['species']

# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train model
model = DecisionTreeClassifier()
model.fit(X_train, y_train)

# Predict
y_pred = model.predict(X_test)
# Accuracy
acc = accuracy_score(y_test, y_pred)
print("Accuracy:", acc)

# Plot
df['species'].value_counts().plot(kind='bar', title='Species Distribution')
plt.show()

Result:

Model Accuracy ≈ 95% (depends on split).


Bar chart displays the number of penguins per species.

Conclusion:
Decision Tree successfully classifies penguin species based on measurable features.
Practical 7 : (Data Science ) Student Performance Analysis
Aim:

To analyze the relationship between study hours and marks obtained using a regression model.

Algorithm:

1. Import and create dataset.


2. Visualize data using a scatter plot.
3. Split into training and testing sets.
4. Train a Linear Regression model.
5. Predict marks based on study hours.
6. Visualize the regression line.

Code :
import pandas as pd
importmatplotlib.pyplot as plt
fromsklearn.linear_model import LinearRegression
fromsklearn.model_selection import train_test_split

# Dataset
data = {'Hours': [1,2,3,4,5,6,7,8,9],
'Marks': [10,20,25,40,50,60,70,85,95]}
df = pd.DataFrame(data)

# Plot data
plt.scatter(df['Hours'], df['Marks'])
plt.title("Study Hours vs Marks")
plt.xlabel("Hours Studied")
plt.ylabel("Marks Scored")
plt.show()

# Split data
X = df[['Hours']]
y = df['Marks']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train model
model = LinearRegression()
model.fit(X_train, y_train)
# Predict
pred = model.predict(X_test)
print("Predicted Marks:", pred)

# Plot regression line


plt.scatter(X, y)
plt.plot(X, model.predict(X), color='red')
plt.title("Regression Line")
plt.xlabel("Hours Studied")
plt.ylabel("Marks Scored")
plt.show()

Conclusion:

Linear Regression model helps in predicting student marks from study hours effectively.

Result:

Regression line shows positive correlation — as hours increase, marks increase.


Practical 8 : (Data Science ) Predicting Student Performance using
Study Hours
Aim:
To predict student marks based on the number of hours studied using a linear regression model.

Algorithm:

1. Import required libraries.


2. Create or load the dataset (Hours vs Marks).
3. Visualize the data using a scatter plot.
4. Split the data into training and testing sets.
5. Train a Linear Regression model.
6. Predict the marks and visualize the regression line.

Code :

import pandas as pd
importmatplotlib.pyplot as plt
fromsklearn.linear_model import LinearRegression
fromsklearn.model_selection import train_test_split

# Step 1: Create dataset


data = {'Hours': [1,2,3,4,5,6,7,8,9],
'Marks': [10,20,25,40,50,60,70,85,95]}
df = pd.DataFrame(data)

# Step 2: Visualize
plt.scatter(df['Hours'], df['Marks'])
plt.title("Study Hours vs Marks")
plt.xlabel("Hours Studied")
plt.ylabel("Marks Scored")
plt.show()

# Step 3: Split data


X = df[['Hours']]
y = df['Marks']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Step 4: Train model


model = LinearRegression()
model.fit(X_train, y_train)
# Step 5: Predict
pred = model.predict(X_test)
print("Predicted Marks:", pred)

# Step 6: Plot Regression Line


plt.scatter(X, y)
plt.plot(X, model.predict(X), color='red')
plt.title("Regression Line")
plt.xlabel("Hours Studied")
plt.ylabel("Marks Scored")
plt.show()

Result:
Displays a red regression line showing that as study hours increase, marks increase.

Conclusion:
Linear Regression model effectively predicts student performance from study hours.
Practical 9 :(Computer Vision )ConvertColor Image to Grayscale
Aim:

To convert a color image into a grayscale image.

Algorithm:

1. Read the image.


2. Convert it to grayscale using cv2.cvtColor().
3. Display both images.

Code:

import cv2

img = cv2.imread(r"C:\Users\HP\Desktop\valli\class 10\practical\flower.jpg")


gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

cv2.imshow("Original Image", img)


cv2.imshow("Grayscale Image", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result:

Shows the original and the grayscale version of the image.

Conclusion:

The image color space was successfully converted to grayscale using OpenCV.
Practical 10 :(Computer Vision ) Rotate an Image
Aim:

To rotate an image using OpenCV.

Algorithm:

1. Import OpenCV.
2. Read an image.
3. Get image dimensions.
4. Use cv2.getRotationMatrix2D() and cv2.warpAffine() to rotate.
5. Display rotated image.

Code:

import cv2
img = cv2.imread(r"C:\Users\HP\Desktop\valli\class 10\practical\flower.jpg")
(h, w) = img.shape[:2]
ifimg is None:
print("❌ Image not found! Please check the path and try again.")
else:
# Step 4: Ask user for rotation angle
angle = float(input("Enter the rotation angle (e.g., 45, 90, 180): "))

# Step 5: Get image dimensions


(h, w) = img.shape[:2]

# Step 6: Create rotation matrix and rotate


M = cv2.getRotationMatrix2D((w // 2, h // 2), angle, 1.0)
rotated = cv2.warpAffine(img, M, (w, h))

# Step 7: Display images


cv2.imshow("Original Image", img)
cv2.imshow(f"Rotated Image ({angle}°)", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
Result:

Displays the original and rotated image.

Conclusion:

OpenCV can rotate an image at any angle using transformation matrices.


Practical 11 :(Computer Vision )

Flip an Image (horizontally & vertically)


Aim:

To flip an image horizontally and vertically.

Algorithm:

1. Read the image.


2. Flip horizontally using cv2.flip(img, 1).
3. Flip vertically using cv2.flip(img, 0).
4. Display results.

Code:
import cv2
img = cv2.imread(r"C:\Users\HP\Desktop\valli\class 10\practical\flower.jpg")

flip_h = cv2.flip(img, 1)
flip_v = cv2.flip(img, 0)

cv2.imshow("Original", img)
cv2.imshow("Horizontal Flip", flip_h)
cv2.imshow("Vertical Flip", flip_v)
cv2.waitKey(0)
cv2.destroyAllWindows()
Result:
The image appears flipped in both directions.

Conclusion:

Images can be mirrored horizontally or vertically using OpenCV’s flip function.


Practical 12 :Natural Language Processing (NLP) Word Count
Frequency
Aim:

To count how many times each word occurs in a text.

Algorithm:

1. Create a sentence.
2. Tokenize into words using split().
3. Use Python dictionary to count frequency.

Code:

text = input ("Enter the sentence:" )


words = text.lower().split()

freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1

print("Word Frequency:", freq)

Conclusion:
Word frequency analysis can help understand the importance of words in text.
Result :
Practical 13 :NLP using Stemming (Porter Stemmer)
Aim:

To reduce words to their root or base form using the Porter Stemming Algorithm in NLP.

Algorithm:

1. Import the PorterStemmer class from the nltk.stem module.


2. Create an object of PorterStemmer.
3. Accept a list of words from the user (as a single input line).
4. Split the input string into individual words using .split().
5. For each word in the list, apply the stem() method.
6. Display the original and stemmed form of each word.

Code:

fromnltk.stemimportPorterStemmer

# Create stemmer object


ps = PorterStemmer()

# Ask user to enter words separated by spaces


words_input = input("Enter words separated by spaces: ")

# Split user input into a list


words = words_input.split()

# Apply stemming to each word


print("\nStemmed Words:")
for w in words:
print(w, "→", ps.stem(w))

🧩 Conclusion:

The program successfully reduces inflected words to their root form using the Porter Stemming
Algorithm.
Stemming helps in simplifying words and preparing text for NLP applications like search engines, text
mining, and sentiment analysis.
Practical 14 : Sentiment Analysis using NLP
Aim:

To analyze user-given text and classify its sentiment as positive or negative using the Naive Bayes
classifier and TF-IDF vectorization.

Algorithm:

1. Import the required modules from sklearn.


2. Prepare a small training dataset with sentences and their sentiment labels.
3. Create a pipeline combining TfidfVectorizer() and MultinomialNB().
4. Train the model using the fit() method.
5. Ask the user to enter one or more sentences for testing.
6. Predict the sentiment using the trained model.
7. Display the input text along with its predicted sentiment.

Code

fromsklearn.feature_extraction.text import TfidfVectorizer


fromsklearn.naive_bayes import MultinomialNB
fromsklearn.pipeline import make_pipeline

# Step 1: Expanded training data


texts = [
"I love AI",
"This is great",
"I feel good",
"This is excellent",
"I hate this",
"This is bad",
"I feel terrible",
"This is awful"
]
labels = [
"positive",
"positive",
"positive",
"positive",
"negative",
"negative",
"negative",
"negative"
]

# Step 2: Create model pipeline


model = make_pipeline(TfidfVectorizer(), MultinomialNB())

# Step 3: Train the model


model.fit(texts, labels)

# Step 4: Get user input


user_input = input("Enter sentences to analyze (separate multiple sentences with commas): ")

# Step 5: Split user input into list


test_sentences = [s.strip() for s in user_input.split(",")]

# Step 6: Predict sentiment


predictions = model.predict(test_sentences)

# Step 7: Display results


print("\nSentiment Analysis Result:")
for text, sentiment in zip(test_sentences, predictions):
print(f"'{text}' → {sentiment}")
Sample Input:

Enter sentences toanalyze (separate multiple sentences with commas): AI is amazing, I dislike bugs

Sample Output:

Sentiment Analysis Result:


'AI is amazing' → positive
'I dislike bugs' → negative

Conclusion:

The program successfully classifies user-entered text as positive or negative using the Naive Bayes
algorithm and TF-IDF vectorization, demonstrating a simple real-world NLP application.
Practical 15 :Bag of Words (BoW) Model using CountVectorizer
Aim:

To represent a collection of text documents as numerical data using the Bag of Words model and
display the word frequency matrix using CountVectorizer in Python.

Algorithm:

1. Start the program.


2. Import necessary libraries:CountVectorizer from sklearn.feature_extraction.text and pandas.
3. Take input of multiple text documents from the user (separated by commas).
4. Create a CountVectorizer object to convert text into word frequency counts.
5. Fit and transform the input text using fit_transform().
6. Convert the resulting array into a DataFrame for better visualization.
7. Display the Bag of Words (word count) matrix.
8. End the program.

Code:

fromsklearn.feature_extraction.textimportCountVectorizer
import pandas aspd

# Step 1: Get input from user


docs_input = input("Enter sentences separated by commas: ")

# Step 2: Split input into a list


docs = [d.strip() for d indocs_input.split(",")]

# Step 3: Create CountVectorizer object


cv = CountVectorizer()

# Step 4: Transform the text data into numerical form


X = cv.fit_transform(docs)

# Step 5: Convert to DataFrame for display


df = pd.DataFrame(X.toarray(), columns=cv.get_feature_names_out())

# Step 6: Display result


print("\nBag of Words Representation:\n")
print(df)
Sample Input:

Enter sentences separated by commas: AI is the future, AI stands for Artificial Intelligence

Sample Output:

Bag of Words Representation:

ai artificialfor future intelligence is stands the


010010101
111101010

🧾 Conclusion:

The Bag of Words (BoW) model successfully converts textual data into numerical form by counting the
frequency of each word in the given sentences.
This representation helps in applying machine learning algorithms to textual data for further NLP tasks
such as classification or sentiment analysis.

You might also like