ML Practical Format
ML Practical Format
Diploma Engineering
Laboratory Manual
(Fundamentals of Machine Learning)
(4341603)
[IT sem-4]
Enrollment No 216120316003
Name Chauhan Krish Pravinbhai
Branch Information Technology(IT)
Academic Term 222
Institute Dr S & S.S. Ghandhy College of Engg &
Tech.
DTE’s Vision:
● To provide globally competitive technical education;
● Remove geographical imbalances and inconsistencies;
● Develop student friendly resources with a special focus on girls’ education
and support to weaker sections;
● Develop programs relevant to industry and create a vibrant pool of technical
professionals.
Institute’s Vision:
“To be a unique center of excellence in technical education & innovation for
sustainable growth of industry and society.”
Institute’s Mission:
Department’s Vision:
“To be a leading department in providing competent IT engineer for the benefit of
industry and society.”
Department’s Mission:
M1: To prepare competent IT engineer by imparting qualitative technical education in
IT field with best infrastructure.
M2: To enhance the student’s technical competency in IT field for solving real world
problems.
M3: To nurture professional and ethical values in IT engineer to become a responsible
member of workforce and society.
Fundamentals of Machine Learning (4341603)
Certificate
Place:…………..
Date: …………………..
Preface
The primary aim of any laboratory/Practical/field work is enhancement of required skills as
well as creative ability amongst students to solve real time problems by developing relevant
competencies in psychomotor domain. Keeping in view, GTU has designed competency focused
outcome-based curriculum -2021 (COGC-2021) for Diploma engineering programmes. In this more
time is allotted to practical work than theory. It shows importance of enhancement of skills amongst
students and it pays attention to utilize every second of time allotted for practical amongst Students,
Instructors and Lecturers to achieve relevant outcomes by performing rather than writing practice in
study type. It is essential for effective implementation of competency focused outcome- based Green
curriculum-2021. Every practical has been keenly designed to serve as a tool to develop & enhance
relevant industry needed competency in each and every student. These psychomotor skills are very
difficult to develop through traditional chalk and board content delivery method in the classroom.
Accordingly, this lab manual has been designed to focus on the industry defined relevant outcomes,
rather than old practice of conducting practical to prove concept and theory.
By using this lab manual, students can read procedure one day in advance to actual
performance day of practical experiment which generates interest and also, they can have idea of
judgement of magnitude prior to performance. This in turn enhances predetermined outcomes
amongst students. Each and every Experiment /Practical in this manual begins by competency,
industry relevant skills, course outcomes as well as practical outcomes which serve as a key role for
doing the practical. The students will also have a clear idea of safety and necessary precautions to be
taken while performing experiment.
This manual also provides guidelines to lecturers to facilitate student-centred lab activities
for each practical/experiment by arranging and managing necessary resources in order that the
students follow the procedures with required safety and necessary precautions to achieve outcomes.
It also gives an idea that how students will be assessed by providing Rubrics.
Fundamentals of machine learning course will help students to build up core competencies
in understanding machine learning approaches and students will be able to design and train machine
learning modes for various use cases. The lab work of the course is designed to develop crisp
understanding of the underpinning theory.
Although we try our level best to design this lab manual, but always there are chances of
improvement. We welcome any suggestions for improvement.
3 | Page
Fundamentals of Machine Learning (4341603)
1. Basic and Discipline specific knowledge: Apply knowledge of basic mathematics, science
and engineering fundamentals and engineering specialization to solve the engineering
problems.
2. Problem analysis: Identify and analyse well-defined engineering problems using codified
standard methods.
4. Engineering Tools, Experimentation and Testing: Apply modern engineering tools and
appropriate technique to conduct standard tests and measurements.
7. Life-long learning: Ability to analyze individual needs and engage in updating in the context
of technological changes in field of engineering.
4 | Page
Fundamentals of Machine Learning (4341603)
a) CO1: -To understand the need of machine learning for various problem solving.
b) CO2: - Prepare machine leaning model and learning the evaluation methods.
c) CO3: - Evaluate various supervised learning algorithms using appropriate dataset.
d) CO4: -Evaluate various unsupervised learning algorithms using appropriate dataset.
e) CO5:-To understand the use of various existing machine learning libraries.
CO1 CO2 CO3 CO4 CO5
S. No. Practical Outcome/Title of experiment
7. ML Project ✔
Use the following dataset as music.csv
5 | Page
Fundamentals of Machine Learning (4341603)
6 | Page
Fundamentals of Machine Learning (4341603)
The following industry relevant skills are expected to be developed in the students by
performance of experiments of this course.
a) Student will learn to automate variety of task making system more efficient and cost
effective
b) Student will learn efficient handling of data that will cater to better data analytics
c) Student will lean to implement machine learning approaches to varied field of
applications from healthcare to e-commerce.
7 | Page
Fundamentals of Machine Learning (4341603)
1. Organize the work in the group and make record of all observations.
2. Students shall develop maintenance skill as expected by industries.
3. Student shall attempt to develop related hand-on skills and build confidence.
8 | Page
Fundamentals of Machine Learning (4341603)
Numerical
1 Computing with Python (NumPy,
Matplotlib)
Introduction
2 to Pandas for data import and export (Excel,
CSV etc.)
Implement
4 the Find-S concept learning algorithm that
finds the most specific hypothesis that is
consistent with the given training data.
Conditions:
Hypothesis can only be conjunction (AND) of literals. Literals
are either attributes or their negations.
9 | Page
Fundamentals of Machine Learning (4341603)
7
ML Project
Use the following dataset as music.csv
9
Import vgsales.csv from kaggle platform.
a. Find rows and columns in dataset
b. Find basic information regarding dataset using
describe command.
C. Find values using values command.
10 | Page
Fundamentals of Machine Learning (4341603)
Project on regression
a. Import home_data.csv on kaggle using
pandas
b. Understand data by running head, info
and describe command
c. Plot the price of house with respect to
area using matplotlib library
d. Apply linear regression model to
predict the price of house
11 | Page
Fundamentals of Machine Learning (4341603)
Date: ……………
Practical No.1: Numerical Computing with Python (NumPy, Matplotlib)
A. Objective: Getting familiarized with python libraries related to visualization and
computation.
B. Expected Program Outcomes (POs):-PO1, PO2, PO3, PO4, PO7.
G. Prerequisite Theory:
Refer Unit 1 of course curriculum. Also explore the link following link
https://numpy.org/doc/stable/
https://matplotlib.org/stable/tutorials/index
H. Resources/Equipment Required
Sr.No. Instrument/Equipment Specification Quantity
/Components/Trainer kit
1 System supporting Jupyter Python 3.x 1
Notebook
12 | Page
Fundamentals of Machine Learning (4341603)
# 2)Shaping Array
Array2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print('1-D Array Shape:-', Array2.shape)
Output:-
1-D Array Shape:- (3, 3)
14 | Page
Fundamentals of Machine Learning (4341603)
b) array([3, 4, 5, 6, 7])
c) arraY([2, 3, 4, 5, 6, 7, 8])
d) array([3, 4, 5, 6, 7, 8])
3. Find the output of the below code
a = np.array([[[1,2,3],[4,5,6]]])
a) 1
b) (1,3)
c) 3
d) (3,1)
4. By default, Plot() function plots a?
a) Bar chart
b) Line chart
c) Pie chart
d) Horizontal bar chart
5. Which of the following type of chart is not supported by pyplot?
a) Pie
b) Boxplot
c) Histogram
d) All of the above
6. To create histogram pyplot provides?
a) hist()
b) histo()
c) histg()
d) histogram()
L. References / Suggestions ( lab manual designer should give)
Numpy
https://www.youtube.com/watch?v=Rbh1rieb3zc
Matplotlib
16 | Page
Fundamentals of Machine Learning (4341603)
https://www.youtube.com/watch?v=yZTBMMdPOww
M. Assessment-Rubrics
Present in
Watched other
practical session
Performed Performed students
but not
practical practical with performing
attentively
Engagement 5 him/her others help practical but not
participated in
self tried him/her self
performance
Work is submitted
Work done after
later than 1 week 2nd week but
Time 5 Completed Work submittedafter
but by the end of before the end
thework 3 week time
2ndweek of3rd week
within 1 week
Total 5 criteria and each having 0-5 marks, weightage taken from curriculum of that
course.
Max 25 marks
17 | Page
Fundamentals of Machine Learning (4341603)
Practical No.2: Introduction to Pandas for data import and export (Excel, CSV etc.)
A. Objective: Getting familiarized with python machine learning libraries.
B. Expected Program Outcomes (POs):-PO1, PO2, PO3, PO4, PO7.
G. Prerequisite Theory:
Refer Unit 6 of course curriculum. Also explore the link following link
https://pandas.pydata.org/docs/user_guide/index.html
H. Resources/Equipment Required
Sr.No. Instrument/Equipment Specification Quantity
/Components/Trainer kit
1 System supporting Jupyter Python 3.x 1
Notebook
18 | Page
Fundamentals of Machine Learning (4341603)
Output:-
pd.read_csv('Panda_Practical.csv')
Panda_Practical.csv:-
19 | Page
Fundamentals of Machine Learning (4341603)
b) Excel
c) HTML
d) All the above
3. Given a dataset named ‘data’ containing the 5 columns and 10 rows, find the
output of the below code?
print(len(data.columns))
a) 5
b) 10
c) 15
d) 50
4. What does the attribute shape return?
a) It returns the number of rows and columns respectively in the form of a
tuple
b) It returns the number of columns and rows respectively in the form of a
list
c) It returns the number of rows and columns respectively in the form of a
list
d) It returns the number of columns and rows respectively in the form of a
tuple
5. Which of the following commands return the data type of the values in each
column in the data frame
a) print(df.dtype)
20 | Page
Fundamentals of Machine Learning (4341603)
b) print(dtypes(df))
c) print(df.dtypes)
d) None of the above
L. References / Suggestions ( lab manual designer should give)
https://www.youtube.com/watch?v=RhEjmHeDNoA
M. Assessment-Rubrics
Present in
Watched other
practical session
Performed Performed students
but not
practical practical with performing
attentively
Engagement 5 him/her others help practical but not
participated in
self tried him/her self
performance
Work is submitted
Work done after
later than 1 week 2nd week but
Time 5 Completed Work submittedafter
but by the end of before the end
thework 3 week time
2ndweek of3rd week
within 1 week
Max 25 marks
21 | Page
Fundamentals of Machine Learning (4341603)
22 | Page
Fundamentals of Machine Learning (4341603)
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
Never eat or drink in the lab, as it can cause contamination and create safety
hazards.
If any accidents or injuries occur, immediately notify the instructor and seek
medical attention if necessary.
J. Procedure to be followed/Source code (CE & IT software subjects):
Supervised Learning algorithms − Almost all the popular supervised learning algorithms, like Linear
Regression, Support Vector Machine (SVM), Decision Tree etc., are the part of scikit-learn.
Unsupervised Learning algorithms − On the other hand, it also has all the popular unsupervised learning
algorithms from clustering, factor analysis, PCA (Principal Component Analysis) to unsupervised neural
networks.
Clustering − This model is used for grouping unlabeled data.
Cross Validation − It is used to check the accuracy of supervised models on unseen data.
Dimensionality Reduction − It is used for reducing the number of attributes in data which can be further
used for summarisation, visualisation and feature selection.
Ensemble methods − As name suggest, it is used for combining the predictions of multiple supervised
models.
Feature extraction − It is used to extract the features from data to define the attributes in image and text
data.
Open Source − It is open source library and also commercially usable under BSD license.
23 | Page
Fundamentals of Machine Learning (4341603)
Program-1:-
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
feature_names = iris.feature_names
target_names = iris.target_names
print("Feature names:", feature_names)
print("Target names:", target_names)
print("\nFirst 10 rows of X:\n", X[:10])
Output:-
Program-2 :-
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
print("X:-",len(X))
print("\n")
print("y:-",len(y))
print("\n")
Output:-
25 | Page
Fundamentals of Machine Learning (4341603)
M. Assessment-Rubrics
him/her participated in
self performance
Work is submitted
Work done after
later than 1 week 2nd week but
Time 5 Completed Work submittedafter
but by the end of before the end
thework 3 week time
2ndweek of3rd week
within 1 week
Max 25 marks
26 | Page
Fundamentals of Machine Learning (4341603)
Practical No.4: Implement the Find-S concept learning algorithm that finds the most specific
hypothesis that is consistent with the given training data.
Conditions:
27 | Page
Fundamentals of Machine Learning (4341603)
1 1 1 0 1 1 0 0 1
1 1 1 0 1 0 0 1 1
1 1 1 0 1 0 0 0 1
0 1 1 1 1 1 0 1 1
0 1 1 1 1 1 0 0 1
1 0 1 1 1 1 0 1 0
0 1 1 1 1 0 0 1 1
1 1 0 1 0 1 0 1 0
1 0 0 1 1 1 0 1 0
1 0 0 1 0 1 1 1 0
0 1 1 1 1 0 0 0 1
1 0 1 1 1 1 1 1 0
0 1 1 0 1 1 0 1 1
H. Resources/Equipment Required
Sr.No. Instrument/Equipment
Specification Quantity
/Components/Trainer kit
1 System supporting Jupyter Python 3.x 1
Notebook
28 | Page
Fundamentals of Machine Learning (4341603)
29 | Page
Fundamentals of Machine Learning (4341603)
Output:-
Practical-4_Dataset.csv
N. Assessment-Rubrics
30 | Page
Fundamentals of Machine Learning (4341603)
Present in
Watched other
practical session
Performed Performed students
but not
practical practical with performing
attentively
Engagement 5 him/her others help practical but not
participated in
self tried him/her self
performance
Work is submitted
Work done after
later than 1 week 2nd week but
Time 5 Completed Work submittedafter
but by the end of before the end
thework 3 week time
2ndweek of3rd week
within 1 week
Max 25 marks
31 | Page
Fundamentals of Machine Learning (4341603)
Practical No.5: Import Pima indian diabetes data Apply select K best and chi2 for feature
selection Identify the best features.
32 | Page
Fundamentals of Machine Learning (4341603)
Program:-
import pandas as pd
import numpy as np
from sklearn.feature_selection import *
read=pd.read_csv("diabetes.csv")
#read=list(read)
#print(read)
read=pd.DataFrame(read)
#print(read)
dataframe=read.values
#print(dataframe)
x=dataframe[:,0:8]
y=dataframe[:,8]
test=SelectKBest(score_func=f_classif,k=4)
fit=test.fit(x,y)
np.set_printoptions(precision=3)
print(fit.scores_)
features=fit.transform(x)
print(features[0:5,:])
33 | Page
Fundamentals of Machine Learning (4341603)
Output:-
4. The best fit model of size 5(i.e., with 5 features) always contains the set of
features from best fit model of size 4.
a) True
b) False
M. References / Suggestions ( lab manual designer should give)
Diabetes Prediction using Machine Learning from Kaggle-
https://www.youtube.com/watch?v=HTN6rccMu1k
https://www.kaggle.com/datasets/uciml/pima-indians-diabetes-database
N. Assessment-Rubrics
34 | Page
Fundamentals of Machine Learning (4341603)
Present in
Watched other
practical session
Performed Performed students
but not
practical practical with performing
attentively
Engagement 5 him/her others help practical but not
participated in
self tried him/her self
performance
Work is submitted
Work done after
later than 1 week 2nd week but
Time 5 Completed Work submittedafter
but by the end of before the end
thework 3 week time
2ndweek of3rd week
within 1 week
Max 25 marks
35 | Page
Fundamentals of Machine Learning (4341603)
The score_func parameter determines the function used to score the features. The default function is f_classif,
which only works with classification tasks. You can change this parameter to use other scoring functions.
You can use this function to set various printing options such as precision, threshold, edgeitems, linewidth,
suppress, nanstr, infstr, formatter, sign, and floatmode
The F1 score is the harmonic mean of precision and recall, where an F1 score reaches its best value at 1 and worst
score at 0. The formula for the F1 score is: F1 = 2 * (precision * recall) / (precision + recall)2.
To use the f1_score function, you can import it into your program like this: from sklearn.metrics import f1_score.
36 | Page
Fundamentals of Machine Learning (4341603)
Practical No.6: Write a program to learn a decision tree and use it to predict class labels of test
data.
37 | Page
Fundamentals of Machine Learning (4341603)
cls=DecisionTreeClassifier()
cls.fit(x_train,y_train)
y_pred=cls.predict(x_test)
accuracy=accuracy_score(y_test,y_pred)
print("Accuracy:-",accuracy)
Output:-
70:30 Ratio:-
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
iris=load_iris()
x=iris.data
y=iris.target
#print("X:-\n",x)
#print("Y:-\n",y)
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=42)
print("X Training:-\n",x_train.shape)
print("X Testing:-\n",x_test.shape)
print("Y Training:-\n",y_train.shape)
print("Y Testing:-\n",y_test.shape)
39 | Page
Fundamentals of Machine Learning (4341603)
print("\n")
cls=DecisionTreeClassifier()
cls.fit(x_train,y_train)
y_pred=cls.predict(x_test)
accuracy=accuracy_score(y_test,y_pred)
print("Accuracy:-",accuracy)
Output:-
40 | Page
Fundamentals of Machine Learning (4341603)
Calculations:
Calculate confusion matrix
41 | Page
Fundamentals of Machine Learning (4341603)
42 | Page
Fundamentals of Machine Learning (4341603)
N. Assessment-Rubrics
Present in
Watched other
practical session
Performed Performed students
but not
practical practical with performing
attentively
Engagement 5 him/her others help practical but not
participated in
self tried him/her self
performance
Work is submitted
Work done after
later than 1 week 2nd week but
Time 5 Completed Work submittedafter
but by the end of before the end
thework 3 week time
2ndweek of3rd week
within 1 week
Max 25 marks
43 | Page
Fundamentals of Machine Learning (4341603)
A. Objective: Effectively use sklearn library to make predictions using decision tree.
B. Expected Program Outcomes (POs):-PO1, PO2, PO3,PO6, PO7.
44 | Page
Fundamentals of Machine Learning (4341603)
45 | Page
Fundamentals of Machine Learning (4341603)
80:20 Ratio:-
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
df=pd.read_csv("music.csv")
#print(df)
input=df[['age','gender']]
output=df['genre']
#print('Input:-\n',input)
#print('Output:-\n',output)
input_array=input.to_numpy()
output_array=output.to_numpy()
#print('Input:-',input_array)
#print('Output:-,output_array)
input_train,input_test,output_train,output_test=train_test_split(input,output,test_size=0.2,random_state=42)
print('Input Training:-',input_train.shape)
print('Input Testing:-',input_test.shape)
print('Output Training:-',output_train.shape)
print('Output Testing:-',output_train.shape)
model=DecisionTreeClassifier()
model.fit(input_train,output_train)
new_data=pd.DataFrame({'age':[21,22],'gender':[1,0]})
predict=model.predict(new_data)
for i,predict in enumerate(predict):
print(f"{i+1}:{predict}")
y_prediction=model.predict(input_test)
accuracy=accuracy_score(output_test,y_prediction)
print(f"Accuracy:-",accuracy)
Output:-
70:30 Ratio:-
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
df=pd.read_csv("music.csv")
46 | Page
Fundamentals of Machine Learning (4341603)
#print(df)
input=df[['age','gender']]
output=df['genre']
#print('Input:-\n',input)
#print('Output:-\n',output)
input_array=input.to_numpy()
output_array=output.to_numpy()
#print('Input:-',input_array)
#print('Output:-,output_array)
input_train,input_test,output_train,output_test=train_test_split(input,output,test_size=0.3,random_state=42)
print('Input Training:-',input_train.shape)
print('Input Testing:-',input_test.shape)
print('Output Training:-',output_train.shape)
print('Output Testing:-',output_train.shape)
model=DecisionTreeClassifier()
model.fit(input_train,output_train)
new_data=pd.DataFrame({'age':[21,22],'gender':[1,0]})
predict=model.predict(new_data)
for i,predict in enumerate(predict):
print(f"{i+1}:{predict}")
y_prediction=model.predict(input_test)
accuracy=accuracy_score(output_test,y_prediction)
print(f"Accuracy:-",accuracy)
Output:-
47 | Page
Fundamentals of Machine Learning (4341603)
Calculations:
Calculate confusion matrix
48 | Page
Fundamentals of Machine Learning (4341603)
N. Assessment-Rubrics
Present in
Watched other
practical session
Performed Performed students
but not
practical practical with performing
attentively
Engagement 5 him/her others help practical but not
participated in
self tried him/her self
performance
49 | Page
Fundamentals of Machine Learning (4341603)
Work is submitted
Work done after
later than 1 week 2nd week but
Time 5 Completed Work submittedafter
but by the end of before the end
thework 3 week time
2ndweek of3rd week
within 1 week
Max 25 marks
50 | Page
Fundamentals of Machine Learning (4341603)
Practical No.8: Write a program to use a K-nearest neighbor it to predict class labels of test
data. Training and test data must be provided explicitly.
51 | Page
Fundamentals of Machine Learning (4341603)
1 1 0 1 0 1 0 1 0
1 0 0 1 1 1 0 1 0
1 0 0 1 0 1 1 1 0
0 1 1 1 1 0 0 0 1
1 0 1 1 1 1 1 1 0
0 1 1 0 1 1 0 1 1
Test Data: test.csv
0 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0
0 1 1 0 1 0 0 0
0 1 1 1 1 0 0 0
52 | Page
Fundamentals of Machine Learning (4341603)
80:20 Ratio:-
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
70:30 Ratio:-
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
53 | Page
Fundamentals of Machine Learning (4341603)
54 | Page
Fundamentals of Machine Learning (4341603)
55 | Page
Fundamentals of Machine Learning (4341603)
M. Assessment-Rubrics
Present in
Watched other
practical session
Performed Performed students
but not
practical practical with performing
attentively
Engagement 5 him/her others help practical but not
participated in
self tried him/her self
performance
Work is submitted
Work done after
later than 1 week 2nd week but
Time 5 Completed Work submittedafter
but by the end of before the end
thework 3 week time
2ndweek of3rd week
within 1 week
Max 25 marks
56 | Page
Fundamentals of Machine Learning (4341603)
57 | Page
Fundamentals of Machine Learning (4341603)
Output:-
58 | Page
Fundamentals of Machine Learning (4341603)
59 | Page
Fundamentals of Machine Learning (4341603)
M. Assessment-Rubrics
Present in
Watched other
practical session
Performed Performed students
but not
practical practical with performing
attentively
Engagement 5 him/her others help practical but not
participated in
self tried him/her self
performance
Work is submitted
Work done after
later than 1 week 2nd week but
Time 5 Completed Work submitted
but by the end of before the end
thework
2ndweek of3rd week after 3 week time
within 1 week
Max 25 marks
60 | Page
Fundamentals of Machine Learning (4341603)
61 | Page
Fundamentals of Machine Learning (4341603)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Customize pcot
plt.xlabel( ' sqft_lot' )
62 | Page
Fundamentals of Machine Learning (4341603)
plt.ylabel( 'price')
plt.title('House Price vs. Area')
Output:-
63 | Page
Fundamentals of Machine Learning (4341603)
64 | Page
Fundamentals of Machine Learning (4341603)
Program (d):-
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
65 | Page
Fundamentals of Machine Learning (4341603)
Output:-
66 | Page
Fundamentals of Machine Learning (4341603)
67 | Page
Fundamentals of Machine Learning (4341603)
M. Assessment-Rubrics
Present in
Watched other
practical session
Performed Performed students
but not
practical practical with performing
attentively
Engagement 5 him/her others help practical but not
participated in
self tried him/her self
performance
Work is submitted
Work done after
later than 1 week 2nd week but
Time 5 Completed Work submittedafter
but by the end of before the end
thework 3 week time
2ndweek of3rd week
within 1 week
Max 25 marks
68 | Page
Fundamentals of Machine Learning (4341603)
69 | Page
Fundamentals of Machine Learning (4341603)
Keep the workspace clean and organized, free from clutter and unnecessary
materials.
Use the software according to its intended purpose and instructions.
Ensure that all the necessary equipment and software are in good working
condition.
Never eat or drink in the lab, as it can cause contamination and create safety
hazards.
If any accidents or injuries occur, immediately notify the instructor and seek
medical attention if necessary.
J. Procedure to be followed/Source code (CE & IT software subjects):
Program:-
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# Generate random data points
np.random.seed(0)
X = np.random.rand(100, 2) # 100 points in 2D space
# Perform K-means clustering
k = 3 # Number of clusters
kmeans = KMeans(n_clusters=k)
kmeans.fit(X)
# Get the cluster labels and centroids
labels = kmeans.labels_
centroids = kmeans.cluster_centers_
# Plot the data points and clusters
plt.scatter(X[:, 0], X[:, 1], c=labels)
plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=150, c='red')
plt.title('K-means Clustering')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Output:-
70 | Page
Fundamentals of Machine Learning (4341603)
71 | Page
Fundamentals of Machine Learning (4341603)
M. Assessment-Rubrics
Present in
Watched other
practical session
Performed Performed students
but not
practical practical with performing
attentively
Engagement 5 him/her others help practical but not
participated in
self tried him/her self
performance
Work is submitted
Work done after
later than 1 week 2nd week but
Time 5 Completed Work submittedafter
but by the end of before the end
thework 3 week time
2ndweek of3rd week
within 1 week
Max 25 marks
72 | Page
Fundamentals of Machine Learning (4341603)
73 | Page
Fundamentals of Machine Learning (4341603)
Program(a):-
from sklearn.datasets import load_iris
# Load the Iris dataset
iris = load_iris()
# Get the data and target
X = iris.data
y = iris.target
# Print the shape of the dataset
print("Number of rows:", X.shape[0])
print("Number of columns:", X.shape[1])
Output:-
74 | Page
Fundamentals of Machine Learning (4341603)
Program(b):-
from sklearn.datasets import load_iris
Output:-
Program(c):-
import pandas as pd
from sklearn.datasets import load_iris
75 | Page
Fundamentals of Machine Learning (4341603)
Output:-
Program(d):-
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
76 | Page
Fundamentals of Machine Learning (4341603)
Program(f):-
import seaborn as sns
import pandas as pd
from sklearn.datasets import load_iris
77 | Page
Fundamentals of Machine Learning (4341603)
Output:-
Program(g):-
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
Output:-
78 | Page
Fundamentals of Machine Learning (4341603)
Program(h):-
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.cluster import KMeans
from sklearn.metrics import accuracy_score
# Compare accuracies
print("K-NN Accuracy:", knn_accuracy)
print("K-means Accuracy:", kmeans_accuracy)
Output:-
79 | Page
Fundamentals of Machine Learning (4341603)
80 | Page
Fundamentals of Machine Learning (4341603)
N. Assessment-Rubrics
Present in
Watched other
practical session
Performed Performed students
but not
practical practical with performing
5 attentively
Engagement him/her others help practical but not
participated in
self tried him/her
performance
self
Work is submitted
Work done after
later than 1 week 2nd week but
Time 5 Completed Work submittedafter
but by the end of before the end
thework 3 week time
2ndweek of3rd week
within 1 week
Max 25 marks
81 | Page