Workshop: Linear Regression on Well-Log Data

Chapter 4, Linear Models, Regression and Classification

Learning objectives

  • Load the book's learning set in Python and split it leave one well out
  • Score linear regression of porosity on wells it never saw, and explain why it carries from well to well
  • Score logistic regression of pay one well held out, and read its confusion matrix, recall and precision at a threshold
  • Draw the ROC curve, read its area, and explain why the porosity logs alone call Ogbon-8's water leg pay

One Well Held Out

A score is honest only on rock the model has not seen. This workshop holds out one well at a time: the model is fitted on eight of the field's nine wells and calls the ninth, and the calls of all nine are pooled. Its confusion matrix counts the four outcomes at one threshold, and its ROC curve shows every threshold at once. Held out this way, logistic regression from the porosity logs and log10 RT calls 0.986 of the nine wells' 10809 samples right at a threshold of 0.50, and the area under its ROC curve is 0.993. From the porosity logs alone it calls 0.874 right, with an area of 0.813, and Ogbon-8, the well wholly in the water leg, only 0.361: the porosity logs read the rock, not its fluid.

Logistic On Nine WellsInteractive figure, enable JavaScript to interact.

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, so they carry a stated noise; porosity and pay are the generator's truth, pay by the Petrophysics book's net-pay rule. The whole set is synthetic, and that is why every number below can be checked. Of its samples 5667 are pay, 2833.5 ft, and Ogbon-8, the well furthest down the structure, holds none. Calling every sample its larger class would score 0.524: the number any model must beat.

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, as in Section 4.1.

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"])
dz = df["depth_ft"].diff().iloc[1]
print(df.shape)
print(df.groupby("well", sort=False)["pay"].sum())

The book's kernel gives 10809 rows, 1201 for each well, and pay in every well but Ogbon-8.

Step 2: Leave One Well Out

Why a Whole Well

A random split of the samples would put the sample half a foot above each test sample in the training set, and the tool averages a few feet of rock, so neighbouring samples are nearly the same reading: the model would be marked on rock it has seen. Holding out a whole well asks the question a field asks, what a model fitted on the wells drilled will say of the next one. Chapter 10 measures how much a random split flatters.

from sklearn.model_selection import LeaveOneGroupOut

wells = df["well"].to_numpy()
folds = list(LeaveOneGroupOut().split(df, groups=wells))
for train, test in folds:
    print(wells[test[0]], len(train), len(test))

The book's kernel gives nine folds: each trains on 9608 samples, eight wells, and tests on the 1201 of the ninth.

Step 3: Porosity on Wells It Never Saw

Linear Regression, Held Out

The linear model of Section 4.1, porosity from the four porosity logs, fitted on eight wells and asked about the ninth.

from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

LOGS = ["GR_API", "RHOB_gcc", "NPHI_vv", "DT_usft"]
X = df[LOGS].to_numpy()
phi = df["PHI_vv"].to_numpy()
phi_hat = np.zeros(len(df))
for train, test in folds:
    model = LinearRegression().fit(X[train], phi[train])
    phi_hat[test] = model.predict(X[test])
rmse = np.sqrt(mean_squared_error(phi, phi_hat))
r2 = r2_score(phi, phi_hat)
print(f"RMSE {rmse:.3f} v/v, R2 {r2:.3f}")

The book's kernel gives an RMSE of 0.016 v/v and an R2R^2 of 0.950 held out, as on Ogbon-1 alone in Section 4.1; from density alone 0.056 v/v and 0.407. The same beds and the same physics run through every well, so the line from the logs to porosity carries from well to well.

Step 4: Pay on Wells It Never Saw

Logistic Regression, Held Out

Each fold's logs are standardized on its own training wells only: a scaler fitted on all nine wells would let the held-out well shape its own inputs. The book's kernel fits the mean log loss plus λ2∥𝐰∥2\tfrac{\lambda}{2}\lVert\mathbf w\rVert^2 with λ=0.0001\lambda = 0.0001; scikit-learn fits CC times the summed log loss plus 12∥𝐰∥2\tfrac12\lVert\mathbf w\rVert^2, the same problem when C=1/(λn)C = 1/(\lambda n), with nn the training samples.

from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler

def held_out_pay(cols, l2=1e-4):
    X = df[cols].to_numpy()
    y = df["pay"].to_numpy()
    prob = np.zeros(len(df))
    for train, test in folds:
        scale = StandardScaler().fit(X[train])
        C = 1.0 / (l2 * len(train))
        model = LogisticRegression(C=C, tol=1e-10,
                                   max_iter=10000)
        model.fit(scale.transform(X[train]), y[train])
        p = model.predict_proba(scale.transform(X[test]))
        prob[test] = p[:, 1]
    return prob

y = df["pay"].to_numpy()
prob_a = held_out_pay(LOGS)
prob_b = held_out_pay(LOGS + ["LRT"])
for name, prob in [("porosity logs", prob_a),
                   ("and log10 RT", prob_b)]:
    call = (prob >= 0.5).astype(int)
    print(name, (call == y).mean().round(3))

The book's kernel gives 0.874 of the samples called right from the porosity logs and 0.986 with log10 RT.

Step 5: The Confusion Matrix

Four Counts at One Threshold

A call is one of four: pay called pay (a true positive, TPTP), pay missed (FNFN), other rock called pay (FPFP) and other rock called not pay (TNTN). Recall, TP/(TP+FN)TP/(TP + FN), is the share of the pay found; precision, TP/(TP+FP)TP/(TP + FP), the share of the pay calls that are pay.

from sklearn.metrics import confusion_matrix

call = (prob_b >= 0.5).astype(int)
tn, fp, fn, tp = confusion_matrix(y, call).ravel()
print(tp, fn, fp, tn)
print("recall", round(tp / (tp + fn), 3))
print("precision", round(tp / (tp + fp), 3))

The book's kernel gives, with log10 RT at 0.50, 5617 pay samples called pay, 50 missed, 100 samples of other rock called pay and 5042 called not pay: a recall of 0.991 and a precision of 0.983.

Step 6: The ROC Curve

Every Threshold at Once

As the threshold falls from 1 to 0 the model calls more samples pay, and the share of pay found and the share of other rock called pay both rise: the ROC curve plots one against the other. Its area is the chance that a pay sample drawn at random gets a higher probability than a sample of other rock, so it scores the ranking, not any one call.

import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, roc_auc_score

for name, prob in [("porosity logs", prob_a),
                   ("and log10 RT", prob_b)]:
    fpr, tpr, thr = roc_curve(y, prob)
    auc = roc_auc_score(y, prob)
    plt.plot(fpr, tpr, label=f"{name}, AUC {auc:.3f}")
plt.plot([0, 1], [0, 1], "--", color="grey")
plt.xlabel("Other rock called pay (share)")
plt.ylabel("Pay found (share)")
plt.legend()
plt.show()

The book's kernel gives an area of 0.813 from the porosity logs and 0.993 with log10 RT.

Step 7: Each Well Held Out

Where the Model Fails

A pooled share can hide a well the model cannot call. 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 0.361 from the porosity logs, with 383.5 ft of its wet reservoir called pay, and 1.000 with log10 RT. Ogbon-8 lies wholly in the water leg: its sands and limestone have the porosity of pay in the wells up the structure, and only resistivity sees that they are wet. With log10 RT the hardest well is Ogbon-4, at 0.953: 1.5 ft of pay missed and 26.5 ft called pay that is not, all of it clean rock that holds oil but is too tight to pass the porosity cutoff of 0.08.

Step 8: The Threshold

One Model, Many Calls

The threshold does not change the model; it chooses a point on its ROC curve. Count the feet missed and the feet called pay that is not.

for t in [0.1, 0.5, 0.9]:
    call = (prob_b >= t).astype(int)
    missed = ((call == 0) & (y == 1)).sum() * dz
    false = ((call == 1) & (y == 0)).sum() * dz
    print(t, missed, "ft missed,", false, "ft false")

The book's kernel gives, with log10 RT, 4.5 ft missed and 115.0 ft false at 0.10, 25.0 ft and 50.0 ft at 0.50, and 155.5 ft and 34.0 ft at 0.90. Which mistake costs more, a missed zone or a completion in wet rock, is the geologist's to say.

What These Scores Are

These scores are on wells the model never saw, and they are the fairest the book has given so far. They are still kind: every well of the set carries Ogbon-1's beds, moved down the structure and their porosity scaled by the book's lateral model, and one tool model logs them all. Real wells differ more, in their rocks, their tools and their boreholes.

This page is prerendered for SEO and accessibility. The interactive widgets above hydrate on JavaScript load.