Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

SciKit Learn

Open in Colab

Scikit-learn is a library that allows you to do machine learning, that is, make predictions from data, in Python. There are four basic tasks:

  1. Regression: predict a number from data points, given data points and corresponding numbers

  2. Classification: predict a category from data points, given data points and corresponding categories

  3. Clustering: predict a category from data points, given only data points

  4. Dimensionality reduction: make data points lower-dimensional so that we can visualize the data

The scikit-learn documentation has an interactive flowchart of when to use each technique.

You may need to install scikit learn

(pycourse) $ conda install scikit-learn

Data Sets

A good place to look for example data sets to use in machine learning tasks is the UCI Machine Learning Repository, which contains hundreds of data sets, including information on where they came from and how to use them.

On this page we’ll use the Iris and Abalone data sets.

The Iris data set consists of measurements of three species of Iris (a flower). The Abalone data set consists of measurements of abalone, a type of edible marine snail.

Each data set’s page has a download link. The download for Abalone contains a file with the extension *.data, which is a csv file containing the data. This file does not have a header - you need to look at the variable information on the data set’s page to get the column names.

Scikit learn also has a few built-in data sets for easy loading:

Some of these can also be found in the UCI repository.

Regression

Abalone are a type of edible marine snail, and they have internal rings that correspond to their age (like trees). In the following, we will use the dataset of abalone measurements. It has the following fields:

FieldColumn in dfTypeUnitDescription
Sexsexnominal—M, F, and I (infant)
Lengthlengthcontinuousmmlongest shell measurement
Diameterdiametercontinuousmmperpendicular to length
Heightheightcontinuousmmwith meat in shell
Whole weightweightcontinuousgramswhole abalone
Shucked weightshucked_weightcontinuousgramsweight of meat
Viscera weightviscera_weightcontinuousgramsgut weight (after bleeding)
Shell weightshell_weightcontinuousgramsafter being dried
Ringsringsinteger—+1.5 gives the age in years

In the data file, the continuous measurements have been divided by 200.

Suppose we are interested in predicting the age of the abalone given their measurements. This is an example of a regression problem.

score is the coefficient of determination R2R^2 (1 is a perfect fit), computed here on the same data the model was fit to.

Suppose there is a hypothesis that the number of rings is proportional to the square root of its weight.

Other linear models have the same interface. ElasticNet adds L1L^1 and L2L^2 penalties on the coefficients to the least squares objective. With the default penalty weight alpha=1.0 it sets the coefficient of root_weight to zero and fits much worse. In practice you would choose alpha by cross-validation (see below).

Classification

Another example of a machine learning problem is classification. Here we will use a dataset of flower measurements from three different flower species of Iris (Iris setosa, Iris virginica, and Iris versicolor). We aim to predict the species of the flower. Because the species is not a numerical output, it is not a regression problem, but a classification problem.

Evaluating your model

The metrics functions take the true labels first and the predictions second. The order doesn’t matter for accuracy, but it does for precision and recall.

Using the full data - before we just used the first 2 features.

Exercise

Try to fit some of the models in the following cell to the same data. Compute the relevant statistics (e.g. accuracy, precision, recall). Look up the documentation for the classifier, and see if the classifier takes any parameters. How does changing the parameter affect the result?

Clustering

Clustering is useful if we don’t have a dataset labelled with the categories we want to predict, but we nevertheless expect there to be a certain number of categories. For example, suppose we have the previous dataset, but we are missing the labels. We can use a clustering algorithm like k-means to cluster the datapoints. Because we don’t have labels, clustering is what is called an unsupervised learning algorithm.

The cluster numbers are arbitrary, so to compare the clusters with the species we need a score that doesn’t depend on how the clusters are numbered, such as the adjusted Rand index (1 for a perfect match, about 0 for random labels):

Dimensionality reduction

Dimensionality reduction is another unsupervised learning problem (that is, it does not require labels). It aims to project datapoints into a lower dimensional space while preserving the structure of the data, such as distances or neighborhoods.

there are 4 features in the Iris data set. Depending on which set of features we use for visualization, we see the clusters separate more clearly.

Let’s try using the tSNE method to visualize the data.