0% found this document useful (0 votes)
958 views21 pages

Ai Class 12 Practical 2

The document is a practical report file for the subject of Artificial Intelligence submitted by student Chiranjeev Seth at Amity International School for the session 2024-25. It includes various Python programming tasks related to data analysis, machine learning, and data visualization, along with source codes and outputs for each task. The report acknowledges the support of teachers, parents, and friends in completing the project.

Uploaded by

sethchiranjeev
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)
958 views21 pages

Ai Class 12 Practical 2

The document is a practical report file for the subject of Artificial Intelligence submitted by student Chiranjeev Seth at Amity International School for the session 2024-25. It includes various Python programming tasks related to data analysis, machine learning, and data visualization, along with source codes and outputs for each task. The report acknowledges the support of teachers, parents, and friends in completing the project.

Uploaded by

sethchiranjeev
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
You are on page 1/ 21

Amity International School

Vrindavan Yojna Lucknow

Session
2024-25

Practical File
Subject: Artificial
Intelligence (843)

Student Name: Chiranjeev Seth


Roll No:
Class & Sec: XII A
Amity International School
Vrindavan Yojna Lucknow

Practical Report File


Subject: Artificial Intelligence
(843)
Session: 2024-25

Submitted By Submitted To
Student Name: Chiranjeev Seth Teacher Name: Mrs. Narayani
Roll No: Singh
Class & Sec: XII A (PGT Computer Science)
AISSCE (CLASS XII) Practical Examination in

Artificial Intelligence

Session 2024-25

ACKNOWLEDGEMENT
I would like to express my special thanks of gratitude to my Artificial
Intelligence teacher Mrs. Narayani Singh , as well as our Principal,
Mrs. Roli Tripathi for providing me with the opportunity to work on
this beautiful project.

Secondly, I would also like to thank my parents and friends who


helped me to complete this project within the limited time frame.

Finally, I would like to thank everyone without whose help I could


not have completed my project successfully.
INDEX
S. TOPIC PAG SIGN
NO E NO ATUR
. E
Unit 1: Capstone Project
1 Write a python program to show Decompose Time Series Data into Trend.

2 Write a python program for Training and Test Data in Python Machine
Learning.
3 Write python program to calculate Mean Absolute Error for given dataset.

4 Write python program to calculate Root Mean Absolute Error for given
dataset.

5 Write python program to calculate Mean Squared Error for given dataset.
6 WAP to check given year is a leap year.

7 WAP in python to print sum of ten natural numbers.

8 WAP in python to print column graph for five subject performances of a


student.
9 WAP in python to create a basic histogram in Matplotlib of some random
values.

10 WAP in python to Draw a line in a diagram from position (1, 3) to (2, 8)


then to (6, 1) and finally to position (8, 10)
11 WAP in python to draw two scatter plots on the same figure for age verses
speed of cycling.
12 WAP in python to plot bar graph for four cricket teams and their highest
score in T-20 match. Use different colour for different team.
13 WAP in python to plot pie chart for five fruits and their quantity in basket
and pull the "Apples" wedge 0.2 from the center of the pie.
14 WAP to read data from CSV file and print top and bottom record using head
() and tail () from dataset.
15 WAP in python with Pyplot,, use the grid() function to add grid lines to the
plot.
Unit 1
Capstone Project-
Python Program(s)

Q1. Write a python program to show Decompose Time Series Data into Trend.

Source Code:

from random import randrange


from pandas import Series
from matplotlib import pyplot
from statsmodels.tsa.seasonal import seasonal_decompose
series = [i+randrange(10) for i in range(1,100)]
result = seasonal_decompose(series, model='additive', period=1)
result.plot()
pyplot.show()
Output:
Q9. WAP in python to create a basic histogram in Matplotlib of some random values.

Source Code:

import matplotlib.pyplot as plt

import numpy as np

# Generate random data for the histogram

data = np.random.randn(1000)

# Plotting a basic histogram

plt.hist(data, bins=30, color='skyblue', edgecolor='black')

# Adding labels and title

plt.xlabel('Values')

plt.ylabel('Frequency')

plt.title('Basic Histogram')

# Display the plot

plt.show()

Output:
Q11. WAP in python to draw two plots on the same figure for age verses speed of cycling.

Source Code:

import matplotlib.pyplot as plt


import numpy as np

#day one, the age and speed of 13 cycles:


x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)

#day two, the age and speed of 15 cycles:


x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y)

plt.show()

Output:
Q13. WAP in python to plot pie chart for five fruits and their quantity in basket and Pull the "Apples"
wedge 0.2 from the center of the pie.
Source Code:
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [0.2, 0, 0, 0]

plt.pie(y, labels = mylabels, explode = myexplode)


plt.show()

Output:
Q15. WAP in python with Pyplot, use the grid() function to add grid lines to the plot.

Source Code:
import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid()

plt.show()

Output:
Q2. Write a python program for Training and Test Data in Python Machine Learning.
Source Code:
# Import necessary libraries
import pandas as pd
from sklearn.model_selection import train_test_split

# Sample dataset: You can replace this with your actual data
# Creating a simple dataset
data = {
'Feature1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'Feature2': [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
'Target': [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
}

# Convert the dictionary into a DataFrame


df = pd.DataFrame(data)

# Separate features (X) and target variable (y)


X = df[['Feature1', 'Feature2']] # Features
y = df['Target'] # Target variable

# Split the dataset into training and testing sets


# test_size=0.2 means 20% of the data will be used for testing, 80% for training
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Display the results


print("Training Features:\n", X_train)
print("\nTraining Target:\n", y_train)
print("\nTesting Features:\n", X_test)
print("\nTesting Target:\n", y_test)
Output:
Feature1 Feature2
5 6 16
0 1 11
7 8 18
2 3 13
9 10 20
4 5 15
3 4 14
6 7 17,
Feature1 Feature2
8 9 19
1 2 12,
5 1
0 0
7 1
2 0
9 1
4 0
3 1
6 0
Name: Target, dtype: int64,
8 0
1 1
Name: Target, dtype: int64)
Q3. Write python program to calculate Mean Absolute Error for given dataset.
Source Output:
from sklearn.metrics import mean_absolute_error
import numpy as np

# Generate some sample data


y_true = np.array([1, 2, 3, 4, 5])
y_pred = np.array([1.5, 2.5, 2.8, 4.2, 4.9])

# Calculate the MAE


mae = mean_absolute_error(y_true, y_pred)
print("Mean Absolute Error:", mae)

Output:
Mean Absolute Error : 0.3
Q4. Write python program to calculate Root Mean Absolute Error for given dataset
Source Code:

import numpy as np
def calculate_rmae(predictions, actuals):

predictions (list or numpy array): The predicted values.


actuals (list or numpy array): The actual values.

Returns:
float: The RMAE value.

predictions = np.array(predictions)
actuals = np.array(actuals)
if len(predictions) != len(actuals):
raise ValueError("The length of predictions and actuals must be the same.")
absolute_errors = np.abs(predictions - actuals)
mean_absolute_error = np.mean(absolute_errors)
rmae = np.sqrt(mean_absolute_error)

return rmae
predictions = [3.2, 2.8, 4.1, 5.0]
actuals = [3.0, 2.5, 4.0, 5.2]

rmae = calculate_rmae(predictions, actuals)


print(f"Root Mean Absolute Error (RMAE): {rmae:.4f}")

Output:
Root Mean Absolute Error: 0.4472
Q5. Write python program to calculate Mean Squared Error for given dataset
Source Code:
# import necessary libraries
import pandas as pd
import numpy as np

# define your series


y_true = pd.Series([1, 2, 3, 4, 5])
y_pred = pd.Series([1.5, 2.5, 3.5, 4.5, 5.5])

# use mean() and square() methods


result = np.mean(np.square(y_true - y_pred))

# print the result


print(f'MSE: {result}')

Output:
Mse: 0.25
Q14. WAP to read data from CSV file and print top and bottom record using head () and tail () from
dataset.
Source Code:

import pandas as pd

# Replace 'your_file.csv' with the path to your CSV file


file_path = 'your_file.csv'

# Read the CSV file


df = pd.read_csv(file_path)

# Print the first 5 rows using head


print("First 5 rows:")
print(df.head())

# Print the last 5 rows using tail


print("\nLast 5 rows:")
print(df.tail())
Output:
First 5 rows:

ID Name Age Department

0 1 John Doe 28 Sales

1 2 Jane Smith 34 Marketing

2 3 Bob Johnson 45 IT

3 4 Emily Davis 29 HR

4 5 Michael Brown 41 Finance

Last 5 rows:

ID Name Age Department

5 6 Linda White 37 Marketing

6 7 Chris Green 30 IT

7 8 Alice Black 26 Sales

8 9 Mark Wood 38 Finance

9 10 Olivia Lee 33 HR
Q12. WAP in python to plot bar graph for four cricket teams and their highest score in T-20 match.
Use different colour for different team.
Source Code:
import matplotlib.pyplot as plt

# Data for the bar graph

teams = ['India', 'Pakistan', 'England', 'New Zealand']

scores = [210, 100, 170, 140]

# Colors for different teams

colors = ['blue', 'green', 'yellow', 'purple']

# Create the bar graph

plt.figure(figsize=(10, 6))

plt.bar(teams, scores, color=colors)

# Add titles and labels

plt.title('Highest Scores in T20 Matches')

plt.xlabel('Teams')

plt.ylabel('Highest Score')

plt.ylim(0, max(scores) + 20)

# Show the bar graph

plt.show()

Output:
Q7. WAP in python to print sum of ten natural numbers.

Source Code:

# Initialize the sum to 0

total_sum = 0

# Loop through the first 10 natural numbers (1 to 10)

for number in range(1, 11):

total_sum += number # Add each number to the total sum

# Print the result

print("The sum of the first 10 natural numbers is:", total_sum)

Output:

The sum of the first 10 natural numbers is: 55


Q8. WAP in python to print column graph for five subject performances of a student.
Source Code:

import matplotlib.pyplot as plt

subject = ['Physic','Chemistry', 'Biology','Maths','English']

percentage =[85,78,89,95,100]

plt.bar(subject,percentage)

plt.title('Analyse Performance of Student on Subject Wise')

plt.xlabel('Subject')

plt.ylabel('Percentage of Students passed')

plt.show()

Output:
Q10. WAP in python to Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and
finally to position (8, 10)
Source Code:

import matplotlib.pyplot as plt

import numpy as np

xpoints = np.array([1, 2, 6, 8])

ypoints = np.array([3, 8, 1, 10])

plt.plot(xpoints, ypoints)

plt.show()

Output:
Q6. WAP to check given year is a leap year.
Source Code:
def CheckLeap(Year):
# Checking if the given year is leap year
if((Year % 400 == 0) or (Year % 100 != 0) and (Year % 4 == 0)):
print("Yes! This Year is a leap Year");
# Else it is not a leap year
else:
print ("This Year is not a leap Year")
# Taking an input year from user
Year = int(input("Enter the number here: "))
# Printing result
CheckLeap(Year)

Output:
Enter the number here: 1700
Yes! This Year is a leap Year

You might also like