Group Part I: Machine Learning

Q3: Classification Analysis (Any one) A. Implement Support Vector Machines (SVM) to classify images of handwritten digits into their respective numerical classes (0 to 9). B. Implement the K-Nearest Neighbours algorithm on the Social Network Ads dataset. Compute the confusion matrix, accuracy, error rate, precision, and recall on the given dataset. Dataset link: https://www.kaggle.com/datasets/rakeshrau/social-network-ads

Classification Analysis (Any one)

Solution and implementation for Q3 from Machine Learning (ml).

3A_svm_handwritten_digits.ipynb Download
Code Cell 1
# Import required libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, classification_report, ConfusionMatrixDisplay
Code Cell 2
# Load the handwritten digits dataset
digits = load_digits()
X = digits.data
y = digits.target

print("Dataset shape:", X.shape)
print("Digit classes:", np.unique(y))
Dataset shape: (1797, 64)
Digit classes: [0 1 2 3 4 5 6 7 8 9]
Code Cell 3
# Display some sample handwritten digit images
fig, axes = plt.subplots(2, 5, figsize=(10, 5))
for ax, image, label in zip(axes.ravel(), digits.images, y):
    ax.imshow(image, cmap="gray")
    ax.set_title(f"Label: {label}")
    ax.axis("off")
plt.tight_layout()
plt.show()
Cell 3 output
<Figure size 1000x500 with 10 Axes>
Code Cell 4
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)
Code Cell 5
# Scale the features and train the SVM classifier
svm_model = make_pipeline(
    StandardScaler(),
    SVC(kernel="rbf", C=10, gamma="scale")
)
svm_model.fit(X_train, y_train)
Pipeline(steps=[('standardscaler', StandardScaler()), ('svc', SVC(C=10))])
Code Cell 6
# Predict digit classes and evaluate model accuracy
y_pred = svm_model.predict(X_test)
print("Accuracy:", round(accuracy_score(y_test, y_pred), 4))
print(classification_report(y_test, y_pred))
Accuracy: 0.9806
              precision    recall  f1-score   support

           0       1.00      1.00      1.00        36
           1       0.97      0.97      0.97        36
           2       1.00      1.00      1.00        35
           3       1.00      1.00      1.00        37
           4       0.95      0.97      0.96        36
           5       0.97      1.00      0.99        37
           6       0.97      1.00      0.99        36
           7       0.95      0.97      0.96        36
           8       1.00      0.94      0.97        35
           9       1.00      0.94      0.97        36

    accuracy                           0.98       360
   macro avg       0.98      0.98      0.98       360
weighted avg       0.98      0.98      0.98       360

Code Cell 7
# Display the confusion matrix
ConfusionMatrixDisplay.from_predictions(y_test, y_pred, cmap="Blues")
plt.title("SVM Confusion Matrix")
plt.tight_layout()
plt.show()
Cell 7 output
<Figure size 640x480 with 2 Axes>
Code Cell 8
# Display one random digit prediction
index = np.random.randint(len(X_test))

plt.figure(figsize=(4, 4))
plt.imshow(X_test[index].reshape(8, 8), cmap="gray")
plt.title(f"Actual: {y_test[index]}\nPredicted: {y_pred[index]}")
plt.axis("off")
plt.show()
Cell 8 output
<Figure size 400x400 with 1 Axes>
3B_knn_social_network_ads.ipynb Download
Code Cell 1
# Import required libraries
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
from sklearn.metrics import accuracy_score, precision_score, recall_score
Code Cell 2
# Load the Social Network Ads dataset
data = pd.read_csv("Social_Network_Ads.csv")
print(data.shape)
data.head()
(400, 5)
    User ID  Gender  Age  EstimatedSalary  Purchased
0  15624510    Male   19            19000          0
1  15810944    Male   35            20000          0
2  15668575  Female   26            43000          0
3  15603246  Female   27            57000          0
4  15804002    Male   19            76000          0
Code Cell 3
# Prepare features and target
data = data.drop(columns=["User ID"], errors="ignore")
data = pd.get_dummies(data, columns=["Gender"], drop_first=True)

X = data.drop(columns=["Purchased"])
y = data["Purchased"]

print("Features:", X.columns.tolist())
print("Target classes:", sorted(y.unique()))
Features: ['Age', 'EstimatedSalary', 'Gender_Male']
Target classes: [0, 1]
Code Cell 4
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)
Code Cell 5
# Scale the features and train the KNN classifier
knn_model = make_pipeline(
    StandardScaler(),
    KNeighborsClassifier(n_neighbors=5)
)
knn_model.fit(X_train, y_train)
Pipeline(steps=[('standardscaler', StandardScaler()),
                ('kneighborsclassifier', KNeighborsClassifier())])
Code Cell 6
# Predict whether each user will purchase
y_pred = knn_model.predict(X_test)
Code Cell 7
# Calculate confusion matrix and evaluation metrics
cm = confusion_matrix(y_test, y_pred, labels=[0, 1])
accuracy = accuracy_score(y_test, y_pred)
error_rate = 1 - accuracy
precision = precision_score(y_test, y_pred, zero_division=0)
recall = recall_score(y_test, y_pred, zero_division=0)

print("Confusion Matrix:\n", cm)
print("Accuracy:", round(accuracy, 4))
print("Error Rate:", round(error_rate, 4))
print("Precision:", round(precision, 4))
print("Recall:", round(recall, 4))
Confusion Matrix:
 [[59  5]
 [ 4 32]]
Accuracy: 0.91
Error Rate: 0.09
Precision: 0.8649
Recall: 0.8889
Code Cell 8
# Visualize the confusion matrix
ConfusionMatrixDisplay(
    confusion_matrix=cm,
    display_labels=["Not Purchased", "Purchased"]
).plot(cmap="Blues")

plt.title("KNN Confusion Matrix")
plt.tight_layout()
plt.show()
Cell 8 output
<Figure size 640x480 with 2 Axes>

Other Questions in Machine Learning

See All Available Questions
Download