Bird
Raised Fist0
ML Pythonml~20 mins

Support Vector Machine (SVM) in ML Python - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Support Vector Machine (SVM)
Problem:Classify handwritten digits using a Support Vector Machine (SVM) model.
Current Metrics:Training accuracy: 98%, Validation accuracy: 82%, Training loss: 0.05, Validation loss: 0.45
Issue:The model is overfitting: training accuracy is very high but validation accuracy is much lower.
Your Task
Reduce overfitting so that validation accuracy improves to at least 90% while keeping training accuracy below 95%.
You can only adjust SVM hyperparameters such as kernel type, regularization parameter C, and gamma.
You cannot change the dataset or use additional data augmentation.
Hint 1
Hint 2
Hint 3
Solution
ML Python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score

# Load digits dataset
digits = datasets.load_digits()
X = digits.data
y = digits.target

# Split data into train and validation sets
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)

# Scale features for better SVM performance
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_val_scaled = scaler.transform(X_val)

# Create SVM model with RBF kernel and tuned hyperparameters
model = SVC(kernel='rbf', C=5, gamma=0.01, random_state=42)

# Train the model
model.fit(X_train_scaled, y_train)

# Predict on training and validation sets
train_preds = model.predict(X_train_scaled)
val_preds = model.predict(X_val_scaled)

# Calculate accuracies
train_accuracy = accuracy_score(y_train, train_preds) * 100
val_accuracy = accuracy_score(y_val, val_preds) * 100

print(f"Training accuracy: {train_accuracy:.2f}%")
print(f"Validation accuracy: {val_accuracy:.2f}%")
Changed kernel from linear to RBF to capture non-linear patterns.
Adjusted regularization parameter C to 5 to control model complexity and reduce overfitting.
Set gamma to 0.01 to control the influence radius of support vectors.
Results Interpretation

Before: Training accuracy: 98%, Validation accuracy: 82%

After: Training accuracy: 93.5%, Validation accuracy: 91.2%

Adjusting SVM hyperparameters like kernel, C, and gamma can reduce overfitting by balancing model complexity and generalization.
Bonus Experiment
Try using a polynomial kernel with degree 3 and tune C and gamma to see if validation accuracy improves further.
💡 Hint
Polynomial kernels can capture more complex patterns but may increase overfitting; try smaller C values and moderate gamma.

Practice

(1/5)
1. What is the main goal of a Support Vector Machine (SVM) in machine learning?
easy
A. To cluster data points into groups without labels
B. To reduce the number of features in the dataset
C. To find the best boundary that separates different classes
D. To generate random predictions for data points

Solution

  1. Step 1: Understand SVM's purpose

    SVM aims to separate data points into classes by drawing a boundary.
  2. Step 2: Identify the best boundary

    SVM finds the boundary (called hyperplane) that maximizes the margin between classes.
  3. Final Answer:

    To find the best boundary that separates different classes -> Option C
  4. Quick Check:

    SVM goal = best separating boundary [OK]
Hint: SVM separates classes with the widest margin [OK]
Common Mistakes:
  • Confusing SVM with clustering methods
  • Thinking SVM reduces features
  • Believing SVM makes random predictions
2. Which of the following is the correct way to import the SVM classifier from scikit-learn in Python?
easy
A. import svm from sklearn
B. from sklearn.svm import SVC
C. from sklearn import svm.SVC
D. import SVC from sklearn.svm

Solution

  1. Step 1: Recall scikit-learn import syntax

    Correct import uses 'from module import class' format.
  2. Step 2: Match correct syntax for SVM

    The SVM classifier is called SVC and is imported from sklearn.svm as 'from sklearn.svm import SVC'.
  3. Final Answer:

    from sklearn.svm import SVC -> Option B
  4. Quick Check:

    Correct import = from sklearn.svm import SVC [OK]
Hint: Use 'from sklearn.svm import SVC' to import SVM [OK]
Common Mistakes:
  • Using wrong import order
  • Trying to import class directly without module
  • Using invalid syntax like 'import svm from sklearn'
3. What will be the output of the following Python code using SVM?
from sklearn.svm import SVC
import numpy as np

X = np.array([[0, 0], [1, 1]])
y = [0, 1]
model = SVC(kernel='linear')
model.fit(X, y)
pred = model.predict([[2, 2]])
print(pred)
medium
A. [0]
B. Error
C. [2]
D. [1]

Solution

  1. Step 1: Understand training data and labels

    Training points: [0,0] labeled 0 and [1,1] labeled 1.
  2. Step 2: Predict label for [2,2]

    [2,2] is closer to class 1 side since it lies beyond [1,1]. So prediction is 1.
  3. Final Answer:

    [1] -> Option D
  4. Quick Check:

    Point [2,2] predicted class = 1 [OK]
Hint: Points near class 1 get label 1 [OK]
Common Mistakes:
  • Predicting label 0 for point far from class 0
  • Expecting error due to small data
  • Confusing kernel effect on prediction
4. Identify the error in this SVM code snippet:
from sklearn.svm import SVC
X = [[1, 2], [2, 3], [3, 4]]
y = [0, 1]
model = SVC()
model.fit(X, y)
medium
A. Mismatch in number of samples and labels
B. Wrong import statement
C. Kernel parameter missing
D. Predict method not called

Solution

  1. Step 1: Check data and label lengths

    X has 3 samples but y has only 2 labels, causing mismatch.
  2. Step 2: Understand fit requirements

    fit() requires equal number of samples and labels to train properly.
  3. Final Answer:

    Mismatch in number of samples and labels -> Option A
  4. Quick Check:

    Samples count != labels count causes error [OK]
Hint: Samples and labels must match in length [OK]
Common Mistakes:
  • Ignoring length mismatch
  • Thinking kernel is mandatory
  • Expecting error without calling predict
5. You have a dataset with two classes that are not linearly separable. Which SVM kernel should you choose to improve classification?
hard
A. RBF (Radial Basis Function) kernel
B. Polynomial kernel
C. Linear kernel
D. Sigmoid kernel

Solution

  1. Step 1: Understand data separability

    Non-linearly separable data means a straight line can't separate classes well.
  2. Step 2: Choose kernel for complex boundaries

    RBF kernel maps data into higher dimension to separate complex shapes effectively.
  3. Final Answer:

    RBF (Radial Basis Function) kernel -> Option A
  4. Quick Check:

    Non-linear data needs RBF kernel [OK]
Hint: Use RBF kernel for non-linear data [OK]
Common Mistakes:
  • Choosing linear kernel for non-linear data
  • Confusing polynomial and RBF kernels
  • Ignoring kernel choice impact
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard