Professional Documents
Culture Documents
AIML Lab Prog
AIML Lab Prog
AIML Lab Prog
Write a program to implement k-nearest neighbor algorithm to classify the iris data set
print both correct and wrong predictions.
import numpy as np
import pandas as pd
X = dataset.iloc[:, :-1]
y = dataset.iloc[:, -1]
print(X.head())
ypred = classifier.predict(Xtest)
i=0
print ("\n-------------------------------------------------------------------------")
print ("-------------------------------------------------------------------------")
if (label == ypred[i]):
else:
i=i+1
print ("-------------------------------------------------------------------------")
print ("-------------------------------------------------------------------------")
print ("-------------------------------------------------------------------------")
print ("-------------------------------------------------------------------------")
Output:
2. Develop a program to apply K-means algorithm to cluster a set of data stored in .CSV file.
Use the same data set for clustering using EM algorithm. Compare the results of these two
algorithms and comment on the quality of clustering.
dataset=load_iris()
X=pd.DataFrame(dataset.data)
X.columns=['Sepal_Length','Sepal_Width','Petal_Length','Petal_Width']
y=pd.DataFrame(dataset.target)
y.columns=['Targets']
# print(X)
plt.figure(figsize=(14,7))
colormap=np.array(['red','lime','black'])
# REAL PLOT
plt.subplot(1,3,1)
plt.scatter(X.Petal_Length,X.Petal_Width,c=colormap[y.Targets],s=40)
plt.title('Real')
# K-PLOT
plt.subplot(1,3,2)
model=KMeans(n_clusters=3)
model.fit(X)
predY=np.choose(model.labels_,[0,1,2]).astype(np.int64)
plt.scatter(X.Petal_Length,X.Petal_Width,c=colormap[predY],s=40)
plt.title('KMeans')
# GMM PLOT
scaler=preprocessing.StandardScaler()
scaler.fit(X)
xsa=scaler.transform(X)
xs=pd.DataFrame(xsa,columns=X.columns)
gmm=GaussianMixture(n_components=3)
gmm.fit(xs)
y_cluster_gmm=gmm.predict(xs)
plt.subplot(1,3,3)
plt.scatter(X.Petal_Length,X.Petal_Width,c=colormap[y_cluster_gmm],s=40)
plt.title('GMM Classification')
Output:
3. Implement the non-parametric Locally Weighted Regression algorithm in order to fit data
points. Select appropriate data set for your experiment and draw graphs
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
m= np.shape(mbill)[1]
one = np.mat(np.ones(m))
X = np.hstack((one.T,mbill.T))
#set k here
ypred = localWeightRegression(X,mtip,0.5)
SortIndex = X[:,1].argsort(0)
xsort = X[SortIndex][:,0]
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(bill,tip, color='green')
ax.plot(xsort[:,1],ypred[SortIndex], color = 'red', linewidth=5)
plt.xlabel('Total bill')
plt.ylabel('Tip')
plt.show();
OUTPUT:
4. Build an Artificial Neural Network by implementing the Backpropagation algorithm and test the
same using appropriate data sets.
import random
# Initialize a network
network = list()
network.append(hidden_layer)
network.append(output_layer)
i= 1
j=j+1
i=i+1
return network
activation = weights[-1]
for i in range(len(weights)-1):
return activation
def transfer(activation):
inputs = row
new_inputs = []
neuron['output'] = transfer(activation)
new_inputs.append(neuron['output'])
inputs = new_inputs
return inputs
for i in reversed(range(len(network))):
layer = network[i]
errors = list()
if i != len(network)-1:
for j in range(len(layer)):
error = 0.0
errors.append(error)
else:
for j in range(len(layer)):
neuron = layer[j]
errors.append(expected[j] - neuron['output'])
for j in range(len(layer)):
neuron = layer[j]
for i in range(len(network)):
inputs = row[:-1]
if i != 0:
inputs = [neuron['output'] for neuron in network[i - 1]]
for j in range(len(inputs)):
sum_error = 0
expected[row[-1]] = 1
backward_propagate_error(network, expected)
seed(2)
dataset = [[2.7810836,2.550537003,0],
[1.465489372,2.362125076,0],
[3.396561688,4.400293529,0],
[1.38807019,1.850220317,0],
[3.06407232,3.005305973,0],
[7.627531214,2.759262235,1],
[5.332441248,2.088626775,1],
[6.922596716,1.77106367,1],
[8.675418651,-0.242068655,1],
[7.673756466,3.508563011,1]]
n_inputs = len(dataset[0]) - 1
#Network Initialization
i= 1
j=1
j=j+1
i=i+1
Output:
Number of Inputs :
2
Number of Outputs :
2
Layer[1] Node[1]:
{'weights': [0.4560342718892494, 0.4478274870593494,
-0.4434486322731913]}
Layer[1] Node[2]:
{'weights': [-0.41512800484107837, 0.33549887812944956,
0.2359699890685233]}
Layer[2] Node[1]:
{'weights': [0.1697304014402209, -0.1918635424108558,
0.10594416567846243]}
Layer[2] Node[2]:
{'weights': [0.10680173364083789, 0.08120401711200309,
-0.3416171297451944]}
Layer[1] Node[2]:
{'weights': [-1.2934302410111027, 1.7109363237151511,
0.7125327507327331], 'output': 0.04760703296164143, 'delta':
-0.005928559978815065}
Layer[2] Node[1]:
{'weights': [-1.3098359335096292, 2.16462207144596,
-0.3079052288835877], 'output': 0.1989556395205846, 'delta':
-0.03170801648036036}
Layer[2] Node[2]:
{'weights': [1.5506793402414165, -2.11315950446121,
0.1333585709422027], 'output': 0.8095042653312078, 'delta':
0.029375796661413225}
5. Demonstrate Genetic algorithm by taking a suitable data for any simple application.
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
gnome_len = len(TARGET)
return [self.mutated_genes() for _ in range(gnome_len)]
# random probability
prob = random.random()
def cal_fitness(self):
'''
Calculate fitness 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
# Driver code
def main():
global POPULATION_SIZE
#current generation
generation = 1
found = False
population = []
population = new_generation
generation += 1
if __name__ == '__main__':
main()
Output: