ML Lab Manual-It
ML Lab Manual-It
MACHINE LEARNING
LAB MANUAL
Semester Regulation-
R22
A.Y: 2024-25
Prepared by:
MRS.KARIMUNNISA. SHAIK,
ASSISTANT PROFESSOR
This is to certify that this manual is a bonafide record of practical work in the
“MACHINE LEARNING” in III B.Tech II Sem (IT) program during the academicyear 2024-
25. This manual is prepared by Mrs.Karimunnisa shaik, Assistant Professor, IT.
PREFACE
This Lab Manual entitled “Machine Learning Lab” is intended for the use of III B. Tech II Semester
Information Technology students of Marri Laxman Reddy Institute of Technology and Management,
Dundigal, Hyderabad. The main objective of the Machine Learning Lab manual is to introduce the
concepts of operating systems, designing principles of operating systems and implementation of
machine learning.
By
Karimunnisa shaik
Department of IT
ACKNOWLEDGEMENT
It was really a good experience, working with “MACHINE LEARNING LAB”. First,
we would like to thank Dr. M. Nagalakshmi , Professor, HOD of Department of Information
Technology and , Marri Laxman Reddy Institute of Technology & Management for his
concern and giving the technical support in preparing the document. We are deeply indebted
and gratefully acknowledge the constant support and valuable patronage of Dr. P. SRIDHAR,
Director, Marri Laxman Reddy Institute of technology & Management for giving us this
wonderful opportunity for preparing the “MACHINE LEARNING LAB” laboratory manual.
We express our hearty thanks to Dr. R. Murali Prasad, Principal, Marri Laxman Reddy
Institute of technology & Management, for timely corrections and scholarly guidance. At last,
but not the least I would like to thanks the entire IT faculties those who had inspired and
helped us to achieve our goal.
By
KARIMUNNISA SHAIK
Assistant Professor
GENERAL INSTRUCTIONS
1. Students are instructed to come to Machine Learning laboratory on time. Late comers are not
entertained in the lab.
2. Students should be punctual to the lab. If not ,the conducted experiments will not be repeated.
3. Students are expected to come prepared at home with the experiments which are going to be
performed.
4. Students are instructed to display their identity cards before entering into the lab.
6. Any damage/loss of system parts like keyboard, mouse during the lab session, it is student’s
responsibility and penalty or fine will be collected from the student.
7. Students should update the records and lab observation books session wise. Beforeleaving the lab
the student should get his/her lab observation book signed by the faculty.
8. Students should submit the lab records by the next lab to the concerned faculty members in the staff
room for their correction and return.
9. Students should not move around the lab during the lab session.
10. If any emergency arises, the student should take the permission from facultymember
concerned in written format.
11. The faculty members may suspend any student from the lab session on disciplinary grounds.
12. Never copy the output from other students. Write down your own outputs.
INSTITUTION VISION AND MISSION
VISION
To be as an ideal academic institution by graduating talented engineers to be ethically strong,
competent with quality research and technologies.
MISSION
To fulfill the promised vision through the following strategic characteristics and aspirations:
Utilize rigorous educational experiences to produce talented engineers.
Create an atmosphere that facilitates the success of students.
Programs that integrate global awareness, communication skills and
Leadership qualities.
Education and Research partnership with institutions and industries to
prepare the students for interdisciplinary research.
DEPARTMENT VISION AND MISSION
VISION
To empower the students to be technologically adept, innovative, self-motivated and responsible
global citizen possessing human values and contribute significantly towards high quality
technical education with ever changing world.
MISSION
Learn and Integrate: Graduates shall apply knowledge to solve computer science
and allied engineering problems with continuous learning.
• Think and Create: Graduates are inculcated with a passion towards higher education
and research with social responsibility.
The Program Outcomes (POs) of the department are defined in a way that the Graduate
Attributes are included, which can be seen in the Program Outcomes (POs) defined.
Program Outcomes (POs) department are as stated below:
inmultidisciplinary settings.
j: An ability to communicate effectively on complex engineering activities within the
engineering community.
k : Ability to demonstrate and understanding of the engineering and management principles
as a member and leader in a team.
l : Ability to engage in independent and lifelong learning in the context of technological
change.
MACHINE LEARNING LAB
COURSE STRUCTURE:
COURSE OBJECTIVES:
To get an overview of the various Machine Learning Techniques and can able to
Demonstrate them using Python.
COURSE OUTCOMES:
EXPERIMENT -1
AIM: The probability that it is Friday and that a student is absent is 3 %. Since there are 5
school days in a week, the probability that it is Friday is 20 %. What is the probability that a
student is absent given that today is Friday? Apply Baye’s rule in python to get the result.
(Ans: 15%)
ALGORITHM:
Step 1: Calculate probability for each word in a text and filter the words which have a probability
less than threshold probability. Words with probability less than threshold probability are irrelevant.
Step 2: Then for each word in the dictionary, create a probability of that word being in insincere
questions and its probability insincere questions. Then finding the conditional probability to use in
naive Bayes classifier.
Step 3: Prediction using conditional probabilities.
Step 4: End.
SOURCE CODE:
OUTPUT:
VIVA QUESTIONS
10.Given the following statistics, what is the probability that a woman has cancer if she has a
positive result?
MACHINE LEARNING LAB
EXPERIMENT – 2
SOURCE CODE:
Import mysql .connector
Myconn=mysql.connector.connect(host=”localhost”,user=”root”,passwd=””,database=”SamplDB”)
Cur=myconn.cursor( )
Cur.execute(“select * from students”)
Result = cur.fetchall( )
Print(“student Details are:”) For x
in result:
Print (x);
myconn.commit( )
myconn.close( )
MACHINE LEARNING LAB
OUTPUT:
MACHINE LEARNING LAB
VIVA QUESTIONS
1. What is MySQL Connector/Python?
2. What are the five major steps for connecting MySQL and Python?
3. How do we create a connection object?
4. How do we create a cursor object?
5. How do we execute SQL query through Python?
6. What is the difference between fetchall() and fetchnone() methods?
7. What is the purpose of rowcount parameter?
8. Which method is used to establish a connection to a database using sqlite3 in Python?
9. Which method is used to execute an SQL query and fetch all the results in Python’s database
interaction?
10. Which method is used to close the cursor in Python’s database interaction?
MACHINE LEARNING LAB
EXPERIMENT – 3
ALGORITHM
1. Initialize h to the most specific hypothesis in H
2. For each positive training instance x For each attribute constraint a, in
h If the constraint a, is satisfied by x Then do nothing
Else replace a, in h by the next more general constraint that is satisfied by x
Output hypothesis h.
3. Hypothesis Construction
SOURCE CODE:
import csv
# Initialize an empty list to hold the data a =
[]
# Open and read the CSV file
with open('FIND-S.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
num_attribute = len(a[0]) - 1
# Initialize the hypothesis with '0' (assuming all attributes are '0')
hypothesis = ['0'] * num_attribute
print("\nThe initial hypothesis is:")
print(hypothesis)
OUTPUT:
MACHINE LEARNING LAB
VIVA QUESTIONS
1. What is present in the version space of the Find-S algorithm in the beginning?
2. When does the hypothesis change in the Find-S algorithm, while iteration?
EXPERIMENT: 4
TRAINING DATABASE
ALGORITHM
SOURCE CODE:
import csv
OUTPUT:
MACHINE LEARNING LAB
VIVA QUESTIONS:
1. The algorithm is trying to find a suitable day for swimming. What is the most general hypothesis?
5. Python supports the creation of anonymous functions at runtime, using a construct called?
8. Let G be the set of maximally general hypotheses. While iterating through the dataset,
EXPERIMENT: 5
SOURCE CODE:
import pandas as pd
import numpy as np
import math
df = pd.read_excel(file_path)
label_encoders = {}
le = LabelEncoder()
df[column] = le.fit_transform(df[column])
label_encoders[column] = le
X = df.drop('Level', axis=1) # Drop the 'Level' column to use the rest as features
clf.fit(X_train, y_train)
python
Copy code
y_pred = clf.predict(X_test)
def calculate_entropy(y):
MACHINE LEARNING LAB
class_counts = np.bincount(y)
probabilities = class_counts /
len(y)
parent_entropy =
calculate_entropy(y) left_split =
return 0
calculate_entropy(right_split)
first_feature_index = clf.tree_.feature[0]
first_threshold = clf.tree_.threshold[0]
first_feature_name = X.columns[first_feature_index]
first_split_entropy = calculate_entropy(y_train)
{first_split_ig}")
python
Copy code
MACHINE LEARNING LAB
plt.figure(figsize=(15, 10))
MACHINE LEARNING LAB
rounded=True)
plt.show()
OUTPUT:
MACHINE LEARNING LAB
VIVA QUESTIONS:
2. Given the entropy for a split, e split = 0.39 and the entropy before the split, e before = What is the
9. what is purning?
EXPERIMENT – 6
SOURCE CODE
import numpy as np
from sklearn import datasets import
matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
np.random.seed(42)
indices = np.random.permutation(len(data))
n_training_samples = 12
test_data = data[indices[-n_training_samples:]]
test_labels = labels[indices[-n_training_samples:]]
fig = plt.figure()
MACHINE LEARNING LAB
ax = fig.add_subplot(111, projection='3d')
plt.show()
OUTPUT:
MACHINE LEARNING LAB
MACHINE LEARNING LAB
VIVA QUESTIONS
1. How does KNN deal with missing data?
EXPERIMENT -7
AIM: GIVEN THE FOLLOWING DATA, WHICH SPECIFY CLASSIFICATIONS FOR NINE
COMBINATIONS OF VAR1 AND VAR2 PREDICT A CLASSIFICATION FOR A CASE WHERE
VAR1=0.906 AND VAR2=0.606, USING THE RESULT K- MEANS CLUSTERING WITH 3
MEANS (I.E., 3 CENTROIDS)
VAR1 VAR2 CLASS
1.713 1.586 0
0.180 1.786 1
0.353 1.240 1
0.940 1.566 0
1.486 0.759 1
1.266 1.106 0
1.540 0.419 1
0.459 1.799 1
0.773 0.186 1
SOURCE CODE:
import numpy as np
from sklearn.cluster import KMeans
OUTPUT:
MACHINE LEARNING LAB
VIVA QUESTIONS
EXPERIMENT - 8
SOURCE CODE:
import numpy as np #
Define the dataset
data = np.array([
['medium', 'skiing', 'design', 'single', 'twenties', 'no', 'highRisk'],
['high', 'golf', 'trading', 'married', 'forties', 'yes', 'lowRisk'],
['low', 'speedway', 'transport', 'married', 'thirties', 'yes', 'medRisk'],
['medium', 'football', 'banking', 'single', 'thirties', 'yes', 'lowRisk'],
['high', 'flying', 'media', 'married', 'fifties', 'yes', 'highRisk'],
['low', 'football', 'security', 'single', 'twenties', 'no', 'medRisk'],
['medium', 'golf', 'media', 'single', 'thirties', 'yes', 'medRisk'],
['medium', 'golf', 'transport', 'married', 'forties', 'yes', 'lowRisk'],
['high', 'skiing', 'banking', 'single', 'thirties', 'yes', 'highRisk'],
['low', 'golf', 'unemployed', 'married', 'forties', 'yes', 'highRisk']
])
MACHINE LEARNING LAB
recreation_column = data[:, 1]
status_column = data[:, 3]
label_column = data[:, 6]
OUTPUT:
MACHINE LEARNING LAB
VIVA QUESTIONS
EXPERIMENT - 9
# Sample data
X = np.array([1, 2, 4, 3, 5])
y = np.array([1, 3, 3, 2, 5])
# Mean of X and y
X_mean = np.mean(X)
y_mean = np.mean(y)
plt.legend()
plt.show()
OUTPUT:
MACHINE LEARNING LAB
VIVA QUESTIONS
1. What Is Regression?
5. Can we solve the multiclass classification problems using Logistic Regression? If Yes thenHow?
6. The correlation for the values of two variables moving in the same direction is
EXPERIMENT - 10
model.fit(X_train, y_train)
OUTPUT:
MACHINE LEARNING LAB
VIVA QUESTIONS
1. Naïve Bayes classifier algorithms are mainly used in text classification?
2. What is the formula for Bayes’ theorem? Where (A & B) and (H & E) are events and P(B), P(H) &
P(E) ≠ 0.
5. here are two boxes. The first box contains 3 white and 2 red balls whereas the second contains 5
white and 4 red balls. A ball is drawn at random from one of the two boxes and is found to be
white. Find the probability that the ball was drawn from the second box?
EXPERIMENT – 11
SOURCE CODE:
import random import
numpy as np
# Parameters population_size =
10
chromosome_length = 6 # Binary representation with 6 bits
max_generations = 50
mutation_rate = 0.01
# Mutation
def mutate(individual):
for i in range(len(individual)):
if random.random() < mutation_rate:
individual[i] = 1 - individual[i] # Flip bit
return individual
# Apply crossover
child1, child2 = crossover(parent1, parent2)
# Apply mutation
child1 = mutate(child1)
child2 = mutate(child2)
OUTPUT:
MACHINE LEARNING LAB
VIVA QUESTIONS
EXPERIMENT -12
AIM: IMPLEMENT THE FINITE WORDS CLASSIFICATION SYSTEM USING BACK- PROPAGATION
ALGORITHM
SOURCE CODE:
import numpy as np
# Word dataset with feature vectors and labels (manually created embeddings) #
Features: [Length of word, Number of vowels, Frequency of letter 'e', etc.]
word_data = np.array([
[5, 2, 1], # apple (fruit)
[6, 3, 1], # orange (fruit)
[3, 1, 0], # dog (animal)
[5, 2, 0], # tiger (animal)
[6, 2, 1], # table (object)
[4, 1, 0], # book (object)
])
# Labels (fruit = [1, 0, 0], animal = [0, 1, 0], object = [0, 0, 1]) labels
= np.array([
[1, 0, 0], # fruit
[1, 0, 0], # fruit
[0, 1, 0], # animal
[0, 1, 0], # animal
[0, 0, 1], # object
[0, 0, 1], # object
MACHINE LEARNING LAB
])
# Initialize parameters
input_size = word_data.shape[1] # Number of input features
hidden_size = 4 # Number of neurons in the hidden layer
output_size = labels.shape[1] # Number of output categories (3 in this case)
learning_rate = 0.5
epochs = 10000 # Number of iterations for training
# Calculate error
error = labels - final_output
# Backpropagation phase
d_output = error * sigmoid_derivative(final_output)
error_hidden_layer = d_output.dot(weights_hidden_output.T)
d_hidden_layer = error_hidden_layer * sigmoid_derivative(hidden_output)
return final_output
OUTPUT:
MACHINE LEARNING LAB
VIVA QUESTIONS
1. What is backpropagation?
4. Can we have the same bias for all neurons of a hidden layer?
6. In a neural network, what if all the weights are initialized with the same value?