Practical No:– 8
Name: Hiren Daxeshbhai Patel Roll No.: 07
Title: Given a dataset for classification task. Write a program to implement Support Vector
Machine and estimate it test performance.
Software Requirement:
• Python
• NumPy
• Pandas
• scikit-learn
• Jupyter Notebook
Source Code:
# Import necessary libraries import
pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
# Load the dataset from a CSV file
data = pd.read_csv('iris_data.csv')
# Display the first few rows of the dataset print("Dataset
Preview:")
print(data.head())
# Separate features and labels
X = data.iloc[:, :-1] # All columns except the last one as features y
= data.iloc[:, -1] # The last column as the label
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Create and train the Support Vector Machine classifier svm_classifier =
SVC(kernel='linear') # You can choose 'linear', 'poly', 'rbf', etc.
svm_classifier.fit(X_train, y_train)
# Predict the labels for the test set y_pred
= svm_classifier.predict(X_test)
# Evaluate the performance of the classifier accuracy
= accuracy_score(y_test, y_pred) conf_matrix =
confusion_matrix(y_test, y_pred) class_report =
classification_report(y_test, y_pred)
# Print the results
print(f"\nAccuracy of the Support Vector Machine Classifier: {accuracy * 100:.2f}%") print("\
nConfusion Matrix:") print(conf_matrix) print("\nClassification Report:") print(class_report)
Output:
Conclusions:
SVM is a powerful and versatile classification tool, especially effective in high-dimensional
spaces. By carefully selecting the kernel function and tuning hyperparameters like \( C \), SVM
can achieve high classification accuracy even with complex datasets.