0% found this document useful (0 votes)
15 views7 pages

Aiml Prac 6-12

This document contains code for implementing several machine learning algorithms to classify the iris dataset, including k-nearest neighbors, decision trees, and random forests. It includes code to load and preprocess the iris data, train models using each algorithm, make predictions on test data, and evaluate accuracy. Visualizations are also generated for the decision trees and random forest classifiers.

Uploaded by

G IND
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)
15 views7 pages

Aiml Prac 6-12

This document contains code for implementing several machine learning algorithms to classify the iris dataset, including k-nearest neighbors, decision trees, and random forests. It includes code to load and preprocess the iris data, train models using each algorithm, make predictions on test data, and evaluate accuracy. Visualizations are also generated for the decision trees and random forest classifiers.

Uploaded by

G IND
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
You are on page 1/ 7

MADHUB EN & BHANU BHAI PATEL INSTITUTE OF TECHNOLOGY

( A CONSTITU ENT CO L LEGE OF CVM UNIVERSITY)

Practical-6
AIM : Write a program to implement k-Nearest Neighbor algorithm
to classify the iris data set. Print both correct and wrong predictions.

Code :
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

iris = load_iris()
print("Features:", iris.feature_names)
print("Labels:", iris.target_names)
print("Dataset size:", iris.data.shape)

X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2,


random_state=42)

knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)

predictions = knn.predict(X_test)
print("\nPredicted labels:", predictions)
print("Actual labels: ", y_test)
print("Accuracy:", accuracy_score(y_test, predictions))
print("\nDetailed Prediction Results:")
for i, (pred, actual) in enumerate(zip(predictions, y_test)):
if pred == actual:
print(f"Sample {i}: Correct Prediction (Class {iris.target_names[pred]})")
else:

11 | P a g
KASHISH DARJI
MADHUB EN & BHANU BHAI PATEL INSTITUTE OF TECHNOLOGY
( A CONSTITU ENT CO L LEGE OF CVM UNIVERSITY)

print(f"Sample {i}: Wrong Prediction (Predicted: {iris.target_names[pred]},


Actual: {iris.target_names[actual]})")

OUTPUT :-

12 | P a g
KASHISH DARJI
MADHUB EN & BHANU BHAI PATEL INSTITUTE OF TECHNOLOGY
( A CONSTITU ENT CO L LEGE OF CVM UNIVERSITY)

Practical – 7
AIM : -Write a program to demonstrate the working of the decision tree
based ID3 algorithm. Use an appropriate data set for building the decision
tree and apply this knowledge to classify a new sample.e.

Code:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

from sklearn.tree import DecisionTreeClassifier, plot_tree


from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt

data = load_iris()
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3, random_state=42)
clf = DecisionTreeClassifier(criterion='entropy', random_state=42)
clf.fit(X_train, y_train)

predictions = clf.predict(X_test)
print("Accuracy:",accuracy_score(y_test,predictions)
plt.figure(figsize=(12, 8))
plot_tree(clf,feature_names=data.feature_names,
class_names=data.target_names, filled=True)
plt.show()

13 | P a g
KASHISH DARJI
MADHUB EN & BHANU BHAI PATEL INSTITUTE OF TECHNOLOGY
( A CONSTITU ENT CO L LEGE OF CVM UNIVERSITY)

OUTPUT :-

14 | P a g
KASHISH DARJI
MADHUB EN & BHANU BHAI PATEL INSTITUTE OF
TECHNOLOGY

Practical – 8
AIM :- Write a program to classify IRIS data using Random forest
classifier.
CODE :
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
import numpy as np
iris = load_iris()
X = iris.data
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,


random_state=42)

rf_classifier = RandomForestClassifier(n_estimators=100, random_state=42)

rf_classifier.fit(X_train, y_train)
predictions = rf_classifier.predict(X_test)

accuracy = accuracy_score(y_test, predictions)


print("Accuracy:", accuracy)
n_classes = len(iris.target_names)
plot_colors = "ryb"
plt.figure(figsize=(8, 6))

20 | P a g
KASHISH DARJI
MADHUB EN & BHANU BHAI PATEL INSTITUTE OF
TECHNOLOGY

for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]):
X = iris.data[:, pair]
y = iris.target
rf_classifier.fit(X, y)

plt.subplot(2, 3, pairidx + 1)
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),
np.arange(y_min, y_max, 0.1))

Z = rf_classifier.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.contourf(xx, yy, Z, alpha=0.8)


for i, color in zip(range(n_classes), plot_colors):
idx = np.where(y == i)
plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i],
cmap=plt.cm.RdYlBu, edgecolor='black', s=15)

plt.suptitle("Decision surfaces of a random forest")


plt.legend(loc='lower right', borderpad=0, handletextpad=0)
plt.axis("tight")
plt.show()

21 | P a g
KASHISH DARJI
MADHUB EN & BHANU BHAI PATEL INSTITUTE OF
TECHNOLOGY

OUTPUT :-

22 | P a g
KASHISH DARJI

You might also like