0% found this document useful (0 votes)
5 views2 pages

Advml Lab

This document contains a Python script that implements the K-Nearest Neighbors (KNN) algorithm using the Iris dataset. It splits the data into training and test sets, evaluates the model's accuracy for different values of K, and visualizes the results with a plot. The script utilizes libraries such as scikit-learn, NumPy, and Matplotlib.

Uploaded by

shiva
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)
5 views2 pages

Advml Lab

This document contains a Python script that implements the K-Nearest Neighbors (KNN) algorithm using the Iris dataset. It splits the data into training and test sets, evaluates the model's accuracy for different values of K, and visualizes the results with a plot. The script utilizes libraries such as scikit-learn, NumPy, and Matplotlib.

Uploaded by

shiva
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/ 2

# Import necessary modules

from sklearn.neighbors import KNeighborsClassifier

from sklearn.model_selection import train_test_split

from sklearn.datasets import load_iris

import numpy as np

import matplotlib.pyplot as plt

irisData = load_iris()

# Create feature and target arrays

X = irisData.data

y = irisData.target

# Split into training and test set

X_train, X_test, y_train, y_test = train_test_split(

X, y, test_size = 0.2, random_state=42)

neighbors = np.arange(1, 9)

train_accuracy = np.empty(len(neighbors))

test_accuracy = np.empty(len(neighbors))

# Loop over K values

for i, k in enumerate(neighbors):

knn = KNeighborsClassifier(n_neighbors=k)

knn.fit(X_train, y_train)

# Compute training and test data accuracy


train_accuracy[i] = knn.score(X_train, y_train)

test_accuracy[i] = knn.score(X_test, y_test)

# Generate plot

plt.plot(neighbors, test_accuracy, label = 'Testing dataset Accuracy')

plt.plot(neighbors, train_accuracy, label = 'Training dataset Accuracy')

plt.legend()

plt.xlabel('n_neighbors')

plt.ylabel('Accuracy')

plt.show()

You might also like