Workshop: Naive Bayes on the Nine Wells
Learning objectives
- Score Gaussian naive Bayes of pay in Python, one well held out at a time, and set it against logistic regression
- Measure how strongly the porosity logs correlate within a class, and explain what that does to naive Bayes
- Show that naive Bayes does better on fewer, less redundant logs
- Read how sure naive Bayes's posteriors are against how often they are right
Where Independence Fails
Naive Bayes takes the logs as independent within a class, and the porosity logs are not: in the pay, density, neutron and sonic all measure porosity, and neutron and density correlate at −0.932. Held out one well at a time, naive Bayes from the porosity logs calls 0.873 of the nine wells' 10809 samples right, as good as logistic regression's 0.874. Add log10 RT and logistic regression rises to 0.986, naive Bayes only to 0.937: it counts one porosity three times, and three logs saying porous rock outvote the one log that sees the oil. From gamma ray, density and log10 RT alone it does better, 0.969.
The Data
The workshop reads the book's own learning set as a CSV file, mlgeo-core/data/ogbon-learning-set.csv on this site: Ogbon-1, the Petrophysics book's well, and Ogbon-2 to Ogbon-9, the book's own hypothetical appraisal wells, 1201 samples each every 0.5 ft, 10809 in all. The logs are the book's own tool model of Ogbon-1's build; pay is the generator's truth by the Petrophysics book's net-pay rule, 5667 samples. The whole set is synthetic, and that is why every number below can be checked.
Each step below gives its code and then what the book's kernel gives for the same computation on the same set.
Step 1: Load the Set
One Row per Half Foot
The file's comment lines name the source and each column's unit; pandas skips them. Resistivity is worked in log10.
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"])
print(df.shape)
print(df["pay"].sum())
The book's kernel gives 10809 rows and 5667 samples of pay.
Step 2: Leave One Well Out
A Whole Well at a Time
As in Section 4.2, each fold trains on eight wells and tests on the ninth, so the model is never marked on rock it has seen.
from sklearn.model_selection import LeaveOneGroupOut
wells = df["well"].to_numpy()
folds = list(LeaveOneGroupOut().split(df, groups=wells))
print(len(folds))
The book's kernel gives nine folds, each testing on 1201 samples.
Step 3: Naive Bayes, Held Out
One Bell Curve per Log and Class
Each fold's logs are standardized on its training wells, and the model's variances are floored at times the largest, the book's setting and scikit-learn's default. The priors are the training wells' shares of pay.
from sklearn.naive_bayes import GaussianNB
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
POR = ["GR_API", "RHOB_gcc", "NPHI_vv", "DT_usft"]
y = df["pay"].to_numpy()
def held_out_nb(cols):
X = df[cols].to_numpy()
prob = np.zeros(len(df))
for train, test in folds:
nb = GaussianNB(var_smoothing=1e-9)
model = make_pipeline(StandardScaler(), nb)
model.fit(X[train], y[train])
p = model.predict_proba(X[test])
prob[test] = p[:, 1]
return prob
prob_a = held_out_nb(POR)
prob_b = held_out_nb(POR + ["LRT"])
for name, prob in [("porosity logs", prob_a),
("and log10 RT", prob_b)]:
print(name, ((prob >= 0.5) == y).mean().round(3))
The book's kernel gives 0.873 from the porosity logs and 0.937 with log10 RT. Section 4.2's logistic regression, held out the same way, gives 0.874 and 0.986.
Step 4: Each Well Held Out
The Water Leg
Score each well on its own.
right = pd.DataFrame({
"well": wells,
"porosity logs": (prob_a >= 0.5) == y,
"and log10 RT": (prob_b >= 0.5) == y,
})
print(right.groupby("well", sort=False).mean().round(3))
The book's kernel gives Ogbon-8, the well wholly in the water leg, 0.362 from the porosity logs and only 0.628 with log10 RT, the hardest well of the nine either way; logistic regression with log10 RT calls all of it right, 1.000. Ogbon-8's wet sands read porous on three logs and wet on one, and naive Bayes adds one log likelihood per log.
Step 5: The Porosity Logs Correlate
One Fact, Three Logs
Within each class, how strongly do density, neutron and sonic move together?
logs = ["RHOB_gcc", "NPHI_vv", "DT_usft"]
print(df.groupby("pay")[logs].corr().round(3))
The book's kernel gives, in the pay, −0.932 between density and neutron, −0.955 between density and sonic and 0.938 between neutron and sonic: porous rock reads low density, high neutron and slow sonic together. In the samples that are not pay, a mixture of shale, wet sand and tight rock, density and neutron correlate at −0.485. The naive model treats each as a separate witness.
Step 6: Fewer Logs
Drop the Witnesses That Repeat
Keep one porosity log, or none.
for cols in [["GR_API", "RHOB_gcc", "LRT"],
["GR_API", "LRT"]]:
prob = held_out_nb(cols)
print(cols, ((prob >= 0.5) == y).mean().round(3))
The book's kernel gives 0.969 from gamma ray, density and log10 RT, with Ogbon-8 at 0.858, and 0.970 from gamma ray and log10 RT alone: better than 0.937 from all five logs. For naive Bayes a log that repeats another is not more evidence but the same evidence counted again.
Step 7: Sure and Wrong
A Posterior Is Not a Share
Counting one fact three times also makes the model too sure. Count the samples whose posterior of pay is at least 0.99 or under 0.01, and how many of those are called wrong.
sure = (prob_b >= 0.99) | (prob_b < 0.01)
wrong = (prob_b >= 0.5) != y
print(sure.mean().round(3), (sure & wrong).sum())
The book's kernel gives, with log10 RT, 0.792 of the samples sure and 273 of those called wrong; logistic regression is that sure of 0.789 of them and wrong on 53. The figure's plate (c) sorts the posteriors into tenths: among the samples naive Bayes gives a posterior of pay between 0.6 and 0.7, only 0.455 are pay.
Step 8: Lithology
Where Naive Bayes Is Enough
The same model on the three rocks.
lith = df["lith"].to_numpy()
X = df[POR].to_numpy()
call = np.empty(len(df), dtype=object)
for train, test in folds:
nb = GaussianNB(var_smoothing=1e-9)
model = make_pipeline(StandardScaler(), nb)
model.fit(X[train], lith[train])
call[test] = model.predict(X[test])
print((call == lith).mean().round(3))
The book's kernel gives 0.995. The three rocks sit far apart on the porosity logs, so even a likelihood of the wrong shape points to the right rock; pay asks for a fine line in porosity and fluid, and there the shape matters.
What These Scores Are
These scores are on wells the model never saw. They are still kind: every well of the set carries Ogbon-1's beds and one tool model logs them all. The lesson carries to real wells, where the porosity logs are as redundant as here: give naive Bayes logs that each say something the others do not.