0% found this document useful (0 votes)
5 views

Supervised Learning

Uploaded by

hexagonsih
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Supervised Learning

Uploaded by

hexagonsih
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

For supervised learning the following program

Program

import numpy as np

import matplotlib.pyplot as plt

import pandas as pd

url="https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"

names=['sepal-length','sepal-width','petal-length','petal-width','Class']

dataset=pd.read_csv(url,names=names)

X = dataset.iloc[:, :-1].values

y = dataset.iloc[:, 4].values

from sklearn.neighbors import KNeighborsClassifier

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)

from sklearn.preprocessing import LabelEncoder

from matplotlib.colors import ListedColormap

# Encode the class labels as integers

label_encoder = LabelEncoder()

y_encoded = label_encoder.fit_transform(y)

# Use only the first two features for a 2D decision boundary plot

X_two_features = X[:, :2]

X_train_2D, X_test_2D, y_train_2D, y_test_2D = train_test_split(X_two_features, y_encoded,


test_size=0.20, random_state=42)

# Fit KNN model on 2D data

knn_2D = KNeighborsClassifier(n_neighbors=5)

knn_2D.fit(X_train_2D, y_train_2D)

# Create a mesh grid for plotting the decision boundary

h = .02
x_min, x_max = X_two_features[:, 0].min() - 1, X_two_features[:, 0].max() + 1

y_min, y_max = X_two_features[:, 1].min() - 1, X_two_features[:, 1].max() + 1

xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

# Predict the labels for each point in the mesh grid

Z = knn_2D.predict(np.c_[xx.ravel(), yy.ravel()])

Z = Z.reshape(xx.shape)

# Plot the decision boundary

plt.figure(figsize=(8, 6))

cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])

cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])

plt.contourf(xx, yy, Z, cmap=cmap_light)

# Plot the original data points

plt.scatter(X_two_features[:, 0], X_two_features[:, 1], c=y_encoded, cmap=cmap_bold,


edgecolor='k', s=20)

plt.xlabel('Sepal length')

plt.ylabel('Sepal width')

plt.title("KNN Decision Boundary (2 features)")

plt.show()

output:

You might also like