Showing posts with label visualization. Show all posts
Showing posts with label visualization. Show all posts

Sunday, May 21, 2017

Machine learning 11 - Visualize high dimensional datasets

When we are dealing with machine learning datasets, many times, we have higher dimensional data than just the easy 2 dimensions. This makes us difficult to visualize the data to get a sense how different dimensions have a relationship with each other, or is there a hidden structure inside it. Today, I will show you the ways I usually use to visualize the higher dimensional datasets. You can find all the script at Qingkai's Github. 
I summarize ways to visualize high dimensional data into 2 groups:
  1. Using algorithms to reduce dimension
  2. Clever way to plot
Let's first see how to use algorithms to visualize the data. In this blog, we will use the IRIS dataset to show how different methods work. 

Let's first load data

from sklearn import datasets
# import the IRIS data
iris = datasets.load_iris()
iris_data = iris.data
Y = iris.target

print('There are %d features'%(iris_data.shape[1]))
print('There are %d classes'%(len(set(Y))))
There are 4 features
There are 3 classes

1 Reduce dimension using algorithms

1.1 Visualize high dimensional data with PCA

Principal Component Analysis is the classical way to reduce the dimensions. In our case, we have 4 features, which means we have 4 dimensions, difficult to visualize. With PCA, we can plot the first two components, and get a sense of the patterns hidden behind the data. 
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
%matplotlib inline

plt.style.use('seaborn-poster')
# Let's do a simple PCA and plot the first two components
pca = PCA(n_components=2)
X_pca = pca.fit_transform(iris_data)

# plot the first two components
plt.figure(figsize = (10, 8))
plt.scatter(X_pca[:, 0], X_pca[:,1], c = Y, s = 80, linewidths=0)
plt.xlabel('First component')
plt.ylabel('Second component')
<matplotlib.text.Text at 0x111681e10>
png
The above figure is showing the first two components of the PCA. I colored the dots with the 3 classes so that we can see the hidden structures. 

1.2 Visualize high dimensional data with t-SNE

t-distributed stochastic neighbor embedding (t-SNE) is a nonlinear dimensionality reduction technique that is particularly well-suited for embedding high-dimensional data into a space of two or three dimensions, which can then be visualized in a scatter plot.
from sklearn.manifold import TSNE
X_tsne = TSNE(learning_rate=100).fit_transform(iris_data)
# plot the first two components
plt.figure(figsize = (10, 8))
plt.scatter(X_tsne[:, 0], X_tsne[:,1], c = Y, s = 80, linewidths=0)
plt.xlabel('First dimension')
plt.ylabel('Second dimension')
<matplotlib.text.Text at 0x111a993d0>
png

2 Clever way to plot

Also, there are many clever ways to plot the data so that we can get a sense of the data. Pandas is the package I usually use for visualize high dimensional data. Here are some examples from pandas visualization:
import pandas as pd
import numpy as np
# let's first put the data into a dataframe
df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                     columns= [x[:-5] for x in iris['feature_names']] + ['target'])
df.head()
sepal lengthsepal widthpetal lengthpetal widthtarget
05.13.51.40.20.0
14.93.01.40.20.0
24.73.21.30.20.0
34.63.11.50.20.0
45.03.61.40.20.0

2.1 Scatter plot matrices

We know that scatter plot is a great tool to visualize the relationship between two variables, if we put every two variable pairs into a scatter plot and make them into a nice matrix, it is the scatter plot matrices. From these plots, we can easily see if a pair of variables related to each other. 
from pandas.plotting import scatter_matrix
scatter_matrix(df[df.columns[[0, 1, 2, 3]]], diagonal = 'density')
png

2.2 Parallel Coordinates

Parallel coordinates are a common way of visualizing high-dimensional geometry and analyzing multivariate data. It allows one to see clusters in data and to estimate other statistics visually. Using parallel coordinates points are represented as connected line segments. Each vertical line represents one attribute. One set of connected line segments represents one data point. Points that tend to cluster will appear closer together.
from pandas.plotting import parallel_coordinates
parallel_coordinates(df, 'target')
<matplotlib.axes._subplots.AxesSubplot at 0x128946590>
png

2.3 Andrews Curve

Andrews curves is another way to visualize structure in high-dimensional data. It is basically a smoothed version of parallel coordinates. 
from pandas.plotting import andrews_curves
andrews_curves(df, 'target')
<matplotlib.axes._subplots.AxesSubplot at 0x129006ad0>
png

2.4 Radviz

Radviz is another way of visualizing multi-variate data. It is based on a simple spring tension minimization algorithm. Basically you set up a bunch of points on a plane. In our case they are equally spaced on a unit circle. Each point represents a single attribute. You then pretend that each sample in the data set is attached to each of these points by a spring, the stiffness of which is proportional to the numerical value of that attribute (they are normalized to unit interval). The point in the plane, where our sample settles to (where the forces acting on our sample are at an equilibrium) is where a dot representing our sample will be drawn. Depending on which class that sample belongs it will be colored differently.
from pandas.plotting import radviz
radviz(df, 'target')
<matplotlib.axes._subplots.AxesSubplot at 0x12890f5d0>
png
These are usually my ways to visualize the high dimensional data to get a quick sense before I build further models. If you have better ways, please let me know.

Sunday, September 25, 2016

Using datashader to visualize billions of data points

Visualization is the best way to explore and communicate insights about data. But many times, we find it is difficult to visualize if we have a lot of data points, the traditional visualization techniques break down. datashader is a tool developed by Continuum Analytics come to rescue. It is extremly easy and fast to use it to plot even billions of data points (see the examples or a video from Scipy 2016). 
This week, we will use datashader to plot the global seismicity for earthquakes larger than M2.0. To speed up the process, I downloaded the earthquake locations/times from the ANSS Catalog from 1898 to 2016, and save them as a csv file in the data folder (You can also grab the data directly using the APIs from my previous blog post). All together, we only have 1120244 earthquakes
And with a couple of lines, you can see we get a very nice looking map with the global seismicity. You can find the script and data at Qingkai's Github.
import pandas as pd
import datashader as ds
import datashader.transfer_functions as tf
from functools import partial
from datashader.utils import export_image
from datashader.colors import colormap_select, Greys9, Hot, viridis, inferno
# read in the earthquake data from file, note that I only read
# in 5 columns with Origin time, Latitude, Longitude, Depth, and
# Magnitude of the earthquakes
df_eq = pd.read_csv('./data/catalog.csv', usecols=[0,1,2,3,4])
# now let's plot them using a black background
background = "black"
export = partial(export_image, background = background)
cm = partial(colormap_select, reverse=(background!="black"))

cvs = ds.Canvas(plot_width=1600, plot_height=1000)
agg = cvs.points(df_eq, 'Longitude', 'Latitude')
export(tf.interpolate(agg, cmap = cm(Hot,0.2), how='eq_hist'),"global_seismicity")

Wednesday, June 29, 2016

Using folium - 6: Layer control (Turn on/off intensity overlay)

In this blog, let's build on the blog from last week that we add a layer control to turn on/off the intensity layer we overlay on the map. All we need is to add two lines to have this control. You can find the script at Qingkai's Github.

In [1]:
import folium
from folium import plugins
from scipy.ndimage import imread
In [2]:
# boundary of the image on the map
min_lon = -123.5617
max_lon = -121.0617
min_lat = 37.382166
max_lat = 39.048834

# create the map
map_ = folium.Map(location=[38.2, -122],
                  tiles='Stamen Terrain', zoom_start = 8)

# read in png file to numpy array
data = imread('./ii_overlay.png')

Intensity = plugins.ImageOverlay(data, opacity=0.8, \
        bounds =[[min_lat, min_lon], [max_lat, max_lon]],\
        attr = 'Shaking Intensity')

# add a name to the layer
Intensity.layer_name = 'Shaking Intensity'

# Overlay the image
map_.add_children(Intensity)

# add the layer control
folium.LayerControl().add_to(map_)

map_
Out[2]: