Machine Learning Lab Manual - Record
Machine Learning Lab Manual - Record
Learning Lab
Date: Experiment :1
1. 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 theprobability 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.
PROGRAM:
OUTPUT:
Result: -
Machine Learning Lab
Experiment:2
Date:
ALGORITHM:
PROCEDURE
We need to install mysql-connector to connect Python with MySQL. You can use the below command to install
this in your system.
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="myDB"
)
Machine Learning Lab
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM MyGuests")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
OUTPUT:
Machine Learning Lab
OUTPUT SCREENS:
Excel Format: CSV
Format:
Result: -
Machine Learning Lab
Experiment:3
Date:
ALGORITHM:
PROGRAM
iris = datasets.load_iris()
data = iris.data labels =
iris.target
np.random.seed(42)
indices = np.random.permutation(len(data))
n_training_samples = 12
learn_data = data[indices[:-n_training_samples]] learn_labels
= labels[indices[:-n_training_samples]]
Machine Learning Lab
n_training_samples:]]
#The following code is only necessary to visualize the data of our learnset import
matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
colours = ("r", "b") X = [] for iclass in
range(3):
X.append([[], [], []]) for i in
range(len(learn_data)): if
learn_labels[i] == iclass:
X[iclass][0].append(learn_data[i][0])
X[iclass][1].append(learn_data[i][1])
X[iclass][2].append(sum(learn_data[i][2:]))
Machine Learning Lab
for i in range(5):
neighbors = get_neighbors(learn_data, learn_labels, test_data[i], 3, distance=distance)
print("Index: ",i,'\n',
"Testset Data: ",test_data[i],'\n',
"Testset Label: ",test_labels[i],'\n',
"Neighbors: ",neighbors,'\n')
OUTPUT:
Machine Learning Lab
Result: -
Machine Learning Lab
Experiment 4
Date:
ALGORITHM:
PROGRAM:
# printing values
print('Slope:' ,regression_model.coef_)
print('Intercept:', regression_model.intercept_)
Machine Learning Lab
print('Root mean squared error: ', rmse) print('R2 score: ', r2)
OUTPUT:
Result: -
Machine Learning Lab
Experiment 5
Date:
ALGORITHM:
PROGRAM:
#Read DataSet df =
datasets.load_iris() x =
df.data
y = df.target
print(x)
print(y)
kmeans5 = KMeans(n_clusters=5)
y_kmeans5 = kmeans5.fit_predict(x)
print(y_kmeans5)
print(kmeans5.cluster_centers_)
plt.title('Elbow method')
plt.xlabel('No of clusters')
plt.ylabel('Error')
plt.show()
print(kmeans3.cluster_centers_)
OUTPUT:
Machine Learning Lab
Result: -
Machine Learning Lab
Machine Learning Lab
Machine Learning Lab
E.g. The first transformed row is [0 1 1 1 0 0 1 0 1] and the unique vocabulary is [‘and’, ‘document’,
‘first’, ‘is’, ‘one’, ‘second’, ‘the’, ‘third’, ‘this’], thus this means that the words “document”, “first”, “is”,
“the” and “this” appeared 1 time each in the initial text string (i.e. ‘This is the first document.’).
In our example, we will convert the collection of text documents (train and test sets) into a matrix of token
counts.
To implement that text transformation we will use the make_pipeline function. This will internally transform
the text data and then the model will be fitted using the transformed data.
Source Code
print("NAIVE BAYES ENGLISH TEST CLASSIFICATION")
print(np.array(test_data.target_names)[predicted_categories])
Machine Learning Lab
Machine Learning Lab
OUTPUT:
Machine Learning Lab
Given a target string, the goal is to produce target string starting from a random string of the same length. In the
following implementation, following analogies are made –
• Characters A-Z, a-z, 0-9 and other special symbols are considered as genes
• A string generated by these character is considered as chromosome/solution/Individual
Fitness score is the number of characters which differ from characters in target string at a particular index. So
individual having lower fitness value is given more preference.
Source Code
# Python3 program to create target string, starting from #
random string using Genetic Algorithm
import random
# Valid genes
GENES = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP QRSTUVWXYZ
1234567890, .-;:_!"#%&/()=?@${[]}'''
class Individual(object):
'''
Class representing individual in population '''
def init (self, chromosome): self.chromosome =
chromosome
self.fitness = self.cal_fitness()
@classmethod def
mutated_genes(self):
'''
create random genes for mutation
'''
global GENES
gene = random.choice(GENES)
return gene
@classmethod def
create_gnome(self):
'''
create chromosome or string of genes
'''
global TARGET
Machine Learning Lab
gnome_len = len(TARGET)
return [self.mutated_genes() for _ in range(gnome_len)]
# random probability
prob = random.random()
def cal_fitness(self):
''' Calculate fittness score, it is the number of
characters in string which differ from target string. '''
global TARGET
fitness = 0 for gs, gt in zip(self.chromosome,
TARGET):
if gs != gt: fitness+= 1
return fitness
found = False
population = []
OUTPUT:
Result: -
Machine Learning Lab
def sigmoid(sop):
return 1.0/(1+numpy.exp(-1*sop))
def sigmoid_sop_deriv(sop):
return sigmoid(sop)*(1.0-sigmoid(sop))
def sop_w_deriv(x):
return x
x1=0.1 x2=0.4
target = 0.7
learning_rate = 0.01
w1=numpy.random.rand() w2=numpy.random.rand()
predicted_output = []
network_error = []
old_err = 0 for k in
range(80000): # Forward Pass
y = w1*x1 + w2*x2 predicted
= sigmoid(y) err =
error(predicted, target)
predicted_output.append(predicted)
network_error.append(err) #
Backward Pass
Machine Learning Lab
g1 = error_predicted_deriv(predicted, target)
g2 = sigmoid_sop_deriv(y)
#print(predicted)
plt.figure()
plt.plot(network_error)
plt.title("Iteration Number vs Error") plt.xlabel("Iteration
Number")
plt.ylabel("Error")
plt.show()
plt.figure()
plt.plot(predicted_output)
plt.title("Iteration Number vs Prediction") plt.xlabel("Iteration
Number")
plt.ylabel("Prediction")
plt.show()
Machine Learning Lab
OUTPUT:
Initial W : 0.08698924153243281 0.4532713230157145
Result: -
Machine Learning Lab
Experiment 9
Date:
Training Database
Algorithm
Hypothesis Construction
Machine Learning Lab
OUTPUT:
Result: -
Machine Learning Lab
Experiment 10
Date:
Training Database
Algorithm
Machine Learning Lab
Source Code:
import csv
with open("enjoysport.csv") as f:
csv_file=csv.reader(f)
data=list(csv_file)
print(data)
print(" ------------------- ")
s=data[1][:-1] #extracting one row or instance or record
g=[['?' for i in range(len(s))] for j in range(len(s))]
print(s)
print(" ------------------- ")
print(g)
print(" ------------------- ")
for i in data:
if i[-1]=="TRUE": # For each positive training record or instance
for j in range(len(s)):
if i[j]!=s[j]:
s[j]='?'
g[j][j]='?'
OUTPUT:
Result: -