Isolation Forest
Part of the Unsupervised Learning section of Coddy's Machine Learning journey. Lesson 35 of 51.
Odd points are easy to cut off. Slice the data at random, again and again, until one point stands alone:
The far point needed 2 cuts, the crowded one 8. An isolation forest averages the cuts over 100 random trees:
from sklearn.ensemble import IsolationForest
forest = IsolationForest(contamination=0.02, random_state=0)
flags = forest.fit_predict(X)fit_predict gives -1 for odd rows, 1 for the rest. contamination is the share of rows you expect to be odd.
Challenge
MediumA port logged 160 crane shifts: moves per hour and energy per move. Which shifts were strange?
- Flag the shifts with an isolation forest,
contamination=0.03,random_state=0. Print the count as below. - Scatter the normal shifts as dots labelled
normal. - Circle the flagged ones:
s=150, facecolors="none", edgecolors="red", labelledflagged. Add a legend and show.
For another port, with 200 shifts:
Flagged: 6 of 200 shiftsCoddy then describes your chart.
Try it yourself
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest
# One row per crane shift at the port: speed and energy use
shifts = pd.read_csv("cranes.csv")
X = shifts[["moves_per_hour", "kwh_per_move"]]
# Don't change the lines below
fig, ax = plt.subplots()
ax.set_title("Crane Shifts")
ax.set_xlabel("Moves per hour")
ax.set_ylabel("Energy per move (kWh)")
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unsupervised Learning
1Finding Groups
Learning Without LabelsMeasuring SimilarityK-Means by HandK-Means in scikit-learnRecap: Gym Members7PCA in Practice
Seeing 64 DimensionsComponents as PatternsCompress and RebuildPCA Before a ModelRecap: Face Scanner10Project: Digit Explorer
Look at the DigitsShrink with PCACluster the DigitsName the ClustersFind the Odd Ones8Anomaly Detection
Finding the Odd OnesIsolation ForestLocal Outlier FactorAnomaly ScoresRecap: Server WatchPractice on your own: Online Python compiler