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:
Regression: predict a number from data points, given data points and corresponding numbers
Classification: predict a category from data points, given data points and corresponding categories
Clustering: predict a category from data points, given only data points
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-learnimport numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sklearn # scikit-learn
import sklearn.metrics as metrics
from sklearn import datasets, linear_model
from sklearn.cluster import KMeans
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.manifold import TSNE
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifierData 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:
from sklearn import datasetsSome 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:
| Field | Column in df | Type | Unit | Description |
|---|---|---|---|---|
| Sex | sex | nominal | — | M, F, and I (infant) |
| Length | length | continuous | mm | longest shell measurement |
| Diameter | diameter | continuous | mm | perpendicular to length |
| Height | height | continuous | mm | with meat in shell |
| Whole weight | weight | continuous | grams | whole abalone |
| Shucked weight | shucked_weight | continuous | grams | weight of meat |
| Viscera weight | viscera_weight | continuous | grams | gut weight (after bleeding) |
| Shell weight | shell_weight | continuous | grams | after being dried |
| Rings | rings | integer | — | +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.
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.data',
header=None, names=['sex', 'length', 'diameter', 'height', 'weight', 'shucked_weight',
'viscera_weight', 'shell_weight', 'rings'])
dfdf.describe()df['rings'].plot.hist()
plt.show()df.plot.scatter('weight', 'rings')
plt.show()X = df[['weight']].to_numpy()
y = df['rings'].to_numpy()X, yfrom sklearn import linear_model
model = linear_model.LinearRegression()
model.fit(X, y)
print("slope: {}, intercept: {}".format(model.coef_, model.intercept_))
print("score: {}".format(model.score(X, y)))score is the coefficient of determination (1 is a perfect fit), computed here on the same data the model was fit to.
# predict number of rings based on new weight observations
model.predict(np.array([[1.5], [2.2]]))df.plot.scatter('weight', 'rings', alpha=0.5)
weight = np.linspace(0, 3, 10).reshape(-1, 1)
plt.plot(weight, model.predict(weight), 'r')
plt.show()Suppose there is a hypothesis that the number of rings is proportional to the square root of its weight.
# create a new feature: sqrt(weight)
df['root_weight'] = np.sqrt(df['weight'])X = df[['weight','root_weight']].to_numpy()
y = df['rings'].to_numpy()
model = linear_model.LinearRegression()
model.fit(X, y)
print("score: {}".format(model.score(X, y)))weight = np.linspace(0, 3, 100).reshape(-1, 1)
root_weight = np.sqrt(weight)
features = np.hstack((weight,root_weight))
df.plot.scatter('weight', 'rings', alpha=0.2)
plt.plot(weight, model.predict(features), 'r')
plt.show()model.coef_plt.hist2d(df['weight'], df['rings'],bins=(50,30));Other linear models have the same interface. ElasticNet adds and 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).
# from sklearn import linear_model
model = linear_model.ElasticNet()
model.fit(X, y)
print("slope: {}, intercept: {}".format(model.coef_, model.intercept_))
print("score: {}".format(model.score(X, y)))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.
from sklearn import datasets
iris = datasets.load_iris()
print(iris.DESCR)X = iris.data[:, :2]
y = iris.target_names[iris.target]for name in iris.target_names:
plt.scatter(X[y == name, 0], X[y == name, 1], label=name)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.legend();from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
print(X_train.shape, y_train.shape)
print(X_test.shape, y_test.shape)from sklearn.neighbors import KNeighborsClassifier
model = KNeighborsClassifier()
model.fit(X_train, y_train)X_testmodel.predict(X_test)Evaluating your model¶
np.mean(model.predict(X_test) == y_test) # Accuracyimport sklearn.metrics as metrics
metrics.accuracy_score(y_test, model.predict(X_test))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.
print(metrics.classification_report(y_test, model.predict(X_test)))# Cross validation
from sklearn.model_selection import cross_val_score
model = KNeighborsClassifier()
scores = cross_val_score(model, X, y, cv=5)
scoresprint(f"Accuracy: {scores.mean():.3f} (+/- {scores.std():.3f})")Using the full data - before we just used the first 2 features.
X = iris.data
y = iris.target_names[iris.target]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
model = KNeighborsClassifier(5)
model.fit(X_train, y_train)
print(metrics.classification_report(y_test, model.predict(X_test)))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?
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysismodels = [
# with the default 200 iterations, the MLP classifier stops before it converges
MLPClassifier(max_iter=1000),
SVC(),
GaussianProcessClassifier(max_iter_predict=20),
GaussianProcessClassifier(max_iter_predict=200),
DecisionTreeClassifier(),
RandomForestClassifier(),
AdaBoostClassifier(),
AdaBoostClassifier(learning_rate=0.5),
GaussianNB(),
QuadraticDiscriminantAnalysis()
]
def train_and_evaluate(model):
print(f"Evaluating {model}:")
X = iris.data
y = iris.target_names[iris.target]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
model.fit(X_train, y_train)
scores = cross_val_score(model, X, y, cv=5)
print(metrics.classification_report(y_test, model.predict(X_test)))
print(f"Accuracy: {scores.mean():.3f} (+/- {scores.std():.3f})")
print("\n====================================================")
for model in models:
train_and_evaluate(model)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.
X = iris.data
y = iris.target_names[iris.target]
for name in iris.target_names:
plt.scatter(X[y == name, 0], X[y == name, 1], label=name)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.legend()
plt.show()from sklearn.cluster import KMeans
model = KMeans(n_clusters=3, random_state=0)
model.fit(X)model.labels_iris.targetfig, ax = plt.subplots(1, 2, figsize=(10, 4))
for label in [0, 1, 2]:
ax[0].scatter(X[model.labels_ == label, 0], X[model.labels_ == label, 1], label=label)
ax[0].set_title('k-means clusters')
for name in iris.target_names:
ax[1].scatter(X[y == name, 0], X[y == name, 1], label=name)
ax[1].set_title('species')
for a in ax:
a.set_xlabel('Sepal length')
a.set_ylabel('Sepal width')
a.legend()
plt.show()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):
metrics.adjusted_rand_score(iris.target, model.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.
X = iris.data[:, :]
y = iris.target_names[iris.target]
fig, ax = plt.subplots(1,2, figsize=(10,5))
ax = ax.flatten()
for name in iris.target_names:
ax[0].scatter(X[y == name, 0], X[y == name, 1], label=name)
ax[0].set_xlabel('Sepal length')
ax[0].set_ylabel('Sepal width')
ax[0].set_title("First 2 features")
ax[0].legend()
for name in iris.target_names:
ax[1].scatter(X[y == name, 2], X[y == name, 3], label=name)
ax[1].set_xlabel('Petal length')
ax[1].set_ylabel('Petal width')
ax[1].set_title("Second 2 features")
ax[1].legend()
plt.show()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.
from sklearn.manifold import TSNE
model = TSNE(n_components=2, random_state=0)
X_transformed = model.fit_transform(X)
print(X.shape, X_transformed.shape)for name in iris.target_names:
plt.scatter(X_transformed[y == name, 0], X_transformed[y == name, 1], label=name)
plt.legend()
plt.show()