Introduction to Machine Learning in Python

In this section we'll go through some preliminary topics, as well as some of the requirements for this tutorial.

By the end of this section you should:

  • Know what sort of tasks qualify as Machine Learning problems.
  • See some simple examples of machine learning
  • Know the basics of creating and manipulating numpy arrays.
  • Know the basics of scatter plots in matplotlib.

What is Machine Learning?

In this section we will begin to explore the basic principles of machine learning. Machine Learning is about building programs with tunable parameters (typically an array of floating point values) that are adjusted automatically so as to improve their behavior by adapting to previously seen data.

Machine Learning can be considered a subfield of Artificial Intelligence since those algorithms can be seen as building blocks to make computers learn to behave more intelligently by somehow generalizing rather that just storing and retrieving data items like a database system would do.

We'll take a look at two very simple machine learning tasks here. The first is a classification task: the figure shows a collection of two-dimensional data, colored according to two different class labels. A classification algorithm may be used to draw a dividing boundary between the two clusters of points:


In [ ]:
# Start pylab inline mode, so figures will appear in the notebook
%pylab inline

In [ ]:
# Import the example plot from the figures directory
from figures import plot_sgd_separator
plot_sgd_separator()

This may seem like a trivial task, but it is a simple version of a very important concept. By drawing this separating line, we have learned a model which can generalize to new data: if you were to drop another point onto the plane which is unlabeled, this algorithm could now predict whether it's a blue or a red point.

If you'd like to see the source code used to generate this, you can either open the code in the figures directory, or you can load the code using the %load magic command:


In [ ]:
%load figures/sgd_separator.py

The next simple task we'll look at is a regression task: a simple best-fit line to a set of data:


In [ ]:
from figures import plot_linear_regression
plot_linear_regression()

Again, this is an example of fitting a model to data, such that the model can make generalizations about new data. The model has been learned from the training data, and can be used to predict the result of test data: here, we might be given an x-value, and the model would allow us to predict the y value. Again, this might seem like a trivial problem, but it is a basic example of a type of operation that is fundamental to machine learning tasks.

Numpy Arrays

Manipulating numpy arrays is an important part of doing machine learning (or, really, any type of scientific computation) in python. This will likely be review for most: we'll quickly go through some of the most important features.


In [ ]:
import numpy as np

# Generating a random array
X = np.random.random((3, 5))  # a 3 x 5 array

print X

In [ ]:
# Accessing elements

# get a single element
print X[0, 0]

# get a row
print X[1]

# get a column
print X[:, 1]

In [ ]:
# Transposing an array
print X.T

In [ ]:
# Turning a row vector into a column vector
y = np.linspace(0, 12, 5)
print y

In [ ]:
# make into a column vector
print y[:, np.newaxis]

There is much, much more to know, but these few operations are fundamental to what we'll do during this tutorial.

Scipy Sparse Matrices

We won't make very much use of these in this tutorial, but sparse matrices are very nice in some situations. For example, in some machine learning tasks, especially those associated with textual analysis, the data may be mostly zeros. Storing all these zeros is very inefficient. We can create and manipulate sparse matrices as follows:


In [ ]:
from scipy import sparse

# Create a random array with a lot of zeros
X = np.random.random((10, 5))
print X

In [ ]:
# set the majority of elements to zero
X[X < 0.7] = 0
print X

In [ ]:
# turn X into a csr (Compressed-Sparse-Row) matrix
X_csr = sparse.csr_matrix(X)
print X_csr

In [ ]:
# convert the sparse matrix to a dense array
print X_csr.toarray()

The CSR representation can be very efficient for computations, but it is not as good for adding elements. For that, the LIL (List-In-List) representation is better:


In [ ]:
# Create an empty LIL matrix and add some items
X_lil = sparse.lil_matrix((5, 5))

for i, j in np.random.randint(0, 5, (15, 2)):
    X_lil[i, j] = i + j

print X_lil

In [ ]:
print X_lil.toarray()

Often, once an LIL matrix is created, it is useful to convert it to a CSR format (many scikit-learn algorithms require CSR or CSC format)


In [ ]:
print X_lil.tocsr()

There are several other sparse formats that can be useful for various problems:

  • CSC (compressed sparse column)
  • BSR (block sparse row)
  • COO (coordinate)
  • DIA (diagonal)
  • DOK (dictionary of keys)

The scipy.sparse submodule also has a lot of functions for sparse matrices including linear algebra, sparse solvers, graph algorithms, and much more.

Matplotlib

Another important part of machine learning is visualization of data. The most common tool for this in Python is matplotlib. It is an extremely flexible package, but we will go over some basics here.

First, something special to IPython notebook. We can turn on the "IPython inline" mode, which will make plots show up inline in the notebook.


In [ ]:
%pylab inline

In [ ]:
# When you run %pylab inline, the following import happens automatically
# but it's often useful to be explicit:
import matplotlib.pyplot as plt

In [ ]:
# plotting a line
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))

In [ ]:
# scatter-plot points
x = np.random.normal(size=500)
y = np.random.normal(size=500)
plt.scatter(x, y)

In [ ]:
# showing images
x = np.linspace(1, 12, 100)
y = x[:, np.newaxis]

im = y * np.sin(x) * np.cos(y)
print im.shape

In [ ]:
# imshow - note that origin is at the top-left by default!
plt.imshow(im)

In [ ]:
# Contour plot - note that origin here is at the bottom-left by default!
plt.contour(im)

In [ ]:
# 3D plotting
from mpl_toolkits.mplot3d import Axes3D
ax = plt.axes(projection='3d')
xgrid, ygrid = np.meshgrid(x, y.ravel())
ax.plot_surface(xgrid, ygrid, im, cmap=plt.cm.jet, cstride=2, rstride=2, linewidth=0)

There are many, many more plot types available. One useful way to explore these is by looking at the matplotlib gallery: http://matplotlib.org/gallery.html

You can test these examples out easily in the notebook: simply copy the Source Code link on each page, and put it in a notebook using the %load magic. For example:


In [ ]:
%load http://matplotlib.org/mpl_examples/pylab_examples/ellipse_collection.py