Support Vector Machine

 

Expt No: 7                                           Support Vector Machine

Date:

 

Aim: To write a program to demonstrate SVM models

 

Program

# SVM

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split

from sklearn.svm import SVC

from sklearn.metrics import accuracy_score

 

# Load the Iris dataset

iris_df = pd.read_csv("Iris.csv")

 

# Extract features (X) and target labels (y)

X = iris_df.drop(columns=['Species'])  # Features

y = iris_df['Species']  # Target labels

 

# Map categorical labels to numerical values for visualization

label_map = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2}

y_color = y.map(label_map)

 

# Select two features for visualization (e.g., sepal length and sepal width)

feature1 = 'SepalLength'

feature2 = 'SepalWidth'

 

# Extract the selected features for plotting

X_plot = X[[feature1, feature2]].values

 

# Split the dataset into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(X_plot, y_color, test_size=0.2, random_state=42)

 

# Train a linear SVM classifier

svm_classifier = SVC(kernel='linear')

svm_classifier.fit(X_train, y_train)

 

# Make predictions on the test set

y_pred = svm_classifier.predict(X_test)

 

# Calculate the accuracy of the model

accuracy = accuracy_score(y_test, y_pred)

print("Accuracy:", accuracy)

 

# Visualize the decision boundary as a line

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

 

# Plot data points

plt.scatter(X_plot[:, 0], X_plot[:, 1], c=y_color, cmap=plt.cm.Set1, edgecolor='k', s=40)

 

# Plot the decision boundary as a line

w = svm_classifier.coef_[0]

a = -w[0] / w[1]

xx = np.linspace(X_plot[:, 0].min(), X_plot[:, 0].max())

yy = a * xx - (svm_classifier.intercept_[0]) / w[1]

plt.plot(xx, yy, 'k-', label='Decision Boundary')

 

# Add labels and title

plt.xlabel(feature1)

plt.ylabel(feature2)

plt.title('Linear SVM Decision Boundary Visualization')

plt.legend()

plt.show()

 

 

 

 

Result: Thus the program to demonstrate SVM models was written and executed.


Sample Output

 

Accuracy: 0.9





No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu