Skip to content

sklearn_model

py3dinterpolations.modelling.models.sklearn_model

Sklearn-compatible model wrapper.

SklearnModel(estimator, model_name='sklearn')

Bases: BaseModel

Wrapper for any sklearn estimator with fit/predict interface.

Handles classifiers (predict_proba) and regressors (predict).

Parameters:

Name Type Description Default
estimator SklearnEstimator

A sklearn estimator instance.

required
model_name str

Human-readable name for this model.

'sklearn'
Source code in py3dinterpolations/modelling/models/sklearn_model.py
19
20
21
def __init__(self, estimator: SklearnEstimator, model_name: str = "sklearn"):
    self._estimator = estimator
    self._model_name = model_name

fit(x, y, z, v)

Fit the sklearn estimator.

Source code in py3dinterpolations/modelling/models/sklearn_model.py
23
24
25
26
def fit(self, x: np.ndarray, y: np.ndarray, z: np.ndarray, v: np.ndarray) -> None:
    """Fit the sklearn estimator."""
    X = np.column_stack([x, y, z])
    self._estimator.fit(X, v)

predict(grid_x, grid_y, grid_z, **kwargs)

Predict on a regular grid.

Returns:

Type Description
InterpolationResult

InterpolationResult with shape (len(grid_z), len(grid_y), len(grid_x))

InterpolationResult

to match the convention of other models.

Source code in py3dinterpolations/modelling/models/sklearn_model.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def predict(
    self,
    grid_x: np.ndarray,
    grid_y: np.ndarray,
    grid_z: np.ndarray,
    **kwargs: object,
) -> InterpolationResult:
    """Predict on a regular grid.

    Returns:
        InterpolationResult with shape (len(grid_z), len(grid_y), len(grid_x))
        to match the convention of other models.
    """
    mx, my, mz = np.meshgrid(grid_x, grid_y, grid_z, indexing="ij")
    X = np.column_stack([mx.ravel(), my.ravel(), mz.ravel()])

    predictions = self._estimator.predict(X)
    interpolated = predictions.reshape(mx.shape)
    # Transpose from XYZ to ZYX to match pykrige convention
    interpolated = np.einsum("xyz->zyx", interpolated)

    probability = None
    if isinstance(self._estimator, SklearnClassifier):
        proba = self._estimator.predict_proba(X)
        probability = proba.reshape((*mx.shape, -1))

    return InterpolationResult(
        interpolated=interpolated,
        probability=probability,
    )