In this section we’ll see some tools you might use for visualizing data.
This falls under the umbrella of Exploratory Data Analysis, which is often used to generate hypotheses.
Let’s consider data sampled from a low-dimensional space with added noise
Here is the -dimensional unit sphere ( is a circle and is the surface of a ball), is the uniform distribution on it, and is normal noise added in every direction. We use these examples because we know the right answer: a good visualization should show us the circle or sphere.
We’ll refer to the data as a point cloud. This means we’re going to think of the samples as points in some space. Any data set can be treated as a point cloud. We’ll represent this point cloud using an numpy array, where is the number of samples, and is the dimension of the space.
One thing we would like to do is visualize our point cloud.
import numpy as np
from scipy.spatial.distance import pdist, squareform # pairwise distances
import matplotlib.pyplot as plt
import plotly
import plotly.graph_objects as go
import sklearn.manifold as manifold
from sklearn.decomposition import KernelPCA, PCA
rng = np.random.default_rng()def sample_noisy_sphere(n, l=1, sigma=0.1):
"""
Sample n points uniformly at random from the l-sphere
embedded in l+1 dimensions
Add normal noise with standard deviation sigma
"""
d = l+1 # dimension of space
X = rng.standard_normal((n, d))
X = X / np.linalg.norm(X, axis=1).reshape(n,-1) # project onto sphere
return X + sigma*rng.standard_normal((n, d))
X = sample_noisy_sphere(1000)
plt.scatter(X[:,0], X[:,1])
plt.gca().set_aspect('equal')
plt.show()Above, we see a noisy circle: the points lie in a band of width about around the unit circle. But what if the circle sits in a higher-dimensional space? The version below places the sphere in a random -dimensional subspace of .
def sample_noisy_sphere(n, **kw):
"""
Sample n points uniformly at random from the l-sphere
embedded in d dimensions.
Add normal noise with standard deviation sigma
Arguments:
n - number of samples
Optional arguments:
r - radius of circle (default 1.0)
l - dimension of sphere (default l = 1 == circle)
sigma - noise standard deviation (default 0.1)
d - dimension of embedded space (default l+1)
"""
r = kw.get('r', 1.0)
l = kw.get('l', 1)
sigma = kw.get('sigma', 0.1)
d = kw.get('d', l+1)
X = rng.standard_normal((n, l+1))
X = r * X / np.linalg.norm(X, axis=1).reshape(n,-1) # project onto sphere
Q, R = np.linalg.qr(rng.standard_normal((d, l+1)))
X = X @ Q.T # apply random rotation
return X + sigma*rng.standard_normal((n, d))(The Q factor of the QR decomposition of a matrix with independent normal entries has orthonormal columns spanning a random -dimensional subspace, so this is a good way to sample random subspaces. Multiplying by Q.T maps the sphere into that subspace without changing any distances.)
m, n = 3,3
fig, ax = plt.subplots(m,n, figsize=(10,10))
for i in range(m):
for j in range(n):
X = sample_noisy_sphere(1000, d=5)
ax[i,j].scatter(X[:,0], X[:,1])
ax[i,j].set_aspect('equal')
plt.show()Each panel is a new random circle in , plotted using its first two coordinates. It isn’t always easy to see the circle. Projecting a circle onto a plane gives an ellipse, whose shape depends on how the plane of the circle sits relative to the coordinate axes: when the circle’s plane is tilted away from the plane of the two coordinates, the ellipse is small or thin. The noise ( in each coordinate) doesn’t shrink under the projection, so it fills in the hole of a small or thin ellipse, and the panel looks like a blob.
Plotly¶
Plotly is an open sourced graphing library which can help you create Javascript visualizations you can interact with in a web browser.
conda install plotly
conda install nbformat # you may need thisIn the 3D plots below, drag to rotate, scroll to zoom, and hover over a point to see its coordinates. The toolbar in the upper right corner can reset the view.
import plotly
import plotly.graph_objects as goX = sample_noisy_sphere(1000, d=3)
fig = go.Figure(data=[go.Scatter3d(x=X[:,0], y=X[:,1], z=X[:,2],
mode='markers', marker=dict(size=1))])
fig.show()Rotate the plot to look at the circle edge-on: it is flat, and its thickness comes from the noise.
We’ll define a function for quick 3D scatter plots of the first three columns of an array. Its optional argument labels gives the points with different labels different colors. It also draws the three axes to the same scale: by default, plotly stretches the axes into a cube when their ranges differ by more than a factor of 4, which can make flat data look thick.
def quick_scatter(X, labels=None):
"""
3D scatter plot of the first three columns of X,
with one color for each distinct value in labels (if given)
"""
if labels is None:
labels = np.zeros(len(X))
fig = go.Figure(data=[go.Scatter3d(x=X[labels == lab, 0], y=X[labels == lab, 1], z=X[labels == lab, 2],
mode='markers', marker=dict(size=2), name=str(lab))
for lab in np.unique(labels)])
fig.update_layout(scene_aspectmode='data', # same scale on all axes
legend_itemsizing='constant') # larger markers in the legend
fig.show()Dimension Reduction¶
Dimension reduction is the process of taking a high-dimensional data set and embedding it in a lower dimension.
Often, data with many features is really generated by a process with only a handful of parameters. This typically means we can think of data being sampled from a low-dimensional (parameter) space, but embedded in a high-dimensional feature space (perhaps with some noise). For example, photographs of an object turning on a turntable have thousands of pixels each, but they are determined by a single parameter, the angle of rotation, so they lie near a closed curve in pixel space, much like our circle.
Dimension reduction algorithms seek to reverse this process - we want to go from the high dimensional feature space to a lower dimensional space where the data generating mechanism may be easier to reason about.
Principal Component Analysis (PCA)¶
The simplest way to reduce the dimension of real-valued data is through a linear projection.
X = sample_noisy_sphere(1000, d=100, sigma=0.1)
Q, R = np.linalg.qr(rng.standard_normal((X.shape[1], 3)))
X2 = X @ Q # project onto a random 3-dimensional subspace
quick_scatter(X2)The circle is hard to see in this projection, if it is visible at all. The circle lies in a 2-dimensional plane in , and a random 3-dimensional subspace captures only a small part of that plane. The noise, on the other hand, has standard deviation in every direction, so it hides the circle.
So a random projection isn’t necessarily useful. We want the best possible subspace to project onto. PCA defines the best -dimensional subspace as the -dimensional subspace with the largest variance in the data. In other words, PCA looks for the directions in which the data is most spread out.
Recall that we can calculate the covariance matrix of the data using
where we assume has zero mean (i.e )
Let be a unit vector. The projection onto the subspace spanned by is calculated as . Note that if has zero-mean that will also have zero mean (prove it). The variance in this 1-dimensional subspace is then
So the subspace with the largest variance is defined by the unit vector which maximizes
We can write this as the variational problem
We recognize this as the problem of finding the largest magnitude eigenpair of , where is the eigenvector, and the eigenvalue of is (prove it).
If we want to project into a dimensional space, we then find
where spans the optimal -dimensional subspace.
This boils down to finding the largest dimensional eigenspace of .
The vectors are known as the principal components of
def mean_center(X):
mu = np.average(X, axis=0) # 1^T X / n
return X - mu
def variance(X):
n = X.shape[0]
X = mean_center(X)
return X.T @ X / n
def principal_vectors(X, k=3):
Sigma = variance(X)
lam, V = np.linalg.eigh(Sigma) # eigenvalues in increasing order
return V[:, ::-1][:, :k] # eigenvectors of the k largest eigenvalues, largest first
def pca_projection(X, k=3):
V = principal_vectors(X, k=k)
return mean_center(X) @ V
X = sample_noisy_sphere(1000, d=100, sigma=0.1)
Xpca = pca_projection(X, k=3)
quick_scatter(Xpca)Now the circle is clear. The top two principal components span (almost exactly) the plane of the circle, and projecting onto orthonormal vectors doesn’t change lengths, so the ring has radius about 1 and lies in the plane of the first two coordinates. The third principal component only contains noise, so the ring is flat, with a thickness set by . Compare with the random projection above: the data and the noise are the same, but now the projection keeps all of the circle.
PCA Via the SVD¶
In practice, you should not compute PCA by forming . Why? Because if is ill-conditioned, then will be even more ill conditioned.
What you should do is use the SVD of the mean-centered . If then
Clearly, the right-singular vectors are the eigenvectors of .
Exercises¶
Write a function to project a design matrix
Xonto its topkprincipal components using the SVD.Modify your function to use ARPACK via
scipy.sparse.linalg.svdsWhat is the condition number expressed in terms of ? (Hint)
Plot the singular values of
Xgenerated above - how might you decide how many principal components to use?
# Your code here
X = sample_noisy_sphere(1000, d=100, sigma=0.1)
s = np.linalg.svd(mean_center(X), compute_uv=False) # singular values only
plt.semilogy(s)
plt.show()Two singular values, about , stand out. They come from the circle, which spans a 2-dimensional plane (each coordinate of a point on the unit circle has variance ). The other 98 come from the noise, and lie between about 2 and 4, near . The number of singular values above this noise floor, where the plot drops sharply, is the dimension of the subspace that contains the data, and so a good choice for the number of principal components. With real data the drop is usually less sharp.
Note that this dimension is 2, not 1: PCA finds the smallest subspace containing the data, while the circle itself is a 1-dimensional curve. This is the motivation for the nonlinear methods below.
Nonlinear Dimensionality Reduction¶
Often linear projections are not sufficient to visualize structure in data, because the map from the parameters to the data is not linear. For example, a circle is a 1-dimensional curve, but any linear projection of it onto a line folds it in half, so points on opposite sides of the circle land on top of each other. There are a variety of techniques you can use for nonlinear dimensionality reduction.
These techniques often fall under the umbrella of “manifold learning” because we think of the parameter space describing the data as some manifold.
We’ll use Scikit-Learn’s manifold learning module to explore these algorithms.
conda install scikit-learnScikit-learn Syntax¶
Let’s go over how Scikit-Learn operates. We’ll use PCA as an example. See the documentation.
In general, Scikit-Learn provides objects that will perform some algorithm on data. In this case, we’ll use a PCA object.
from sklearn.decomposition import PCAtransformer = PCA(n_components=3)
type(transformer)There are two stages to using a dimension reduction technique.
First we “fit” an object (transformer above) to the data: for PCA, this computes the principal components. Then we can transform X using the object: for PCA, this projects X onto the principal components. The two stages are separate so that you can also transform new data using what was learned from the original data.
X = sample_noisy_sphere(1000, d=100, sigma=0.01)
transformer.fit(X)
Xpca = transformer.transform(X)
quick_scatter(Xpca)This is the same picture as with our own pca_projection, with a thinner ring since here. (The sign of each principal component is arbitrary, so the picture may be flipped.)
You can also use the combined fit_transform method. After fitting, the transformer stores what it learned in attributes whose names end in an underscore, such as components_ (the principal components) and explained_variance_ratio_ (the fraction of the total variance captured by each component):
Xpca = transformer.fit_transform(X)
transformer.explained_variance_ratio_The first two components capture almost all of the variance, about half each, since the circle is spread out equally in every direction of its plane. The third captures only noise. This gives another way to choose the number of components: keep enough of them to capture most of the variance.
Generating Nonlinear Data¶
Let’s make our data more interesting. First, we’ll generate three nested circles in , with radii 1, 2, and 3. Each call to sample_noisy_sphere picks its own random rotation, so the circles are all centered at the origin but lie in different planes, like the rings of a gyroscope.
def nested_spheres(*rs, **kw):
"""
generate nested circles
Arguments:
r1, r2, r3,... radii of circles
Optional arguments:
n = number of samples for each circle (default 500)
additional arguments will be passed to sample_noisy_sphere
"""
ns = kw.pop('n', 500) # remove key from dict
if type(ns) is int:
ns = tuple(ns for r in rs)
data = []
for n, r in zip(ns, rs):
data.append(sample_noisy_sphere(n, r=r, **kw))
return np.concatenate(data, axis=0)
rng = np.random.default_rng(1)
X = nested_spheres(1.0, 2.0, 3.0, d=3)
labels = np.repeat(["r = 1", "r = 2", "r = 3"], 500) # which circle each point came from
quick_scatter(X, labels)We only use labels to color the plots; none of the methods below sees them. For each method, check whether each circle stays together as a closed loop, and whether the three circles stay apart.
Next we apply a nonlinear function ,
to every point. The circles are still closed curves, but now they are bent, and they live in , so the plot only shows the first three coordinates. The goal of the methods below is to recover the three separate loops from Y.
def f(x):
y = [x[0]*x[1], x[0] - x[1], np.sin(x[1]), np.cos(x[1])]
y.extend([x[i] for i in range(2, len(x))])
return np.array(y)
Y = np.array([f(x) for x in X])
quick_scatter(Y, labels)The map stretches the outer circles much more than the inner one, since grows like the square of the radius: the inner circle (r = 1) becomes a small tangle near the origin, while the outer circle (r = 3) spans a range of about 10.
Let’s try PCA first:
Ypca = PCA().fit_transform(Y)
quick_scatter(Ypca, labels)PCA can only rotate and project, so it can’t undo the bending. The directions of largest variance mostly follow the large outer circles, so they take up most of the plot, while the inner circle is squeezed into the middle, and the circles overlap in some views.
Kernel PCA¶
Kernel PCA computes principal components after an implicit nonlinear map of the data into a higher-dimensional feature space. It only needs inner products in that feature space, which are given by a kernel function , here the Gaussian (RBF) kernel .
from sklearn.decomposition import KernelPCA
transformer = KernelPCA(n_components=3, kernel="rbf")
Ytrans = transformer.fit_transform(Y)
quick_scatter(Ytrans, labels)The circles are better separated than with PCA, but each loop is bent and its points are unevenly spread. The default kernel width is (one over the number of features). Try values of gamma 10 times smaller or larger to see how much the picture depends on it.
Isomap¶
Isomap builds a nearest-neighbor graph of the data, approximates distances along the data by shortest-path distances in that graph, and then looks for points in whose Euclidean distances match those distances (multidimensional scaling, below).
import sklearn.manifold as manifoldtransformer = manifold.Isomap(n_components=3)
Ytrans = transformer.fit_transform(Y)
quick_scatter(Ytrans, labels)Each circle becomes its own curve, and the sizes of the curves follow the lengths of the circles in Y, since Isomap tries to preserve distances measured along the data. However, the three circles are far apart compared with the distance between neighboring points, so the nearest-neighbor graph falls apart into several connected components (here the outer circle also splits into two pieces), and scikit-learn warns that it has to join them. Shortest-path distances between different components aren’t meaningful, so neither are the positions of the curves relative to each other. This is one limitation of Isomap.
Spectral Embedding¶
Spectral embeddings are computed from a graph built from the data, typically a weighted nearest-neighbors graph. The coordinates are eigenvectors of the graph Laplacian with the smallest eigenvalues, as in Spectral Graph Theory, so points that are strongly connected in the graph end up close together.
transformer = manifold.SpectralEmbedding(n_components=3)
Ytrans = transformer.fit_transform(Y)
quick_scatter(Ytrans, labels)The axis values are tiny, because the coordinates are entries of normalized eigenvectors; their scale means nothing, only the shape does. The inner circle is again kept apart from the others, which spread along separate branches but overlap near the middle. If the neighbor graph had several connected components, each would collapse to a single point, since the eigenvectors with the smallest eigenvalues are then constant on each component.
t-SNE¶
t-SNE tries to keep points that are close in the original space close in the embedding. It is good at showing clusters, but the sizes of the clusters and the distances between them in a t-SNE plot don’t mean much. Its perplexity parameter (default 30) roughly sets how many neighbors each point pays attention to.
transformer = manifold.TSNE(n_components=3, init='pca', random_state=0)
Ytrans = transformer.fit_transform(Y)
quick_scatter(Ytrans, labels)t-SNE separates the three circles most cleanly, each as its own loop. But the inner circle, which is much smaller than the others in Y, comes out about as large as them: t-SNE doesn’t preserve sizes, or distances between clusters. t-SNE is also random; rerun it with a different random_state to see which features of the picture are stable.
Multidimensional Scaling¶
Multidimensional scaling (MDS) looks for points in whose pairwise Euclidean distances match a given matrix of dissimilarities as closely as possible. The dissimilarities don’t have to be Euclidean distances, so let’s use the (cityblock) metric instead.
from scipy.spatial.distance import pdist, squareform # pairwise distances
D = squareform(pdist(Y,'cityblock')) # L1 metric# scikit-learn before 1.8: use dissimilarity="precomputed" instead of metric=, and no init=
transformer = manifold.MDS(n_components=3, metric="precomputed", init="classical_mds")
Ytrans = transformer.fit_transform(D)
quick_scatter(Ytrans, labels)The MDS picture looks a lot like the PCA one: the outer circles take up most of the plot, and the inner one is squeezed into the middle. MDS tries to match all pairwise dissimilarities at once, and the largest ones, across the outer circles, dominate the fit. The methods built on a nearest-neighbor graph (Isomap, spectral embedding, t-SNE) only use the distances between nearby points, which is why they could pull the circles apart.
Reading Embeddings¶
| Method | Tries to preserve | Watch out for |
|---|---|---|
| PCA | directions of largest variance (linear) | can’t unfold curved data |
| Kernel PCA | variance after a nonlinear feature map | depends on the kernel and its width |
| Isomap | distances along the data | needs a connected neighbor graph |
| Spectral embedding | which points are connected in a neighbor graph | the scale of the axes means nothing |
| t-SNE | which points are neighbors | cluster sizes and gaps between clusters mean nothing; random |
| MDS | all pairwise dissimilarities | dominated by the largest dissimilarities |
Some things to check in any embedding:
Axis scales. Are the axes drawn to the same scale? A stretched axis can make noise look like structure.
Known labels or parameters. If you know something about the points (a class, or a parameter such as an angle), color the points by it. Points that should be together should stay together.
Shape. Do loops, holes, and branches match what you expect? A circle should stay a closed loop.
Stability. Rerun with different random seeds and parameters (
n_neighbors,perplexity,gamma). A feature that appears for only one setting is probably an artifact.