EE 4521/5521, Fall 2026

Topic 9

Professor Jarvis Haupt

Linear SVM

There are some nice illustrative examples right from the scikit-learn Python package examples that we'll consider here.

This is our first time using scikit-learn, but we'll revisit it often for the rest of the semester. This is one of the "go-to" machine learning packages in Python.

In the code below, you'll see the non-negative regularization parameter C. As stated in the slides, this parameter balances two criteria -- the total size of the deviations for points that violate the margin, and $\|\mathbf{w}\|_2$. This sort of trades off the size of the margin for the correctly classified points with the tolerance for margin violations. This is an example of a tuning parameter that we sometimes need to adjust manually in practice.

In [ ]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.datasets import make_blobs


# we create 40 separable points
X, y = make_blobs(n_samples=40, centers=2, random_state=6)

# fit the model, don't regularize for illustration purposes
clf = svm.SVC(kernel='linear', C=1e3)
clf.fit(X, y)

plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=plt.cm.Paired)

# plot the decision function
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()

# create grid to evaluate model
xx = np.linspace(xlim[0], xlim[1], 30)
yy = np.linspace(ylim[0], ylim[1], 30)
YY, XX = np.meshgrid(yy, xx)
xy = np.vstack([XX.ravel(), YY.ravel()]).T
Z = clf.decision_function(xy).reshape(XX.shape)

# plot decision boundary and margins
ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5,
           linestyles=['--', '-', '--'])
# plot support vectors
ax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=100,
           linewidth=1, facecolors='none', edgecolors='k')
plt.show()

It's worth mentioning that the term support vector machine is not sort of arbitrary. Instead, it comes from the fact that the optimal solution is really only a function of the closest data points to the boundary. These are circled in the example above, and are known as support vectors.

At the end of the day, the goal isn't necessarily to be able to do a good job on the data we have (although that's a step in the right direction!). Instead, we want to be able to do a good job correctly classifying new points that we haven't yet seen. If the new points are sort of similar (in distribution, at least) to the points we have seen, and we have seen enough training examples to elucidate the complexity of the distribution(s) from which the points are drawn, then this approach will likely work well! In this sense, the learned classifier is useful in helping us predict new labels based on the corresponding features.

Let's look at a soft-margin example.

In [ ]:
# Code source: Gaël Varoquaux
# Modified for documentation by Jaques Grobler
# License: BSD 3 clause

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm

# we create 40 separable points
np.random.seed(0)
X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]]
Y = [0] * 20 + [1] * 20

# figure number
fignum = 1

# fit the model
for name, penalty in (('unreg', 1), ('reg', 0.05)):

    clf = svm.SVC(kernel='linear', C=penalty)
    clf.fit(X, Y)

    # get the separating hyperplane
    w = clf.coef_[0]
    a = -w[0] / w[1]
    xx = np.linspace(-5, 5)
    yy = a * xx - (clf.intercept_[0]) / w[1]

    # plot the parallels to the separating hyperplane that pass through the
    # support vectors (margin away from hyperplane in direction
    # perpendicular to hyperplane). This is sqrt(1+a^2) away vertically in
    # 2-d.
    margin = 1 / np.sqrt(np.sum(clf.coef_ ** 2))
    yy_down = yy - np.sqrt(1 + a ** 2) * margin
    yy_up = yy + np.sqrt(1 + a ** 2) * margin

    # plot the line, the points, and the nearest vectors to the plane
    plt.figure(fignum, figsize=(4, 3))
    plt.clf()
    plt.plot(xx, yy, 'k-')
    plt.plot(xx, yy_down, 'k--')
    plt.plot(xx, yy_up, 'k--')

    plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80,
                facecolors='none', zorder=10, edgecolors='k')
    plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired,
                edgecolors='k')

    plt.axis('tight')
    x_min = -4.8
    x_max = 4.2
    y_min = -6
    y_max = 6
    plt.title(name)

    XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
    Z = clf.predict(np.c_[XX.ravel(), YY.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(XX.shape)
    plt.pcolormesh(XX, YY, Z, cmap=plt.cm.Paired)

    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)

    plt.xticks(())
    plt.yticks(())
    fignum = fignum + 1

plt.show()

Kernel SVM

We'll again look at a nice example from the scikit-learn package. This is written to explore the use of different kernels.

In [ ]:
# Code source: Gaël Varoquaux
# License: BSD 3 clause

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm


# Our dataset and targets
X = np.c_[(.4, -.7),
          (-1.5, -1),
          (-1.4, -.9),
          (-1.3, -1.2),
          (-1.1, -.2),
          (-1.2, -.4),
          (-.5, 1.2),
          (-1.5, 2.1),
          (1, 1),
          # --
          (1.3, .8),
          (1.2, .5),
          (.2, -2),
          (.5, -2.4),
          (.2, -2.3),
          (0, -2.7),
          (1.3, 2.1)].T
Y = [0] * 8 + [1] * 8

# figure number
fignum = 1

# fit the model
for kernel in ('linear', 'poly', 'rbf'):
    clf = svm.SVC(kernel=kernel, gamma=2)
    clf.fit(X, Y)

    # plot the line, the points, and the nearest vectors to the plane
    plt.figure(fignum, figsize=(4, 3))
    plt.clf()

    plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80,
                facecolors='none', zorder=10, edgecolors='k')
    plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired,
                edgecolors='k')

    plt.axis('tight')
    x_min = -3
    x_max = 3
    y_min = -3
    y_max = 3
    plt.title(kernel)

    XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
    Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(XX.shape)
    plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired)
    plt.contour(XX, YY, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'],
                levels=[-.5, 0, .5])

    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)

    plt.xticks(())
    plt.yticks(())
    fignum = fignum + 1
plt.show()

Naïve Bayes Classification

As alluded in the slides, the (nice) example below is from here (specifically, Chapter 5).

In [ ]:
import numpy as np
import matplotlib.pyplot as plt
#import seaborn as sns; sns.set()

# Generate (and visualize) some training data
from sklearn.datasets import make_blobs
X, y = make_blobs(100, 2, centers=2, random_state=2, cluster_std=1.5)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='RdBu');
plt.title('Training Data', size=14)
plt.show()

Here we'll use a Gaussian approach, assuming that the conditional marginal of each feature is independent and Gaussian distributed. The learning of the corresponding parameters can be accomplished via the following snippet.

In [ ]:
from sklearn.naive_bayes import GaussianNB
model = GaussianNB()
model.fit(X, y);

This gives a model where the contours of the corresponding Gaussian PDFs are nominally as shown here:

In [ ]:
fig, ax = plt.subplots()

ax.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='RdBu')
ax.set_title('Naive Bayes Model', size=14)

xlim = (-8, 8)
ylim = (-15, 5)

xg = np.linspace(xlim[0], xlim[1], 60) # Increased the number of points by 1
yg = np.linspace(ylim[0], ylim[1], 40)
xx, yy = np.meshgrid(xg[0:-1], yg[0:-1])
Xgrid = np.vstack([xx.ravel(), yy.ravel()]).T

for label, color in enumerate(['red', 'blue']):
    mask = (y == label)
    mu, std = X[mask].mean(0), X[mask].std(0)
    P = np.exp(-0.5 * (Xgrid - mu) ** 2 / std ** 2).prod(1)
    Pm = np.ma.masked_array(P, P < 0.03)
    ax.pcolorfast(np.squeeze(xg), np.squeeze(yg), Pm.reshape(xx.shape), alpha=0.5,
                  cmap=color.title() + 's')
    ax.contour(xx, yy, P.reshape(xx.shape),
               levels=[0.01, 0.1, 0.5, 0.9],
               colors=color, alpha=0.2)

ax.set(xlim=xlim, ylim=ylim)
plt.show()

Now we can generate some new (test) data, and predict the label using the Naive Bayes approach. Let's generate, label, and plot the data.

In [ ]:
rng = np.random.RandomState(0)
Xnew = [-6, -14] + [14, 18] * rng.rand(2000, 2)
ynew = model.predict(Xnew)

plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='RdBu')
lim = plt.axis()
plt.scatter(Xnew[:, 0], Xnew[:, 1], c=ynew, s=20, cmap='RdBu', alpha=0.1)
plt.axis(lim);
plt.title('Training (dark) and Test (light) Data')
plt.show()

As they point out in the example we're following, there's a nice interpretation that arises from the Bayesian framework - that you can do a probabilistic classification. Ultimately we want to make a decision (blue or red above), but one can make "soft" decisions here to see how confident we are in a labeling decision. The columns give the posterior probabilities of the first and second label class, respectively.

In [ ]:
yprob = model.predict_proba(Xnew)
yprob[-8:].round(2)

Text Classification Example

Let's look at another example of Naive Bayes classification, but where we don't assume Gaussian probability models.

In settings where the data take the form of discrete integers (e.g., where the features are integer-valued) it makes sense to consider discrete distributions. A commonly used choice in this context is the multinomial distribution.

Recall that we mentioned (somewhat in passing, and in some examples) that the Binomial PMF describes a discrete random variable parameterized by two values ($n$, and integer $\geq 1$, and $p\in[0,1]$). A Binomial random variable arises, for example, as a sum of $n$ iid Bernoulli($p$) random variables. Thus, it can take values in the set $\{0,1,\dots,n\}$.

The multinomial PMF generalizes this to a sum of iid discrete random variables that can take more than two values. Specifically, suppose we have a collection of random variables $W_1, \dots, W_n$ where each $W_i$ takes values in a set $\{1,\dots,k\}$ with (nonnegative) probabilities $\{p_1,\dots,p_k\}$, respectively (satisfying $\sum_{i=1}^k p_i = 1$). Such random variables are called categorical random variables. A sum of $n$ iid categorical random variables (with parameters as above) is a multinomial random variable with parameters $n$ and $p_1,\dots,p_k$.

Now, with this background, let's see how this comes into play in text classification problems.

In [ ]:
# get the data and print the category "target" names
from sklearn.datasets import fetch_20newsgroups

data = fetch_20newsgroups()
data.target_names

Following the example, we'll get just a subset of the categories.

In [ ]:
# extract training and test data
categories = ['talk.religion.misc', 'soc.religion.christian',
              'sci.space', 'comp.graphics']
train = fetch_20newsgroups(subset='train', categories=categories)
test = fetch_20newsgroups(subset='test', categories=categories)

# Print an example
print(train.data[5])

Now we need to extract some features to use for classification. Here, the features are essentially proportional to word frequencies in the documents (but with an extra computation that downplays the effects of very common words). These are called tf-idf (term frequency - inverse document frequency) features.

In [ ]:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline

# Instantiate the model.  The first argument is the feature extraction method
# The second argument is the classification method (multinomial Naive Bayes)
model = make_pipeline(TfidfVectorizer(), MultinomialNB())

# Fit the model and classify the test data!
model.fit(train.data, train.target)
labels = model.predict(test.data)

A nice way to visualize the performance of a $K$-class classifier is by way of the so-called confusion matrix. The confusion matrix depicts the predicted labels for elements from each label class, for data in the test data set.

In [ ]:
from sklearn.metrics import confusion_matrix
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt

mat = confusion_matrix(test.target, labels)
sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False,
            xticklabels=train.target_names, yticklabels=train.target_names)
plt.xlabel('true label')
plt.ylabel('predicted label');
plt.show()

From this we can see that the two "religion" categories are (not surprisingly) the most often confused. Nonetheless, this simple classifier does surprisingly well!

Let's see how we can predict the category for some of our own text (that we make up!).

In [ ]:
# A function that predicts the label for our own text input
def predict_category(s, train=train, model=model):
    pred = model.predict([s])
    return train.target_names[pred[0]]

# Try it out!
print('"mission to mars": ', predict_category('mission to mars'))

print(predict_category('Easter Sunday'))

print(predict_category('High resolution camera images of Saturn'))

print(predict_category('High resolution camera images of Saturn saved as a JPEG'))

As a final thought, I quote the nice overview provided in the reference we've been following -- actually, the Colab notebook linked from it -- regarding When To Use Naïve Bayes:

"Because naive Bayesian classifiers make such stringent assumptions about data, they will generally not perform as well as a more complicated model. That said, they have several advantages:

  • They are extremely fast for both training and prediction
  • They provide straightforward probabilistic prediction
  • They are often very easily interpretable
  • They have very few (if any) tunable parameters

These advantages mean a naive Bayesian classifier is often a good choice as an initial baseline classification. If it performs suitably, then congratulations: you have a very fast, very interpretable classifier for your problem. If it does not perform well, then you can begin exploring more sophisticated models, with some baseline knowledge of how well they should perform.

Naive Bayes classifiers tend to perform especially well in one of the following situations:

  • When the naive assumptions actually match the data (very rare in practice)
  • For very well-separated categories, when model complexity is less important
  • For very high-dimensional data, when model complexity is less important

The last two points seem distinct, but they actually are related: as the dimension of a dataset grows, it is much less likely for any two points to be found close together (after all, they must be close in every single dimension to be close overall). This means that clusters in high dimensions tend to be more separated, on average, than clusters in low dimensions, assuming the new dimensions actually add information. For this reason, simplistic classifiers like naive Bayes tend to work as well or better than more complicated classifiers as the dimensionality grows: once you have enough data, even a simple model can be very powerful."