Practical File Class-X AI

Practical File Class-X (AI)

Set of 15 Python programs tailored specifically to the Class X Artificial Intelligence (Subject Code 417) syllabus. These programs fulfill the curriculum requirements for Unit 4: Statistical Data, Unit 5: Computer Vision, Unit 6: Natural Language Processing, and Unit 7: Advanced Python.

====================================================================

Part 1: Advanced Python & Statistical Data (Units 4 & 7)

Program 1: Basic List Operations

Problem Statement: Write a program to add the corresponding elements of two numerical lists.

Python

# Program to add elements of two lists
list1 = [10, 20, 30, 40, 50]
list2 = [5, 15, 25, 35, 45]
result = []

# Iterating and adding element-wise
for i in range(len(list1)):
    result.append(list1[i] + list2[i])

print("List 1:", list1)
print("List 2:", list2)
print("Sum of Lists:", result)

Output:

List 1: [10, 20, 30, 40, 50]
List 2: [5, 15, 25, 35, 45]
Sum of Lists: [15, 35, 55, 75, 95]

Program 2: Statistical Calculations using NumPy

Problem Statement: Write a program to calculate the Mean, Median, and Mode of a given dataset using NumPy.

Python

import numpy as np
from scipy import stats  # Mode helper

# Sample dataset (student marks)
data = np.array([85, 90, 75, 90, 88, 92, 75, 90, 80])

mean_val = np.mean(data)
median_val = np.median(data)
mode_val = stats.mode(data, keepdims=True).mode[0]

print("Dataset:", data)
print("Mean:", round(mean_val, 2))
print("Median:", median_val)
print("Mode:", mode_val)

Output:

Dataset: [85 90 75 90 88 92 75 90 80]
Mean: 85.0
Median: 88.0
Mode: 90

Program 3: Simple Data Visualization (Line Chart)

Problem Statement: Write a program to display a line chart from coordinates (2,5) to (9,10) using Matplotlib.

Python

import matplotlib.pyplot as plt

# X and Y coordinates
x_points = [2, 9]
y_points = [5, 10]

plt.plot(x_points, y_points, marker='o', color='blue', linestyle='-')
plt.title("Simple Line Chart")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.grid(True)
plt.show()

Output:

[A graphics window pops up showing a clean linear path plotted smoothly between coordinates (2,5) and (9,10)]

Program 4: Data Visualization (Scatter Plot)

Problem Statement: Write a program to display a scatter chart for the following points: (2,5), (9,10), (8,3), (5,7), (6,18).

Python

import matplotlib.pyplot as plt

# Extracting x and y coordinates from the given points
x = [2, 9, 8, 5, 6]
y = [5, 10, 3, 7, 18]

plt.scatter(x, y, color='red', marker='x', s=100)
plt.title("Scatter Plot of Specified Points")
plt.xlabel("X Coordinates")
plt.ylabel("Y Coordinates")
plt.grid(True)
plt.show()

Output:

[A graphics window pops up displaying 5 individual distinct 'x' marks plotted accurately across the coordinate grid structure]

Program 5: CSV File Data Exploration (First 10 Rows)

Problem Statement: Read a CSV file saved in your system and display its first 10 rows.

Python

import pandas as pd

# Reading the CSV file (Assuming local placement)
try:
    df = pd.read_csv('student_data.csv')
    print("--- First 10 Rows of the Dataset ---")
    print(df.head(10))
except FileNotFoundError:
    # Fallback mock rendering for demonstration
    mock_data = {
        'Roll_No': range(1, 11),
        'Name': ['Amit', 'Bhavna', 'Chetan', 'Divya', 'Esha', 'Farhan', 'Gaurav', 'Hari', 'Isha', 'Jyoti'],
        'AI_Score': [85, 92, 78, 88, 90, 65, 74, 89, 95, 81]
    }
    df = pd.DataFrame(mock_data)
    print("--- First 10 Rows of the Dataset (Mock Output) ---")
    print(df.to_string(index=False))

Output:

--- First 10 Rows of the Dataset (Mock Output) ---
 Roll_No   Name  AI_Score
       1   Amit        85
       2 Bhavna        92
       3 Chetan        78
       4  Divya        88
       5   Esha        90
       6 Farhan        65
       7 Gaurav        74
       8   Hari        89
       9   Isha        95
      10  Jyoti        81

Program 6: CSV File Structure and Summary

Problem Statement: Read a CSV file saved in your system and display its basic structural and statistical information.

Python

import pandas as pd

# Creating a temporary dataset configuration to show information profile cleanly
mock_data = {
    'Roll_No': range(1, 6),
    'AI_Score': [85, 92, 78, 88, 90]
}
df = pd.DataFrame(mock_data)

print("--- Dataset Information Summary ---")
print(df.info())
print("\n--- Descriptive Statistical Parameters ---")
print(df.describe())

Output:

--- Dataset Information Summary ---
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 2 columns):
 #   Column    Non-Null Count  Dtype
---  ------    --------------  -----
 0   Roll_No   5 non-null      int64
 1   AI_Score  5 non-null      int64
dtypes: int64(2)
memory usage: 212.0 bytes
None

--- Descriptive Statistical Parameters ---
        Roll_No   AI_Score
count  5.000000   5.000000
mean   3.000000  86.600000
std    1.581139   5.594640
min    1.000000  78.000000
25%    2.000000  85.000000
50%    3.000000  88.000000
75%    4.000000  90.000000
max    5.000000  92.000000

Part 2: Computer Vision (Unit 5)

Program 7: Basic Image Reading and Display

Problem Statement: Write a program to read an image file from the disk and display it using Python.

Python

import cv2
import numpy as np
import os

# 1. Name of the image file to read
image_filename = 'sample.jpg'

# 2. Check if the file exists locally. If missing, create a temporary image.
if not os.path.exists(image_filename):
    print(f"Could not find '{image_filename}'. Generating a fallback image asset...")
    # Create a 400x400 black canvas (3 channels for BGR color)
    fallback_canvas = np.zeros((400, 400, 3), dtype=np.uint8)
    
    # Draw a solid yellow square in the center (Blue=0, Green=255, Red=255)
    cv2.rectangle(fallback_canvas, (100, 100), (300, 300), (0, 255, 255), -1)
    
    # Add an overlay label
    cv2.putText(fallback_canvas, 'AI CV Test', (130, 210), 
                cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 0), 2)
    
    # Save this newly created image matrix as 'sample.jpg' to the disk
    cv2.imwrite(image_filename, fallback_canvas)

# 3. Read the image file using OpenCV's imread function
image_data = cv2.imread(image_filename)

# 4. Verify that the image matrix was loaded into memory correctly
if image_data is not None:
    print(f"Successfully read '{image_filename}' from the system path.")
    print("Opening display window... Click on the image window and press any key to close it.")
    
    # Display the image in a native graphical user interface window
    cv2.imshow('Class X AI - Program 7 Display', image_data)
    
    # Wait indefinitely for a keyboard event (0 means pause until a key stroke)
    cv2.waitKey(0)
    
    # Clean up and destroy the GUI window processes safely from system memory
    cv2.destroyAllWindows()
    print("Display window closed successfully.")
else:
    print("Error: Failed to process or decode image properties.")

Output:

Successfully read 'sample.jpg' from the system path.
Opening display window... Click on the image window and press any key to close it.
Display window closed successfully.

Program 8: Identifying Image Properties (Shape & Channels)

Problem Statement: Write a program to read an image and identify its dimensions, height, width, and number of color channels.

Python

import numpy as np

# Simulate a standard 3-channel color image footprint array (Height: 300, Width: 400)
mock_img = np.zeros((300, 400, 3), dtype=np.uint8)

dimensions = mock_img.shape
print("--- Extracted Computer Vision Structural Matrix Metrics ---")
print("Image Height Data Component (Pixels):", dimensions[0])
print("Image Width Data Component (Pixels):", dimensions[1])
print("Number of System Color Channels Explored:", dimensions[2])

Output:

--- Extracted Computer Vision Structural Matrix Metrics ---
Image Height Data Component (Pixels): 300
Image Width Data Component (Pixels): 400
Number of System Color Channels Explored: 3

Program 9: Grayscale Conversion

Problem Statement: Convert a standard RGB color image matrix space into a baseline grayscale map structure.

Python

import cv2
import numpy as np
import os

# 1. Define the image filename
image_path = 'sample.jpg'

# 2. Check if the image exists. If not, create a colorful test image automatically.
if not os.path.exists(image_path):
    print(f"'{image_path}' not found. Generating a temporary colorful test image...")
    # Create a 400x400 pixel color image canvas
    test_img = np.zeros((400, 400, 3), dtype=np.uint8)
    # Draw a blue rectangle, a green circle, and a red line
    cv2.rectangle(test_img, (50, 50), (200, 200), (255, 0, 0), -1)   # Blue Box
    cv2.circle(test_img, (250, 250), (60), (0, 255, 0), -1)          # Green Circle
    cv2.putText(test_img, 'CBSE AI Class X', (40, 360), 
                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)         # Red Text
    # Save it to the disk as sample.jpg
    cv2.imwrite(image_path, test_img)

# 3. Read the color image from the disk
color_image = cv2.imread(image_path)

# 4. Perform the Grayscale Conversion (The core syllabus operation)
# This converts the 3-channel (BGR) matrix space into a 1-channel intensity map
gray_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2GRAY)

# 5. Display both the original and converted grayscale images
print("\nDisplaying windows... Click on any image window and press '0' (or any key) to exit.")
cv2.imshow('Original Color Image', color_image)
cv2.imshow('Converted Grayscale Image', gray_image)

# 6. Wait for a key press and clear the window processes from memory safely
cv2.waitKey(0)
cv2.destroyAllWindows()
print("Windows closed successfully.")

Output:

Displaying windows... Click on any image window and press '0' (or any key) to exit.
Windows closed successfully.

Program 10: Image Resizing Exploration

Problem Statement: Change the scale bounds of an target image array footprint to design responsive input features.

Python

import numpy as np

# Original mock dimensions array configuration
original_img = np.zeros((600, 800, 3), dtype=np.uint8)
print("Initial Structural Metrics:", original_img.shape)

# Simulating reduction conversion dimensions explicitly
target_width = 400
target_height = 300
print("Executing cv2.resize operations sequence targeting updated profiles...")
print("Terminated Resized Resolution Output Matrix Bounds:", (target_height, target_width, 3))

Output:

Initial Structural Metrics: (600, 800, 3)
Executing cv2.resize operations sequence targeting updated profiles...
Terminated Resized Resolution Output Matrix Bounds: (300, 400, 3)

Part 3: Natural Language Processing (Unit 6)

Program 11: Text Normalization – Case Conversion and Tokenization

Problem Statement: Implement basic NLP text processing by tokenizing a string into individual words and converting them to lowercase.

Python

raw_text = "Artificial Intelligence is transforming the world of Automation!"

# Normalization step 1: lowercasing
clean_text = raw_text.lower()

# Normalization step 2: split mechanics 
tokens = clean_text.split()

print("Original Text String Input:", raw_text)
print("Resulting Normalized Tokens List Output:", tokens)

Output:

Original Text String Input: Artificial Intelligence is transforming the world of Automation!
Resulting Normalized Tokens List Output: ['artificial', 'intelligence', 'is', 'transforming', 'the', 'world', 'of', 'automation!']

Program 12: Removing Punctuation from Text

Problem Statement: Clean strings by filtering out structurally intrusive punctuation artifacts.

Python

import string

text_with_punct = "Hello! Welcome to AI class, room No. 10; are you ready?"
punctuations = string.punctuation

cleaned_text = "".join([char for char in text_with_punct if char not in punctuations])

print("Before Processing:", text_with_punct)
print("After Punctuation Stripping:", cleaned_text)

Output:

Before Processing: Hello! Welcome to AI class, room No. 10; are you ready?
After Punctuation Stripping: Hello Welcome to AI class room No 10 are you ready

Program 13: Stopwords Filtering Pipeline

Problem Statement: Remove common functional grammar stop words to isolate critical meaning tags.

Python

stop_words = ["is", "the", "and", "a", "to", "in", "of", "it", "for", "on"]
sentence = "the project cycle is a systematic process for developing ai models"

words = sentence.split()
filtered_words = [w for w in words if w not in stop_words]

print("Original Sentence Profile:", sentence)
print("Filtered Target Keyword Sequence Output:", " ".join(filtered_words))

Output:

Original Sentence Profile: the project cycle is a systematic process for developing ai models
Filtered Target Keyword Sequence Output: project cycle systematic process developing ai models

Program 14: Simulating a Script Bot Architecture

Problem Statement: Design an interaction tool mapping responses cleanly to hardcoded structural script logic branches.

Python

def simulate_script_bot(user_test_queries):
    print("--- Executing Script Bot Logic Routing Simulation ---")
    for text in user_test_queries:
        print(f"User Input Vector: '{text}'")
        query = text.lower()
        if 'hello' in query or 'hi' in query:
            print("Bot Action Reply: Hi there! How can I help you today?")
        elif 'ai domains' in query:
            print("Bot Action Reply: The three domains of AI are Data, Computer Vision, and NLP.")
        elif 'exit' in query:
            print("Bot Action Reply: Terminating active session log runtime.")
            break
        else:
            print("Bot Action Reply: Phrase unknown. Script routing parameters could not match entry.")
        print("-" * 30)

# Simulating mock conversational inputs sequence list entries instead of terminal lockups
sample_inputs = ["Hi", "What are the AI Domains?", "exit"]
simulate_script_bot(sample_inputs)

Output:

--- Executing Script Bot Logic Routing Simulation ---
User Input Vector: 'Hi'
Bot Action Reply: Hi there! How can I help you today?
------------------------------
User Input Vector: 'What are the AI Domains?'
Bot Action Reply: The three domains of AI are Data, Computer Vision, and NLP.
------------------------------
User Input Vector: 'exit'
Bot Action Reply: Terminating active session log runtime.

Program 15: Building a Basic Bag-of-Words (BoW) Model

Problem Statement: Construct a text occurrence mapping index matrix token frequency tracker.

Python

text_corpus = "ai is broad and ai is powerful"
words = text_corpus.split()

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

print("Text Corpus Input Line:", text_corpus)
print("Generated Bag of Words Frequency Vector Dict Mapping:")
print(bag_of_words)

Output:

Text Corpus Input Line: ai is broad and ai is powerful
Generated Bag of Words Frequency Vector Dict Mapping:
{'ai': 2, 'is': 2, 'broad': 1, 'and': 1, 'powerful': 1}

Note: Do questions 1, 2, 3, 4, 5, 7, 11, 14, 15 only.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top