Apply a Support Vector Machine (SVM) classifier on the Iris dataset to train and test the model, standardize the features, predict the species, and evaluate its performance.¶

In [1]:
# Import required libraries
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import classification_report, accuracy_score
In [2]:
# 1. Load the Iris dataset
iris = datasets.load_iris()
X = iris.data     # Features: sepal length, sepal width, petal length, petal width
y = iris.target   # Labels: speacies
In [3]:
# Convert to DataFrame (optinal - for clarity)
df = pd.DataFrame(X, columns = iris.feature_names)
df['target'] = y
print("First 5 rows of datasets:\n", df.head())
First 5 rows of datasets:
    sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  \
0                5.1               3.5                1.4               0.2   
1                4.9               3.0                1.4               0.2   
2                4.7               3.2                1.3               0.2   
3                4.6               3.1                1.5               0.2   
4                5.0               3.6                1.4               0.2   

   target  
0       0  
1       0  
2       0  
3       0  
4       0  
In [4]:
# 2. 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)
In [5]:
# 3. Standardize the features (important for SVM)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
In [6]:
# 4. Create and train the SVM classifier
svm_clf = SVC(kernel = 'rbf', C = 1.0, gamma='scale') # RBF kernel SVM
svm_clf.fit(X_train, y_train)
Out[6]:
SVC()
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
C  1.0
kernel  'rbf'
degree  3
gamma  'scale'
coef0  0.0
shrinking  True
probability  False
tol  0.001
cache_size  200
class_weight  None
verbose  False
max_iter  -1
decision_function_shape  'ovr'
break_ties  False
random_state  None
In [7]:
# 5. Predict on the test set
y_pred =  svm_clf.predict(X_test)
In [8]:
# 6. Evaluate the model
print("\nAccuracy on Test Set: {:.2f}%".format(accuracy_score(y_test, y_pred) * 100))
print("\nClassification report:\n", classification_report(y_test, y_pred, target_names=iris.target_names))
Accuracy on Test Set: 100.00%

Classification report:
               precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        19
  versicolor       1.00      1.00      1.00        13
   virginica       1.00      1.00      1.00        13

    accuracy                           1.00        45
   macro avg       1.00      1.00      1.00        45
weighted avg       1.00      1.00      1.00        45