Workshop: Classifying Rock Types with KNN
Learning objectives
- Load the book's learning set in Python and read each column's unit
- Score kNN on the nine wells with one well held out at a time, the scaler fitted on the training wells only
- Choose k from the curve of accuracy against k, and say why a flat curve makes the best k a weak choice
- Explain why no k rescues the porosity logs in the well that sits in the water leg, and what resistivity adds
Choose k on Wells the Model Has Not Seen
Section 5.1 scored kNN on Ogbon-1's own samples, which flatters it. Here it is scored the way a model of well logs must be: leave one well out. Train on eight of the field's nine wells, call every sample of the ninth, nine times over, and pool the calls. Rock types are easy this way, 0.999 right from the four porosity logs; pay is the hard question. On the porosity logs alone kNN calls 0.879 of the nine wells' 10809 samples right at its best k, 41, and with log10 RT 0.976 at k = 15. The logs a model reads decide more than its k.
The Data
The workshop reads the book's own learning set, the file the figure is computed from: ogbon-learning-set.csv, served beside this book at mlgeo-core/data/ogbon-learning-set.csv. It holds Ogbon-1, the Petrophysics book's synthetic well, and eight hypothetical appraisal wells of the book's field, 1201 half-foot samples each, their logs as the book's own tool model records them and their truth as the generator made it. Its comment lines name every unit: depth in ft, GR in API, RHOB in g/cc, NPHI in v/v, DT in us/ft, RT in ohm.m. Pay is the Petrophysics book's net-pay rule on the truth. 0.524 of the samples are pay, so a model that calls every sample pay is right 0.524 of the time: that is the number to beat. One well, Ogbon-8, lies down the structure in the water leg and has no pay at all.
Step 1: Load the Set
Read the file with its comment lines skipped, and build the two sets of logs the book uses: the porosity logs, and the porosity logs with resistivity worked in log10, because it spans decades.
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"])
POROSITY = ["GR_API", "RHOB_gcc",
"NPHI_vv", "DT_usft"]
WITH_RT = POROSITY + ["LRT"]
wells = df["well"]
print(df.groupby("well")["pay"].sum())
Step 2: One Well Held Out
A pipeline keeps the scaler inside each fold, so it is fitted on the eight training wells only and the held-out well is standardized with their means and standard deviations. LeaveOneGroupOut makes the nine folds from the well names.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import (
LeaveOneGroupOut, cross_val_predict)
def held_out_calls(cols, label, k):
model = make_pipeline(
StandardScaler(),
KNeighborsClassifier(n_neighbors=k))
return cross_val_predict(
model, df[cols], df[label],
groups=wells, cv=LeaveOneGroupOut())
lith = held_out_calls(POROSITY, "lith", 5)
print((lith == df["lith"]).mean())
For the rock types the book's kernel gives 0.999 at k = 5, 6.5 ft called the wrong rock in the nine wells. The three rocks sit as far apart in the other wells as in Ogbon-1.
Step 3: Pay, and the Curve of k
Score pay at each k of the book's table and plot the share called right against k for both sets of logs.
import matplotlib.pyplot as plt
KS = [1, 3, 5, 7, 9, 11, 15, 21,
25, 31, 41, 51]
for cols, name in [(POROSITY, "porosity logs"),
(WITH_RT, "with log10 RT")]:
acc = [(held_out_calls(cols, "pay", k)
== df["pay"]).mean() for k in KS]
plt.semilogx(KS, acc, "o-", label=name)
plt.xlabel("k")
plt.ylabel("share called right")
plt.legend()
plt.show()
The book's kernel gives, on the porosity logs, 0.791 at k = 1 rising to 0.879 at k = 41; with log10 RT, 0.970 at k = 1 and 0.976 at k = 15, its best, then 0.974 at k = 51. One neighbour copies the sample nearest it, the tool's noise and all; a wider vote averages the noise away. On the porosity logs the curve is flat from k = 25 on: k = 41 is best by one sample in 10809 over k = 31. A best k on a flat curve is a weak choice, and any k on the flat part would do as well.
Step 4: The Wells One by One
Pooling hides which well the model fails on. Score each well when it is the one held out.
pay = held_out_calls(POROSITY, "pay", 41)
right = pd.Series(pay == df["pay"])
print(right.groupby(wells).mean())
On the porosity logs at k = 41 the book's kernel calls Ogbon-8 right at only 0.357, and 386.0 ft of the 647.5 ft of false pay in the nine wells is in that one well. Ogbon-8 is in the water leg: its clean, porous sand reads on gamma ray, density, neutron and sonic like the other wells' oil sand, and 0.911 of the sandstone in the other eight wells is pay. No k can fix that, because the porosity logs cannot tell oil from brine. With log10 RT at k = 15 Ogbon-8 is called right at 0.868, and every other well at 0.955 or better.
Step 5: The Calls in Feet
A share hides which mistake is made. Count the calls in feet, half a foot to a sample.
from sklearn.metrics import confusion_matrix
pay = held_out_calls(WITH_RT, "pay", 15)
feet = 0.5 * confusion_matrix(df["pay"], pay)
print(feet)
With log10 RT at k = 15 the book's kernel calls 124.0 ft pay that is not and misses 8.0 ft of pay; on the porosity logs at k = 41, 647.5 ft false and 7.0 ft missed. The porosity logs' mistakes are almost all false pay: wet sand called oil sand.
Your Numbers and the Book's
scikit-learn's kNN is the same model, but your numbers may differ from the book's in the last digit: the file rounds each log (density to 0.0001 g/cc, for one), and a tied distance or vote can be broken another way. The best k here is chosen on the same folds it is scored on, which flatters it a little; Chapter 10 returns to that. A random split of the samples, which puts a well's neighbouring samples on both sides, would flatter more.