Frozen feature tables for T1-T3, TF-IDF + logistic regression and DistilBERT baselines with grouped splits, T4/C4 question answering (zero-shot, few-shot, RAG, tool_only, agent), Qwen zero-shot T2, paired well-cluster bootstrap and the G2 coverage report. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
183 lines
8.7 KiB
Python
183 lines
8.7 KiB
Python
"""Grouped classical baselines and the two classification OCR diagnostics."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from tempfile import TemporaryDirectory
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
from sklearn.base import BaseEstimator, TransformerMixin
|
|
from sklearn.compose import ColumnTransformer
|
|
from sklearn.feature_extraction.text import TfidfVectorizer
|
|
from sklearn.impute import SimpleImputer
|
|
from sklearn.linear_model import LogisticRegression
|
|
from sklearn.model_selection import GridSearchCV, GroupKFold, LeaveOneGroupOut, cross_val_predict
|
|
from sklearn.pipeline import Pipeline
|
|
from sklearn.preprocessing import StandardScaler
|
|
|
|
from . import labels
|
|
from .m34 import interval_overlap
|
|
from .m34_features import DELIMITER
|
|
from .names import well_of
|
|
|
|
|
|
class FormationProfile(TransformerMixin, BaseEstimator):
|
|
"""Describe proximity to formation tops of training wells using a regional depth profile."""
|
|
|
|
def __init__(self, picks):
|
|
self.picks = picks
|
|
|
|
def fit(self, X, y=None):
|
|
self.training_wells_ = set(X["well"])
|
|
return self
|
|
|
|
def transform(self, X):
|
|
out = np.zeros((len(X), 2))
|
|
for well, local in X.reset_index(drop=True).groupby("well", sort=False):
|
|
picks = self.picks[self.picks["well"].isin(self.training_wells_ - {well})]
|
|
tops = picks.groupby("surface")["md"].median().sort_values().to_numpy()
|
|
if len(tops):
|
|
depth = local["md_top"].to_numpy()
|
|
nearest = np.abs(depth[:, None] - tops).min(axis=1)
|
|
out[local.index] = np.column_stack([np.searchsorted(tops, depth, side="right"), nearest])
|
|
return out
|
|
|
|
|
|
def picks_for_training(root):
|
|
picks = pd.read_parquet(root / "witsml/formation_tops.parquet", columns=["wellbore", "surface", "md"])
|
|
picks = picks.dropna().copy()
|
|
picks["well"] = picks["wellbore"].map(well_of)
|
|
return picks[["well", "surface", "md"]]
|
|
|
|
|
|
def datasets(tables, protocol):
|
|
definitions = protocol["tasks"]["t2"]["npt_definition"]
|
|
yield "t1", "section", "masked", tables["t1"], "target"
|
|
for definition in (definitions["primary"], definitions["sensitivity"]):
|
|
for mode in ("masked", "unmasked"):
|
|
yield "t2", definition, mode, tables["t2"], f"npt_{definition}"
|
|
yield "t3", definition, mode, tables["t3"], f"label_{definition}"
|
|
|
|
|
|
def numeric_columns(frame):
|
|
permitted = {"md_top", "depth_from_own_top", "depth_samples", "max_hole_md"}
|
|
return [c for c in frame if c in permitted or c.startswith("witsml_")]
|
|
|
|
|
|
def model_inputs(frame, mode, modality):
|
|
allowed = ["well", *numeric_columns(frame)]
|
|
x = frame[allowed].copy()
|
|
x["text"] = frame[f"text_{modality}"].fillna("")
|
|
if mode == "unmasked":
|
|
x["text"] += DELIMITER + frame["codes"].fillna("")
|
|
return x
|
|
|
|
|
|
def text_model(x, settings, picks=None, cache=None):
|
|
prep = [("text", TfidfVectorizer(ngram_range=(1, 2), min_df=settings["tfidf_min_df"],
|
|
sublinear_tf=True, max_features=60000), "text")]
|
|
if nums := numeric_columns(x):
|
|
prep.append(("numeric", Pipeline([
|
|
("impute", SimpleImputer(strategy="median", add_indicator=True, keep_empty_features=True)),
|
|
("scale", StandardScaler()),
|
|
]), nums))
|
|
if picks is not None:
|
|
prep.append(("formation", Pipeline([("profile", FormationProfile(picks)), ("scale", StandardScaler())]),
|
|
["well", "md_top"]))
|
|
return Pipeline([("encoding", ColumnTransformer(prep, sparse_threshold=1.0)),
|
|
("logistic", LogisticRegression(max_iter=300))], memory=cache)
|
|
|
|
|
|
def fold_prediction(train_x, train_y, tune, variants, task, settings, n_splits, picks):
|
|
with TemporaryDirectory(prefix="volve-dia-fold-") as cache:
|
|
return fit_fold(train_x, train_y, tune, variants, task, settings, n_splits, picks, cache)
|
|
|
|
|
|
def fit_fold(train_x, train_y, tune, variants, task, settings, n_splits, picks, cache):
|
|
estimator = text_model(train_x, settings, picks, cache)
|
|
inner = GroupKFold(n_splits=n_splits)
|
|
search = GridSearchCV(estimator, {"logistic__C": settings["logistic_c"]}, cv=inner, error_score="raise",
|
|
scoring="accuracy" if task == "t1" else "average_precision")
|
|
tune_x, tune_y, tune_groups = train_x.iloc[tune], train_y[tune], train_x["well"].iloc[tune]
|
|
search.fit(tune_x, tune_y, groups=tune_groups)
|
|
model = search.best_estimator_
|
|
threshold = 0.5
|
|
if task == "t3":
|
|
oof = cross_val_predict(model, tune_x, tune_y, groups=tune_groups, cv=inner, method="predict_proba")[:, 1]
|
|
threshold = max(settings["t3_thresholds"], key=lambda t: interval_overlap(
|
|
tune_y, oof >= t, np.ones(len(tune_y), dtype=np.int64)))
|
|
if len(tune) != len(train_x):
|
|
model.fit(train_x, train_y)
|
|
result = {}
|
|
for modality, test_x in variants.items():
|
|
if task == "t1":
|
|
prediction = model.predict(test_x)
|
|
scores = np.full(len(prediction), np.nan)
|
|
else:
|
|
scores = model.predict_proba(test_x)[:, 1]
|
|
prediction = scores >= threshold
|
|
result[modality] = prediction, scores
|
|
return result, search.best_params_["logistic__C"], threshold
|
|
|
|
|
|
def prediction_rows(frame, task, target, definition, mode, group, method, modality, values, scores, seed=-1):
|
|
columns = ["item", "well", "wellbore", target]
|
|
columns += [c for c in ("subset", "c4", "date_flag", "cause_b") if c in frame]
|
|
result = frame[columns].copy()
|
|
if "subset" not in result:
|
|
result["subset"] = "all"
|
|
return result.rename(columns={target: "target"}).assign(
|
|
target=lambda d: d["target"].astype(str), prediction=np.asarray(values).astype(str), score=scores,
|
|
task=task, definition=definition, mode=mode, split=group, method=method, modality=modality, seed=seed)
|
|
|
|
|
|
def cheap_baselines(task, target, train, test):
|
|
if task == "t1":
|
|
most = train[target].mode().iat[0]
|
|
return {"majority": (np.repeat(most, len(test)), np.full(len(test), np.nan))}
|
|
prevalence = float(train[target].mean())
|
|
majority = np.repeat(float(prevalence >= 0.5), len(test))
|
|
output = {"majority": (majority.astype(bool), majority)}
|
|
if task == "t2":
|
|
length = LogisticRegression().fit(train[["comment_length"]], train[target])
|
|
scores = length.predict_proba(test[["comment_length"]])[:, 1]
|
|
expression = "|".join(f"(?:{term})" for term in labels.load_config()["text_lexicon"]["npt"])
|
|
hits = test["text_xml"].str.contains(expression, flags=re.IGNORECASE, regex=True).to_numpy()
|
|
output |= {"comment_length": (scores >= 0.5, scores), "lexicon": (hits, hits.astype(float))}
|
|
return output
|
|
|
|
|
|
def classical(tables, protocol, spec, root, task_filter=None):
|
|
settings = spec["classification"]
|
|
configurations = protocol["splits"]
|
|
picks = picks_for_training(root)
|
|
for task, definition, mode, frame, target in datasets(tables, protocol):
|
|
if task_filter is not None and task != task_filter:
|
|
continue
|
|
frame = frame.reset_index(drop=True)
|
|
x = model_inputs(frame, mode, "xml")
|
|
c4 = task in ("t1", "t2") and mode == "masked" and definition != "a"
|
|
ocr = model_inputs(frame, mode, "ocr") if c4 else None
|
|
for group in (configurations["group"], configurations["sensitivity_group"]):
|
|
groups = frame[group]
|
|
for train_idx, test_idx in LeaveOneGroupOut().split(x, frame[target], groups=groups):
|
|
train, test = frame.iloc[train_idx], frame.iloc[test_idx]
|
|
tune = np.flatnonzero(~train["well"].isin(test["well"]).to_numpy())
|
|
variants = {"xml": x.iloc[test_idx]}
|
|
if group == "well" and c4:
|
|
variants["ocr"] = ocr.iloc[test_idx]
|
|
out, c, threshold = fold_prediction(
|
|
x.iloc[train_idx], train[target].to_numpy(), tune,
|
|
variants, task, settings, configurations["inner"]["n_splits"], picks if task == "t3" else None)
|
|
for modality, (values, scores) in out.items():
|
|
use = test["c4"].to_numpy() if modality == "ocr" else np.ones(len(test), dtype=bool)
|
|
if use.any():
|
|
yield prediction_rows(test.iloc[np.flatnonzero(use)], task, target, definition, mode, group,
|
|
"tfidf_logistic", modality, values[use], scores[use]).assign(
|
|
logistic_c=c, threshold=threshold)
|
|
if mode == "masked":
|
|
for method, (values, scores) in cheap_baselines(task, target, train, test).items():
|
|
yield prediction_rows(test, task, target, definition, mode, group, method,
|
|
"xml", values, scores)
|