Workshop: An Auto-encoder for Unsupervised Anomaly Detection
Learning objectives
- Plant the book's own log faults in the nine wells by a stated, seeded rule, in Python and as the book's kernel does
- Train an autoencoder on eight wells at a time and score the ninth by its reconstruction error
- Compute the area under the ROC curve of the scores against the planted faults, by trapezoids and by ranks
- Say which faults reconstruction error finds, which it misses, and what it flags that is not a fault
Faults the Book Planted
Trained on eight of the Ogbon field's nine wells and scoring the ninth by what it cannot rebuild, nine times over, a tanh autoencoder with one bottleneck unit ranks a planted fault above clean log 0.740 of the time, the area under its ROC curve; PCA from one component ranks it 0.567. It finds the washouts, 0.968, and most of the noisy tools, 0.739, and misses the stuck tools, 0.496, a coin's odds: reconstruction error finds what is unlike the training logs, which is not always what is wrong. Flagging the worst 2 % of each well catches 51.5 ft of the 191.5 ft planted, with 56.5 ft of clean log flagged, 11.5 ft of it in Ogbon-8's limestone, the only limestone in the water leg. This workshop computes them in Python; the figure runs the book's stored networks on each held-out well.
The Nine Wells and the Faults
The data are the book's own learning set: Ogbon-1, the Petrophysics book's well, and eight hypothetical appraisal wells of the book's field, each 1201 samples every 0.5 ft of six logs as the book's own tool model records them, all synthetic. Into a copy of each well's logs the book plants three faults of its own, one in each third of the well, in an order and at depths drawn from the kernel's generator seeded 1616 plus 31 times the well's index, each 5 to 10 ft long: a washout, where the hole has caved and the pad tools read the mud (density −0.25 g/cc, neutron +0.12 v/v, sonic +15 us/ft and the photoelectric factor −1 b/e, each times a severity from 0.6 to 1); a stuck tool, one of the six logs held at its value at the interval's top; and a noisy tool, one log with 5 times its tool model's noise added. These are the book's own faults, not any real tool's, and a real washout is read on the caliper, which the learning set does not carry. In all, 383 of the 10809 samples are planted, 191.5 ft: washouts 68.0 ft, stuck tools 63.5 ft and noisy tools 60.0 ft. Nobody tells the autoencoder where they are: it is trained on the faulted logs as they are.
Step 1: Load the Learning Set
import numpy as np
import pandas as pd
URL = "https://ogbonlab.com/mlgeo-core/data/ogbon-learning-set.csv"
df = pd.read_csv(URL, comment="#")
df["LRT"] = np.log10(df["RT_ohmm"])
LOGS = ["GR_API", "RHOB_gcc", "NPHI_vv", "DT_usft", "LRT", "PEF_be"]
wells = df["well"].unique()
dz = np.diff(df["depth_ft"].to_numpy()[:2])[0]
Step 2: Plant the Faults
The kernel's generator (mulberry32), its shuffle and its normal draw, written out so Python plants the faults the book's kernel plants, sample for sample:
def mulberry32(seed):
s = seed & 0xFFFFFFFF
def r():
nonlocal s
s = (s + 0x6D2B79F5) & 0xFFFFFFFF
t = s
t = ((t ^ (t >> 15)) * (t | 1)) & 0xFFFFFFFF
t ^= (t + ((t ^ (t >> 7)) * (t | 61) & 0xFFFFFFFF)) & 0xFFFFFFFF
return ((t ^ (t >> 14)) & 0xFFFFFFFF) / 4294967296
return r
def gauss(r):
u, v = 1 - r(), r()
return np.sqrt(-2 * np.log(u)) * np.cos(2 * np.pi * v)
def shuffle(n, r):
a = list(range(n))
for i in range(n - 1, 0, -1):
j = int(r() * (i + 1))
a[i], a[j] = a[j], a[i]
return a
SIGMA = {"GR_API": 6, "RHOB_gcc": 0.025, "NPHI_vv": 0.015,
"DT_usft": 2.5, "LRT": 0.06, "PEF_be": 0.15}
SHIFT = {"RHOB_gcc": -0.25, "NPHI_vv": 0.12,
"DT_usft": 15, "PEF_be": -1}
def plant(k, X):
r = mulberry32(1616 + 31 * k)
n, third = len(X), len(X) // 3
lo, hi = round(5 / dz), round(10 / dz)
kind = np.full(n, -1)
for j, kd in enumerate(shuffle(3, r)):
ln = lo + int(r() * (hi - lo + 1))
top = j * third + int(r() * (third - ln))
rows = slice(top, top + ln)
if kd == 0: # a washout
u = 0.6 + 0.4 * r()
for c, d in SHIFT.items():
X.loc[X.index[rows], c] += d * u
elif kd == 1: # a stuck tool
c = LOGS[int(r() * 6)]
X.loc[X.index[rows], c] = X[c].iloc[top]
else: # a noisy tool
c = LOGS[int(r() * 6)]
for i in range(top, top + ln):
X.loc[X.index[i], c] += 5 * SIGMA[c] * gauss(r)
kind[rows] = kd
return X, kind
planted, kinds = [], []
for k, w in enumerate(wells):
X, kind = plant(k, df.loc[df["well"] == w, LOGS].copy())
planted.append(X.to_numpy())
kinds.append(kind)
Step 3: Leave One Well Out
For each well, standardize on the other eight, train the autoencoder to copy them, and score each of the held-out well's samples by its mean squared error over the six standardized logs; PCA from one component, fitted on the same eight, is the straight model beside it.
from sklearn.neural_network import MLPRegressor
from sklearn.decomposition import PCA
score_ae, score_pca = [], []
for k in range(len(wells)):
train = np.vstack([planted[j] for j in range(len(wells)) if j != k])
mu, sd = train.mean(axis=0), train.std(axis=0)
Z, Zk = (train - mu) / sd, (planted[k] - mu) / sd
ae = MLPRegressor(hidden_layer_sizes=(8, 1, 8),
activation="tanh", solver="adam",
learning_rate_init=0.01, batch_size=64,
max_iter=40, random_state=k).fit(Z, Z)
score_ae.append(((Zk - ae.predict(Zk)) ** 2).mean(axis=1))
pca = PCA(n_components=1).fit(Z)
back = pca.inverse_transform(pca.transform(Zk))
score_pca.append(((Zk - back) ** 2).mean(axis=1))
The book's kernel trains the same network, 6-8-1-8-6 with tanh in every hidden layer, by Adam at a learning rate of 0.01 in batches of 64 for 40 epochs. scikit-learn starts and steps its own way (and adds a small weight penalty), so its scores may differ from the kernel's; PCA's do not.
Step 4: The Area Under the ROC Curve
The area is the chance that a planted sample outscores a clean one. The book's kernel takes it by trapezoids under the curve, tied scores moving together; counting every planted and clean pair, a tie a half, gives the same number.
from sklearn.metrics import roc_auc_score
kind = np.concatenate(kinds)
y = (kind >= 0).astype(int)
s_ae, s_pca = np.concatenate(score_ae), np.concatenate(score_pca)
auc_ae, auc_pca = roc_auc_score(y, s_ae), roc_auc_score(y, s_pca)
def kind_auc(s, kd):
keep = (kind == -1) | (kind == kd)
return roc_auc_score(kind[keep] == kd, s[keep])
by_kind = {name: kind_auc(s_ae, kd) for kd, name in
enumerate(["washout", "stuck", "noisy"])}
The book's kernel gives 0.740 for the autoencoder and 0.567 for PCA, and by kind, for the autoencoder, washouts 0.968, noisy tools 0.739 and stuck tools 0.496; for PCA 0.652, 0.557 and 0.486. One straight direction through six logs and three rock types rebuilds most samples badly, faults or not; one bent unit follows the rocks and leaves the faults standing out.
Step 5: Flag the Worst of Each Well
def flag(scores, share=0.02):
out = []
for s in scores:
m = round(share * len(s))
top = np.argsort(-s, kind="stable")[:m]
f = np.zeros(len(s), bool)
f[top] = True
out.append(f)
return np.concatenate(out)
f = flag(score_ae)
caught_ft = (f & (y == 1)).sum() * dz
false_ft = (f & (y == 0)).sum() * dz
The book's kernel gives, flagging the worst 2 % of each well, 51.5 ft of the planted 191.5 ft caught and 56.5 ft of clean log flagged; at 1 %, 29.0 ft and 25.0 ft; at 5 %, 71.5 ft and 198.5 ft. The planted share of the wells is 0.035, so a rule that flags a fixed share of every well trades caught faults for false alarms at once.
What It Misses
Ogbon-5's stuck tool (gamma ray) at 5950.0 to 5956.5 ft holds one value for 7.0 ft, yet 383 of the well's clean samples score higher than any of it. A log frozen at its own last value reads a value the logs take every few feet, and the other five logs agree with it; it is wrong only in time, which a score taken sample by sample cannot see. A stuck tool is caught by a rule on a log's variance over a window, not by an autoencoder.
What It Flags That Is Not a Fault
Ogbon-8 sits 484.5 ft down the dip, and its tight limestone, alone of the nine wells', lies in the water leg: it reads log10 RT 0.63 on average against 2.09 in the other eight wells' limestone. No training well holds wet limestone, so of the 24 samples flagged in Ogbon-8, 23 are clean limestone. An autoencoder flags what is new to it, and new rock is not a fault: what it flags is a list to look at, not a verdict.
What an Autoencoder Is For
An autoencoder learns what the logs usually do from logs nobody has labelled, and its reconstruction error points at what they did not do. On these wells it finds the faults that break the logs' joint pattern and misses the one that keeps it, and it flags rock the training wells never showed it. Section 16.3, the chapter quiz, asks what Sections 16.1 and 16.2 computed.