0% found this document useful (0 votes)
697 views40 pages

Class XII Data Science Practical Programs

Class 12 data science practical file

Uploaded by

ridaaimena
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)
697 views40 pages

Class XII Data Science Practical Programs

Class 12 data science practical file

Uploaded by

ridaaimena
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

Kovaipudur, Coimbatore – 641042

Affiliation No:
1930510

PRACTICAL FILE
for

SSCE 2026
Examination
[As a part of the Data Science Course
(844)]

Submitted
by:

Reg No. ___________

Under the
Guidance of:

PGT
(CSc)

CERTIFICATE

Certified that this is the bonafide record of the practical work in Data
Science done by (Reg No: ______________ ) and is submitted for the
Practical Examination at CS Academy, Coimbatore on ________________.

____________
_________

Signa
ture of Principal

([Link]
Baburaj)
________________________
________________________

Internal Examiner
External Examiner

INDEX

[Link] TOPIC PAGE


NO.
1. Scatter plot - R Studio
2. Line chart 1
3. Line chart 2
4. Bar chart 1
5. Bar chart 2
6. Pie chart
7. Univariate analysis – R Studio
8. Univariate analysis - Box plot
9. Univariate analysis – Histogram
10. Bivariate analysis
11. Decision tree
12. Scatter plot
13. KNN Algorithm
14. Line of best fit
15. Line of best fit - formatting
16. Linear regression
17. Multiple linear regression 1
18. Multiple linear regression 2
19. Non linear regression 1
20. Non linear regression 2
21. Clustering of data
22. K means clustering
Instructions:

1. Please do not take print out of the instructions typed.


2. Every program should begin in a new page
3. Every program should have AIM, CODING, OUTPUT and
RESULT.
4. All headings will have a font size of 16 and rest will have
size 14pt
5. Add borders to all the pages
6. Index should only be typed.
7. Page numbers to start after the index.
8. All programs should have a heading at the center.
9. Only colour print out to be taken
10. Rough draft can be black and white - back to back
11. Final draft - Only one side print and all pages to be
spiral bound. The outer cover for the spiral should be blue.

SCATTER PLOT

QUESTION 1:
Plot a scatter plot for any two variables.
AIM: To plot a scatter plot for two variables using R.

CODING:

>x=c(1,2,3,4,5)

>y=c(200,400,300,110,100)

>plot(x,y,main='title',xlab='Car number',ylab='speed')

OUTPUT:

RESULT :

The above program has been successfully executed and the


output is verified.

LINE CHART 1

QUESTION 2:
Draw a line chart in R to depict age vs height.

AIM: To draw a line chart to depict age vs height.


CODING:

>age = c(20, 25, 30, 35, 40)

>height = c(160, 165, 170, 175, 180)

>plot(age,height,type="o",xlab="Age",ylab="Height",main="R
ight height for the right age")

OUTPUT:

RESULT:

The above program has been successfully executed and the


output is verified.

LINE CHART 2

QUESTION 3:
A company made an analysis for 5 years from 2017 to 2022.
Draw a line chart to show the sales performance over the 5
years. Give an appropriate title.

AIM: To plot a line chart showing a company’s sales


performance.

CODING:

>year = c(2017, 2018, 2019, 2020, 2021, 2022)

>sales = c(100000, 120000, 90000, 110000, 130000, 150000)

>plot(year,sales,type="o",xlab="Years",ylab="Sales",main="S
ales performance over the years")

OUTPUT:

RESULT:

The above program has been executed successfully and the


output is verified.

BAR CHART 1

QUESTION 4:
Draw a bar chart to depict temperature over a period of 6
months horizontally.

AIM: To create a bar chart that depicts the temperature over a


period of 6 months.
CODING:

library(ggplot2)

temperature_data <- [Link](Month = c("Jan", "Feb", "Mar",


"Apr", "May", "Jun"),Temperature =
c(25.79,29.66,31.37,34.19,35.03,33.87))

ggplot(temperature_data, aes(x = Temperature, y = Month)) +


geom_bar(stat = "identity", fill = "skyblue") +labs(title =
"Temperature Over 6 Months", x = "Temperature (°C)", y =
"Month")

OUTPUT:

RE
SULT:

The above program has been executed successfully and the


output is verified.

BAR CHART 2

QUESTION 5:
Draw a bar chart to depict temperature over a period of 6
months Vertically

AIM: To create a bar chart that depicts the temperature over a


period of 6 months.

CODING:

>temperature_data <- [Link](Month = c("Jan", "Feb",


"Mar", "Apr", "May", "Jun"),Temperature =
c(25.79,29.66,31.37,34.19,35.03,33.87))

>barplot(temperature_data$Temperature, [Link] =
temperature_data$Month,col = "skyblue",main = "Temperature
Over 6 Months",xlab = "Month",ylab = "Temperature (°C)")

OUTPUT:

RESULT:

The above program has been executed successfully and the


output is verified.

PIE CHART

QUESTION 6:
Draw a pie chart to show the population in Tamil Nadu ,
Kerala , Andhra Pradesh and Karnataka.

AIM: To show the population of states using a pie chart.


CODING:

>h=c(72147030,35090000,49577103,67833000)

>labels=c("Tamil Nadu","Kerala","Andhra
Pradesh","Karnataka")

>pie(h,labels)

OUTPUT:

RESULT:

The above program has been executed successfully and the


output is verified.

UNIVARIATE ANALYSIS – R STUDIO

QUESTION 7:
Write a program for univariate analysis using R Studio

AIM: To perform basic descriptive statistical analysis and


visualization on a dataset.
CODING:

d <- c(1:10)
print(d)
print(min(d))
print(max(d))
print(mean(d))
print(median(d))
print(IQR(d))
print(sd(d))
# Range
print(max(d) - min(d))
print(table(d))
boxplot(d)
hist(d)

OUTPUT:

RESULT:
The above program has been executed successfully and the
output is verified.

UNIVARIATE ANALYSIS - BOXPLOT

QUESTION 8: Read a csv file using Python and visualise


graphically on a single variable.
Univariate Analysis for Iris Data

About [Link]
Iris is a multivariate data set. Collection of 150 records of IRIS
flowers. Each record has 4 attributes - petal length and width,
sepal length and width.

3 types of Iris flowers and 50 records for each

Iris setosa
Iris virginica
Iris versicolor
AIM: To read a csv file using Python and visualise graphically
on a single variable.

CODING:

import pandas as pd
import [Link] as plt
df = pd.read_csv('[Link]') # reading the csv file
print(df)

[Link](df['sepalwidth'])

# drop - removes the column class and draws the graph

dfm = [Link]('Class',axis=1)
[Link]("Box plots of all 4 variables")
[Link]([Link],labels=["Sepal Length","Sepal Width",
"Petal length","Petal Width"])

[Link]()
OUTPUT:

RESULT:
The above program has been executed successfully and the
output is verified.

UNIVARIATE ANALYSIS – HISTOGRAM

QUESTION 9: Draw a histogram for a univariate analysis using


[Link] dataset.
AIM: To plot a Histogram for a univariate analysis using [Link]
dataset.

CODING:

import pandas as pd
import [Link] as plt
df = pd.read_csv('[Link]') # reading the csv file
[Link](df['petallength'])
[Link]()

OUTPUT:

RESULT:
The above program has been executed successfully and the
output is verified.
BIVARIATE ANALYSIS

QUESTION 10: Write a program using Python for Bivariate


Analysis using IRIS data set

AIM: To visualize the relationship between Sepal Length and


Petal Length from the Iris dataset using a scatter plot.

CODING:
import pandas as pd
import [Link] as plt
df = pd.read_csv('[Link]') # reading the csv file
[Link]("Line Plot of Sepal Length")
[Link]('Sepal Length')
[Link]('Petal Length')
[Link](df['sepallength'],df['petallength']) # two variables
[Link]()

OUTPUT:

RESULT:
The above program has been executed successfully and the
output is verified.

DECISION TREE

QUESTION 11: Classification Algorithm- I

Write a program to visualise a Decision Tree of iris


dataset

AIM: To visualise a Decision Tree of iris dataset

CODING:
from [Link] import load_iris
iris = load_iris()

import [Link] as plt


import numpy as np

from [Link] import DecisionTreeClassifier


from [Link] import plot_tree

[Link]()

# An estimator is an object that fits a model based on some


training data and is #capable of inferring some properties on
new data.

clf = DecisionTreeClassifier().fit([Link], [Link])


plot_tree(clf)
[Link]("Decision tree trained on all the iris features")
[Link]()

OUTPUT:
RESULT:
The above program has been executed successfully and the
output is verified.

SCATTER PLOT
QUESTION 12: Write a program using Python to draw a scatter
plot

AIM: To visualize data points with class labels using a scatter


plot, where colors represent different classes

CODING:

import [Link] as plt

x = [4, 5, 10, 4, 3, 11, 14 , 8, 10, 12]


y = [21, 19, 24, 17, 16, 25, 24, 22, 21, 21]
classes = [0, 0, 1, 0, 0, 1, 1, 0, 1, 1]

[Link](x, y, c=classes)
[Link]()

OUTPUT:

RESULT:
The above program has been executed successfully and the
output is verified.
KNN ALGORITHM
QUESTION 13: Write a program to perform KNN algorithm

# Type pip install scikit-learn in command prompt


from [Link] import KNeighborsClassifier

data = list(zip(x, y)) # maps the value of x to y

'''
This code is written in Python and uses the scikitlearn library.
• The first line creates an instance of the KNeighborsClassifier
class with the parameter n_neighbors set to 3.
• This means that the classifier will consider the 3 nearest
neighbors when making predictions.
• The second line fits the classifier to the training data X_train
and y_train.
• This means that the classifier will learn from the training data
and be able to make predictions on new data.
• Overall, this code is creating and training a K-Nearest
Neighbors classifier with a k value of 3.'''

AIM:

CODING

import [Link] as plt

x = [4, 5, 10, 4, 3, 11, 14 , 8, 10, 12]


y = [21, 19, 24, 17, 16, 25, 24, 22, 21, 21]
classes = [0, 0, 1, 0, 0, 1, 1, 0, 1, 1]

from [Link] import KNeighborsClassifier

data = list(zip(x, y))

knn = KNeighborsClassifier(n_neighbors=1)
[Link](data, classes)

new_x = 8
new_y = 21
new_point = [(new_x, new_y)]

prediction = [Link](new_point)

[Link](x + [new_x], y + [new_y], c=classes +


[prediction[0]])
[Link](x=new_x-1.7, y=new_y-0.7, s=f"new point, class:
{prediction[0]}")

[Link]()

OUTPUT
Result

14. Write a program to draw the line of best fit

import numpy as np
import [Link] as plt

#define data
x = [Link]([1, 2, 3, 4, 5, 6, 7, 8])
y = [Link]([2, 5, 6, 7, 9, 12, 16, 19])

#find line of best fit


a, b = [Link](x, y, 1)

#add points to plot


[Link](x, y)

#add line of best fit to plot


[Link](x, a*x+b)

[Link]()

Output

Result
15. Write a program to perform line of best fit with formatting

import numpy as np
import [Link] as plt

#define data
x = [Link]([1, 2, 3, 4, 5, 6, 7, 8])
y = [Link]([2, 5, 6, 7, 9, 12, 16, 19])

#find line of best fit


a, b = [Link](x, y, 1)

#add points to plot


[Link](x, y, color='purple')

#add line of best fit to plot


[Link](x, a*x+b, color='steelblue', linestyle='--', linewidth=2)

#add fitted regression equation to plot


[Link](1, 17, 'y = ' + '{:.2f}'.format(b) + ' + {:.2f}'.format(a) +
'x', size=14)
[Link]

Output
Result
16. Write a program to plot a linear regression model and calculate the
Mean Absolute Error and Root Square Mean using Python

import numpy as np
import [Link] as metrics
import [Link] as plt

y = [Link]([-3, -1, -2, 1, -1, 1, 2, 1, 3, 4, 3, 5])


yhat = [Link]([-2, 1, -1, 0, -1, 1, 2, 2, 3, 3, 3, 5])
x = list(range(len(y)))

[Link](x, y, color="blue", label="original")


[Link](x, yhat, color="red", label="predicted")
[Link]()
[Link]()

#By using the above formulas, we can easily calculate them in Python.

# calculate manually
d = y - yhat
mse_f = [Link](d**2)
mae_f = [Link](abs(d))
rmse_f = [Link](mse_f)
r2_f = 1-(sum(d**2)/sum(([Link](y))**2))

print("Results by manual calculation:")


print("MAE:",mae_f)
print("MSE:", mse_f)
print("RMSE:", rmse_f)
print("R-Squared:", r2_f)

Output
Result

17. Write a program using Python to visualise graph for multiple linear
regression

import numpy as np
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import [Link] as plt

def generate_dataset(n):
x = []
y = []
random_x1 = [Link]()
random_x2 = [Link]()
for i in range(n):
x1 = i
x2 = i/2 + [Link]()*n
[Link]([1, x1, x2])
[Link](random_x1 * x1 + random_x2 * x2 + 1)
return [Link](x), [Link](y)

x, y = generate_dataset(200)

[Link]['[Link]'] = 12

fig = [Link]()
ax = fig.add_subplot(projection ='3d')

[Link](x[:, 1], x[:, 2], y, label ='y', s = 5)


[Link]()
ax.view_init(45, 0)

[Link]()
18. Read a csv file and perform multiple linear regression.

import pandas as pd
import numpy as np
import [Link] as plt
from sklearn.model_selection import train_test_split
from [Link] import ColumnTransformer
from [Link] import OneHotEncoder
from sklearn.linear_model import LinearRegression

df_start = pd.read_csv(‘[Link]')
print(df_start.head())

# Describe data
print(df_start.describe())
# Data distribution
# Relationship between Sepallength and Sepalwidth
[Link](df_start['sepallength'], df_start['sepalwidth'], color =
'lightcoral') [Link]('Sepallength vs Sepalwidth')
[Link]('sepallength')
[Link]('sepalwidth')
[Link](False)
[Link]()

Output
Result

19. Write a program using Python to perform Non linear Regression


import numpy as np
import [Link] as plt
#matplotlib inline

x = [Link](-6.0, 6.0, 0.1)

##You can adjust the slope and intercept to verify the changes in the
graph
y = 1*(x**3) + 2*(x**2) + 1*x + 3
y_noise = 20 * [Link](size=[Link])
ydata = y + y_noise
[Link](x, ydata, 'bo')
[Link](x,y, 'r')
[Link]('Dependent Variable')
[Link]('Indepdendent Variable')
[Link]()

Output
Result

20. Write a program to depict the graph of a non linear regression model

import numpy as np
import [Link] as plt
#matplotlib inline

x = [Link](-6.0, 6.0, 0.1)

##You can adjust the slope and intercept to verify the changes in the
graph

y = [Link](x,2)
y_noise = 2 * [Link](size=[Link])
ydata = y + y_noise
[Link](x, ydata, 'bo')
[Link](x,y, 'r')
[Link]('Dependent Variable')
[Link]('Indepdendent Variable')
[Link]()

Output

Result
21. Write a program to perform clustering of data using Python

# Importing Modules
from sklearn import datasets
import [Link] as plt

# Loading dataset
iris_df = datasets.load_iris()

# Available methods on dataset


print(dir(iris_df))

# Features
print(iris_df.feature_names)

# Targets
print(iris_df.target)

# Target Names
print(iris_df.target_names)
label = {0: 'red', 1: 'blue', 2: 'green'}

# Dataset Slicing
x_axis = iris_df.data[:, 0] # Sepal Length
y_axis = iris_df.data[:, 2] # Sepal Width

# Plotting
[Link](x_axis, y_axis, c=iris_df.target)
[Link]()

Output
Result

22. K means Clustering program


Write a program to perform clustering using KNN

import numpy as np
import pandas as pd

import [Link] as plt

from [Link] import make_blobs


from [Link] import KNeighborsClassifier
from sklearn.model_selection import train_test_split

# create a dataset
X, y = make_blobs(n_samples = 500, n_features = 2, centers =
4,cluster_std = 1.5, random_state = 4)

# visualise a dataset
[Link]('seaborn')
[Link](figsize = (10,10))
[Link](X[:,0], X[:,1], c=y, marker= '*',s=100,edgecolors='black')
[Link]()

# Splitting Data into Training and Testing Datasets

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0)

# KNN Classifier Implementation

knn5 = KNeighborsClassifier(n_neighbors = 5)
knn1 = KNeighborsClassifier(n_neighbors=1)

# Predictions for the KNN Classifiers

[Link](X_train, y_train)
[Link](X_train, y_train)

y_pred_5 = [Link](X_test)
y_pred_1 = [Link](X_test)

# Predict Accuracy for both k values

from [Link] import accuracy_score


print("Accuracy with k=5", accuracy_score(y_test, y_pred_5)*100)
print("Accuracy with k=1", accuracy_score(y_test, y_pred_1)*100)

# Visualize Predictions

[Link](figsize = (15,5))
[Link](1,2,1)
[Link](X_test[:,0], X_test[:,1], c=y_pred_5, marker= '*',
s=100,edgecolors='black')
[Link]("Predicted values with k=5", fontsize=20)

[Link](1,2,2)
[Link](X_test[:,0], X_test[:,1], c=y_pred_1, marker= '*',
s=100,edgecolors='black')
[Link]("Predicted values with k=1", fontsize=20)
[Link]()

Common questions

Powered by AI

Scatter plots are advantageous in visualizing data relationships as they allow for displaying the correlation between two numerical variables, which can help in identifying trends, clusters, and outliers within the data set . They are particularly beneficial for datasets where the observer wants to evaluate whether and how strongly two variables are related, such as visualizing the class labels in a scatter plot where different colors represent different classes .

Decision trees are a vital tool in classification tasks as they provide a simple and interpretable predictive model that mimics human decision-making. They categorize data into branches representing decisions, which makes them highly interpretable. For instance, visualizing a Decision Tree of the iris dataset helps to clearly see the criteria used for classification based on petal and sepal measurements . They support decision-making processes by breaking down complex decision-making into a series of simpler decisions, making them valuable in predictive analytics in business, healthcare, and other fields.

A line chart depicting a company's sales performance over years visualizes the trend by connecting data points linearly, which helps in identifying rises and falls over time. In the context of sales performance from 2017 to 2022, it clearly shows the increase or decrease in sales, making it easier to detect consistent patterns or seasonal trends . This type of visualization is crucial when wanting to analyze how sales figures have changed annually, providing insights into potential business cycles or economic factors affecting sales.

Linear regression is commonly used to project a line of best fit in datasets because it provides the simplest model that explains the relationship between independent and dependent variables using a straight line. Visually, this is represented by plotting data points on a graph and drawing a line through the points that minimizes the sum of squared differences between the observed and predicted values. The example from the source demonstrates plotting a line of best fit using the polyfit function from numpy, where x and y data points are used to compute the line equation a*x + b . This visual representation aids in understanding trends and making predictions.

K-means clustering is important in pattern recognition because it partitions datasets into distinct groups based on feature similarity, thus uncovering underlying patterns or structures. This method is instrumental in scenarios like segmenting customers based on purchasing patterns or identifying similar regions within large geographical datasets. For instance, as illustrated in the clustering of iris data, K-means efficiently groups data points into clusters representing the different species of iris flowers, aiding in insights such as customer segmentation or anomaly detection . The centroids of these clusters can also provide prototype examples for each cluster, crucial in developing strategies or making informed decisions.

Univariate analysis allows analysts to summarize data, identify patterns, and make inferences about the dataset’s distribution from descriptive statistics and visualizations like histograms and box plots. Implementing this in Python involves computing statistical measures such as mean, median, mode, range, and visualizing these through box plots or histograms to detect outliers and understand the data's spread. For example, reading a 'csv' file and plotting box plots or histograms provides insights like data variability and central tendencies, critical for further data preprocessing and modeling tasks.

Multiple linear regression is essential in modeling relationships involving more than two variables because it allows for the estimation of the relationships between a dependent variable and multiple independent variables. For instance, in the example of generating a dataset for 3D visualization, multiple linear regression helps in predicting the dependent variable 'y' based on multiple independent variables 'x1' and 'x2' . This facilitates the understanding of more complex data structures and interactions between variables in a multi-dimensional space, enhancing predictive accuracy in fields like econometrics, biology, and engineering.

The K-Nearest Neighbors (KNN) algorithm plays a crucial role in classification due to its simple yet powerful method of classifying data based on feature similarity. It works on a distance-based approach by comparing the distance between the data points and assigning them to the class most common among its k-nearest neighbors. In practice, this involves using a distance metric like Euclidean distance to determine proximity . By evaluating the nearest data points (or neighbors), KNN can make predictions about the target class for new data entries, as illustrated by plotting the classification of a new data point against existing classes.

Nonlinear regression differs from linear regression in both model complexity and the way it fits the data. Whereas linear regression assumes a linear relationship between the dependent and independent variables, nonlinear regression can model more complex relationships using polynomial or exponential equations. For example, nonlinear regression can be seen when modelling a dataset with a cubic or quadratic function to better capture the curvature in the data points, as shown in plotting complex graphs . This flexibility in shaping the model to the data's structure allows nonlinear regression to achieve better fits in scenarios where linear models fail to capture the underlying patterns.

Bar charts are effective for comparing categorical data as they use bars to show the frequency or value of data items. When depicting monthly temperature variations, as in the given example of temperature over a six-month period, bar charts display the temperature for each month side by side . This side-by-side comparison makes it easy to visualize which months were hotter or colder, highlighting differences and trends in temperature levels over time, which is more effective than using just raw numbers.

You might also like