Module 14 · Support vector machines · Lesson 53 of 66

Support vector machines

Find the widest gap between classes, and tune C and gamma with a grid search.

In this lesson · about 25 minutes

  • Explain the margin and support vectors
  • Train an SVC on the breast cancer data
  • Tune C and gamma automatically with GridSearchCV

Picture two groups of points on a page. Many lines could separate them, but the safest is the one with the widest empty band on either side: the maximum margin. A support vector machine (SVM) finds that line. The points sitting on the edge of the band are the support vectors; they alone decide where the line goes.

When no straight line can separate the groups, the kernel trick lets an SVM draw curved boundaries, as if lifting the points into more dimensions where a flat cut works. The default 'rbf' kernel does this.

Two settings matter most:

  • C: how much a misclassified training point costs. High C bends the boundary to get every point right (risking overfitting); low C keeps it smooth.
  • gamma: how far one point's influence reaches with the rbf kernel. High gamma means very local, wiggly boundaries.

The breast cancer data

scikit-learn includes this data set: 30 measurements of cell nuclei from 569 tumors, each labeled malignant (0) or benign (1).

Exercise

Train an SVC

The data is split for you (test_size=0.30, random_state=101). Train an SVC() with default settings called model, save its predictions as predictions, and print the confusion matrix.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
df_feat = pd.DataFrame(cancer['data'], columns=cancer['feature_names'])
df_target = pd.DataFrame(cancer['target'], columns=['Cancer'])
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
X_train, X_test, y_train, y_test = train_test_split(df_feat, np.ravel(df_target), test_size=0.30, random_state=101)

Grid search

Guessing C and gamma by hand is slow. GridSearchCV tries every combination you list. For each one it uses cross-validation: it splits the training data into 5 parts, trains on 4 and scores on the fifth, five times over, and averages. With refit=True it then retrains the best combination on all the training data, so the grid object works like a model.

Exercise

Search the grid

Make param_grid with 'C' in [0.1, 1, 10, 100, 1000] and 'gamma' in [1, 0.1, 0.01, 0.001, 0.0001]. Fit GridSearchCV(SVC(), param_grid, refit=True) called grid to the training data, save grid.predict(X_test) as grid_predictions, and end with grid.best_params_.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
df_feat = pd.DataFrame(cancer['data'], columns=cancer['feature_names'])
df_target = pd.DataFrame(cancer['target'], columns=['Cancer'])
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
X_train, X_test, y_train, y_test = train_test_split(df_feat, np.ravel(df_target), test_size=0.30, random_state=101)

Compare

Exercises solved: 0 of 2

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.