Skip to content

openavmkit.inference

This module contains various inference models for predicting missing values in spatial datasets (e.g. you are missing some amount of building square footage). It uses proxy variables supplied by the user (e.g. building footprint size) and works out geospatial correlations to predict the missing values.

perform_spatial_inference() is the main function that orchestrates the inference process based on user settings.

CategoricalEncoder

CategoricalEncoder()

Universal categorical encoder that handles unseen categories.

Source code in openavmkit/inference.py
284
285
286
def __init__(self):
    self.label_encoder = LabelEncoder()
    self.unknown_value = None  # Will be set during fit

fit

fit(series)

Fit encoder adding a special unknown value.

Parameters:

Name Type Description Default
series Series

data series to fit

required
Source code in openavmkit/inference.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def fit(self, series: pd.Series) -> None:
    """Fit encoder adding a special unknown value.

    Parameters
    ----------
    series : pd.Series
        data series to fit
    """

    # Get unique non-null values
    unique_values = series.dropna().unique()

    # Add an extra category for unknown
    self.label_encoder.fit(np.append(unique_values, ["__UNKNOWN__"]))
    self.unknown_value = self.label_encoder.transform(["__UNKNOWN__"])[0]

fit_transform

fit_transform(series)

Fit and transform in one step.

Parameters:

Name Type Description Default
series Series

data series to fit & transform

required

Returns:

Type Description
ndarray

the transformed data series

Source code in openavmkit/inference.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
def fit_transform(self, series: pd.Series) -> np.ndarray:
    """Fit and transform in one step.

    Parameters
    ----------
    series : pd.Series
        data series to fit & transform

    Returns
    -------
    np.ndarray
        the transformed data series

    """
    self.fit(series)
    return self.transform(series)

transform

transform(series)

Transform values, mapping unseen categories to unknown.

Parameters:

Name Type Description Default
series Series

data series to transform

required

Returns:

Type Description
ndarray

the transformed data sereies

Source code in openavmkit/inference.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
def transform(self, series: pd.Series) -> np.ndarray:
    """Transform values, mapping unseen categories to unknown.

    Parameters
    ----------
    series : pd.Series
        data series to transform

    Returns
    -------
    np.ndarray
        the transformed data sereies
    """
    # Handle nulls first
    series = series.fillna("__UNKNOWN__")

    # Create output array
    result = np.full(len(series), self.unknown_value)

    # Get mask of known categories
    known_mask = series.isin(self.label_encoder.classes_)

    # Transform known categories
    if known_mask.any():
        result[known_mask] = self.label_encoder.transform(series[known_mask])

    return result

EnsembleModel

EnsembleModel()

Bases: InferenceModel

Ensemble model combining LightGBM, XGBoost, and Random Forest.

Source code in openavmkit/inference.py
934
935
936
937
938
939
940
941
942
943
944
def __init__(self):
    self.lgb_model = LightGBMModel()
    self.xgb_model = XGBoostModel()
    self.rf_model = RandomForestModel()
    self.weights = None
    self.encoders = {}
    self.proxy_fields = None
    self.location_fields = None
    self.interaction_fields = None
    self.imputer = SimpleImputer(strategy="median")
    self.feature_order = None

evaluate

evaluate(df, target)

Evaluate model performance.

Parameters:

Name Type Description Default
df DataFrame

DataFrame containing features and true target values.

required
target str

Name of the target variable column in df.

required

Returns:

Type Description
Dict[str, float]

Dictionary of evaluation metrics (e.g., R², RMSE).

Source code in openavmkit/inference.py
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
def evaluate(self, df: pd.DataFrame, target: str) -> Dict[str, float]:
    """
    Evaluate model performance.

    Parameters
    ----------
    df : pandas.DataFrame
        DataFrame containing features and true target values.
    target : str
        Name of the target variable column in `df`.

    Returns
    -------
    Dict[str, float]
        Dictionary of evaluation metrics (e.g., R², RMSE).
    """
    predictions = self.predict(df)
    actuals = df[target]

    metrics = {
        "mae": np.abs(predictions - actuals).mean(),
        "mape": np.abs((predictions - actuals) / actuals).mean() * 100,
        "rmse": np.sqrt(((predictions - actuals) ** 2).mean()),
        "r2": 1
        - ((predictions - actuals) ** 2).sum()
        / ((actuals - actuals.mean()) ** 2).sum(),
    }

    return metrics

fit

fit(df, target, settings)

Fit ensemble model and determine optimal weights.

Parameters:

Name Type Description Default
df DataFrame

Training data.

required
target str

Field name of the target variable.

required
settings Dict[str, Any]

Settings dictionary.

required
Source code in openavmkit/inference.py
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
def fit(self, df: pd.DataFrame, target: str, settings: Dict[str, Any]) -> None:
    """Fit ensemble model and determine optimal weights.

    Parameters
    ----------
    df : pd.DataFrame
        Training data.
    target : str
        Field name of the target variable.
    settings : Dict[str, Any]
        Settings dictionary.
    """
    proxies = settings.get("proxies", [])
    locations = [
        loc for loc in settings.get("locations", []) if loc != "___everything___"
    ]
    interactions = settings.get("interactions", [])

    # Format interaction fields
    self.interaction_fields = []
    for interaction in interactions:
        if isinstance(interaction, list):
            self.interaction_fields.append("_x_".join(interaction))
        else:
            self.interaction_fields.append(interaction)

    self.proxy_fields = proxies
    self.location_fields = locations

    # Split data for weight optimization
    df_train, df_val = train_test_split(df, test_size=0.2, random_state=42)

    # Fit individual models
    print("\nFitting LightGBM model...")
    self.lgb_model.fit(df_train, target, settings)
    print("\nFitting XGBoost model...")
    self.xgb_model.fit(df_train, target, settings)
    print("\nFitting Random Forest model...")
    self.rf_model.fit(df_train, target, settings)

    # Get predictions on validation set
    lgb_preds = self.lgb_model.predict(df_val)
    xgb_preds = self.xgb_model.predict(df_val)
    rf_preds = self.rf_model.predict(df_val)
    actuals = df_val[target].values.astype(
        float
    )  # Convert to numpy array and ensure float type

    # Optimize weights to minimize RMSE
    def objective(weights):
        ensemble_preds = (
            weights[0] * lgb_preds + weights[1] * xgb_preds + weights[2] * rf_preds
        )
        return np.sqrt(((ensemble_preds - actuals) ** 2).mean())

    initial_weights = np.array([1 / 3, 1 / 3, 1 / 3])
    bounds = [(0, 1), (0, 1), (0, 1)]
    constraints = {"type": "eq", "fun": lambda w: np.sum(w) - 1}

    result = minimize(
        objective, initial_weights, bounds=bounds, constraints=constraints
    )
    self.weights = result.x

    print("\nEnsemble weights:")
    print(f"--> LightGBM: {self.weights[0]:.4f}")
    print(f"--> XGBoost: {self.weights[1]:.4f}")
    print(f"--> Random Forest: {self.weights[2]:.4f}")

    # Fit final models on full data
    self.lgb_model.fit(df, target, settings)
    self.xgb_model.fit(df, target, settings)
    self.rf_model.fit(df, target, settings)

predict

predict(df)

Make predictions on new data.

Parameters:

Name Type Description Default
df DataFrame

Data to perform predictions on.

required

Returns:

Type Description
Series

Predicted values of the target variable chosen during fit()

Source code in openavmkit/inference.py
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
def predict(self, df: pd.DataFrame) -> pd.Series:
    """Make predictions on new data.

    Parameters
    ----------
    df : pd.DataFrame
        Data to perform predictions on.

    Returns
    -------
    pd.Series
        Predicted values of the target variable chosen during fit()
    """
    lgb_preds = self.lgb_model.predict(df)
    xgb_preds = self.xgb_model.predict(df)
    rf_preds = self.rf_model.predict(df)

    return pd.Series(
        self.weights[0] * lgb_preds
        + self.weights[1] * xgb_preds
        + self.weights[2] * rf_preds,
        index=df.index,
    )

InferenceModel

Bases: ABC

Base class for inference models.

evaluate abstractmethod

evaluate(df, target)

Evaluate model performance on training data.

Parameters:

Name Type Description Default
df DataFrame

Training data.

required
target str

Field name of the target variable.

required

Returns:

Type Description
Dict[str, float]

Dictionary containing the following metrics: "mae", "mape", "rmse", "r2"

Source code in openavmkit/inference.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
@abstractmethod
def evaluate(self, df: pd.DataFrame, target: str) -> Dict[str, float]:
    """Evaluate model performance on training data.

    Parameters
    ----------
    df : pd.DataFrame
        Training data.
    target : str
        Field name of the target variable.

    Returns
    -------
    Dict[str, float]
        Dictionary containing the following metrics: "mae", "mape", "rmse", "r2"
    """
    pass

fit abstractmethod

fit(df, target, settings)

Fit the model using training data.

Parameters:

Name Type Description Default
df DataFrame

Training data.

required
target str

Field name of the target variable.

required
settings Dict[str, Any]

Settings dictionary.

required

Returns:

Type Description
None
Source code in openavmkit/inference.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@abstractmethod
def fit(self, df: pd.DataFrame, target: str, settings: Dict[str, Any]) -> None:
    """
    Fit the model using training data.

    Parameters
    ----------
    df : pd.DataFrame
        Training data.
    target : str
        Field name of the target variable.
    settings : Dict[str, Any]
        Settings dictionary.

    Returns
    -------
    None
    """
    pass

predict abstractmethod

predict(df)

Make predictions on new data.

Parameters:

Name Type Description Default
df DataFrame

Data to perform predictions on.

required

Returns:

Type Description
Series

Predicted values of the target variable chosen during fit()

Source code in openavmkit/inference.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@abstractmethod
def predict(self, df: pd.DataFrame) -> pd.Series:
    """Make predictions on new data.

    Parameters
    ----------
    df : pd.DataFrame
        Data to perform predictions on.

    Returns
    -------
    pd.Series
        Predicted values of the target variable chosen during fit()
    """
    pass

LightGBMModel

LightGBMModel()

Bases: InferenceModel

LightGBM model with improved validation and parameters.

Source code in openavmkit/inference.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
def __init__(self):
    self.model = lgb.LGBMRegressor(
        n_estimators=200,
        max_depth=-1,
        num_leaves=31,
        learning_rate=0.05,
        subsample=0.8,
        colsample_bytree=0.8,
        reg_alpha=0.1,
        reg_lambda=0.1,
        random_state=42,
        n_jobs=-1,
    )
    self.encoders = {}
    self.proxy_fields = None
    self.location_fields = None
    self.interaction_fields = None
    self.imputer = SimpleImputer(strategy="median")
    self.feature_order = None  # Store the order of features from training

evaluate

evaluate(df, target)

Evaluate model performance.

Parameters:

Name Type Description Default
df DataFrame

DataFrame containing features and true target values.

required
target str

Name of the target variable column in df.

required

Returns:

Type Description
Dict[str, float]

Dictionary of evaluation metrics (e.g., R², RMSE).

Source code in openavmkit/inference.py
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
def evaluate(self, df: pd.DataFrame, target: str) -> Dict[str, float]:
    """
    Evaluate model performance.

    Parameters
    ----------
    df : pandas.DataFrame
        DataFrame containing features and true target values.
    target : str
        Name of the target variable column in `df`.

    Returns
    -------
    Dict[str, float]
        Dictionary of evaluation metrics (e.g., R², RMSE).
    """
    predictions = self.predict(df)
    actuals = df[target]

    metrics = {
        "mae": np.abs(predictions - actuals).mean(),
        "mape": np.abs((predictions - actuals) / actuals).mean() * 100,
        "rmse": np.sqrt(((predictions - actuals) ** 2).mean()),
        "r2": 1
        - ((predictions - actuals) ** 2).sum()
        / ((actuals - actuals.mean()) ** 2).sum(),
    }

    return metrics

fit

fit(df, target, settings)

Fit the model using training data.

Parameters:

Name Type Description Default
df DataFrame

Training data.

required
target str

Field name of the target variable.

required
settings Dict[str, Any]

Settings dictionary.

required
Source code in openavmkit/inference.py
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
def fit(self, df: pd.DataFrame, target: str, settings: Dict[str, Any]) -> None:
    """
    Fit the model using training data.

    Parameters
    ----------
    df : pd.DataFrame
        Training data.
    target : str
        Field name of the target variable.
    settings : Dict[str, Any]
        Settings dictionary.
    """

    proxies = settings.get("proxies", [])
    locations = [
        loc for loc in settings.get("locations", []) if loc != "___everything___"
    ]
    interactions = settings.get("interactions", [])

    # Format interaction fields
    self.interaction_fields = []
    for interaction in interactions:
        if isinstance(interaction, list):
            self.interaction_fields.append("_x_".join(interaction))
        else:
            self.interaction_fields.append(interaction)

    self.proxy_fields = proxies
    self.location_fields = locations

    # Create feature matrix
    X = self._create_feature_matrix(df, fit=True)
    y = df[target].values.astype(
        float
    )  # Convert to numpy array and ensure float type

    print("\nFitting LightGBM model:")
    print(f"Features being used: {list(X.columns)}")
    if self.interaction_fields:
        print(f"Interaction features: {self.interaction_fields}")

    # Fit model
    self.model.fit(X, y)

    # Print feature importances
    importances = pd.Series(
        self.model.feature_importances_, index=X.columns
    ).sort_values(ascending=False)

    print("\nFeature importances:")
    for feat, imp in importances.items():
        print(f"--> {feat}: {imp:.4f}")

    if self.interaction_fields:
        print("\nInteraction feature importances:")
        interaction_importances = importances[
            importances.index.isin(self.interaction_fields)
        ]
        for feat, imp in interaction_importances.items():
            print(f"--> {feat}: {imp:.4f}")

predict

predict(df)

Make predictions on new data.

Parameters:

Name Type Description Default
df DataFrame

Data to perform predictions on.

required

Returns:

Type Description
Series

Predicted values of the target variable chosen during fit()

Source code in openavmkit/inference.py
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
def predict(self, df: pd.DataFrame) -> pd.Series:
    """Make predictions on new data.

    Parameters
    ----------
    df : pd.DataFrame
        Data to perform predictions on.

    Returns
    -------
    pd.Series
        Predicted values of the target variable chosen during fit()
    """
    # Create feature matrix using same process as fit
    X = self._create_feature_matrix(df, fit=False)

    # Verify we have all features
    missing_features = set(self.feature_order) - set(X.columns)
    if missing_features:
        raise ValueError(f"Missing features during prediction: {missing_features}")

    return pd.Series(self.model.predict(X), index=df.index)

RandomForestModel

RandomForestModel()

Bases: InferenceModel

Random Forest with improved validation and parameters.

Source code in openavmkit/inference.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
def __init__(self):
    self.model = RandomForestRegressor(
        n_estimators=200,
        max_depth=None,
        min_samples_split=5,
        min_samples_leaf=2,
        max_features="sqrt",
        random_state=42,
        n_jobs=-1,
    )
    self.encoders = {}
    self.proxy_fields = None
    self.location_fields = None
    self.interaction_fields = None
    self.imputer = SimpleImputer(strategy="median")
    self.feature_order = None  # Store the order of features from training

evaluate

evaluate(df, target)

Evaluate model performance.

Parameters:

Name Type Description Default
df DataFrame

DataFrame containing features and true target values.

required
target str

Name of the target variable.

required

Returns:

Type Description
Dict[str, float]

Dictionary of evaluation metrics (e.g., R², RMSE).

Source code in openavmkit/inference.py
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
def evaluate(self, df: pd.DataFrame, target: str) -> Dict[str, float]:
    """
    Evaluate model performance.

    Parameters
    ----------
    df : pandas.DataFrame
        DataFrame containing features and true target values.
    target : str
        Name of the target variable.

    Returns
    -------
    Dict[str, float]
        Dictionary of evaluation metrics (e.g., R², RMSE).
    """
    predictions = self.predict(df)
    actuals = df[target]

    metrics = {
        "mae": np.abs(predictions - actuals).mean(),
        "mape": np.abs((predictions - actuals) / actuals).mean() * 100,
        "rmse": np.sqrt(((predictions - actuals) ** 2).mean()),
        "r2": 1
        - ((predictions - actuals) ** 2).sum()
        / ((actuals - actuals.mean()) ** 2).sum(),
    }

    return metrics

fit

fit(df, target, settings)

Fit the model using training data.

Parameters:

Name Type Description Default
df DataFrame

Training data.

required
target str

Field name of the target variable.

required
settings Dict[str, Any]

Settings dictionary.

required
Source code in openavmkit/inference.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def fit(self, df: pd.DataFrame, target: str, settings: Dict[str, Any]) -> None:
    """
    Fit the model using training data.

    Parameters
    ----------
    df : pd.DataFrame
        Training data.
    target : str
        Field name of the target variable.
    settings : Dict[str, Any]
        Settings dictionary.
    """

    proxies = settings.get("proxies", [])
    locations = [
        loc for loc in settings.get("locations", []) if loc != "___everything___"
    ]
    interactions = settings.get("interactions", [])

    # Format interaction fields
    self.interaction_fields = []
    for interaction in interactions:
        if isinstance(interaction, list):
            self.interaction_fields.append("_x_".join(interaction))
        else:
            self.interaction_fields.append(interaction)

    self.proxy_fields = proxies
    self.location_fields = locations

    # Create feature matrix
    X = self._create_feature_matrix(df, fit=True)
    y = df[target].values.astype(
        float
    )  # Convert to numpy array and ensure float type

    print("\nFitting Random Forest model:")
    print(f"Features being used: {list(X.columns)}")
    if self.interaction_fields:
        print(f"Interaction features: {self.interaction_fields}")

    # Fit model
    self.model.fit(X, y)

    # Print feature importances
    importances = pd.Series(
        self.model.feature_importances_, index=X.columns
    ).sort_values(ascending=False)

    print("\nFeature importances:")
    for feat, imp in importances.items():
        print(f"--> {feat}: {imp:.4f}")

    if self.interaction_fields:
        print("\nInteraction feature importances:")
        interaction_importances = importances[
            importances.index.isin(self.interaction_fields)
        ]
        for feat, imp in interaction_importances.items():
            print(f"--> {feat}: {imp:.4f}")

predict

predict(df)

Make predictions using best model.

Parameters:

Name Type Description Default
df DataFrame

Input DataFrame for making predictions.

required

Returns:

Type Description
Series

Predicted values from the best model.

Source code in openavmkit/inference.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
def predict(self, df: pd.DataFrame) -> pd.Series:
    """
    Make predictions using best model.

    Parameters
    ----------
    df : pandas.DataFrame
        Input DataFrame for making predictions.

    Returns
    -------
    pandas.Series
        Predicted values from the best model.
    """
    # Create feature matrix using same process as fit
    X = self._create_feature_matrix(df, fit=False)

    # Verify we have all features
    missing_features = set(self.feature_order) - set(X.columns)
    if missing_features:
        raise ValueError(f"Missing features during prediction: {missing_features}")

    return pd.Series(self.model.predict(X), index=df.index)

RatioProxyModel

RatioProxyModel()

Bases: InferenceModel

Ratio-based proxy model with proper validation handling.

Source code in openavmkit/inference.py
91
92
93
def __init__(self):
    self.proxy_ratios = {}
    self.proxy_stats = {}

evaluate

evaluate(df, target)

Evaluate model performance.

Parameters:

Name Type Description Default
df DataFrame

DataFrame containing features and true target values.

required
target str

Name of the target variable column in df.

required

Returns:

Type Description
Dict[str, float]

Dictionary of evaluation metrics (e.g., R², RMSE).

Source code in openavmkit/inference.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def evaluate(self, df: pd.DataFrame, target: str) -> Dict[str, float]:
    """
    Evaluate model performance.

    Parameters
    ----------
    df : pandas.DataFrame
        DataFrame containing features and true target values.
    target : str
        Name of the target variable column in `df`.

    Returns
    -------
    Dict[str, float]
        Dictionary of evaluation metrics (e.g., R², RMSE).
    """
    valid_mask = df[target].notna()
    predictions = self.predict(df[valid_mask])

    actuals = df.loc[valid_mask, target]

    # Calculate metrics
    metrics = {
        "mae": np.abs(predictions - actuals).mean(),
        "mape": np.abs((predictions - actuals) / actuals).mean() * 100,
        "rmse": np.sqrt(((predictions - actuals) ** 2).mean()),
        "r2": 1
        - ((predictions - actuals) ** 2).sum()
        / ((actuals - actuals.mean()) ** 2).sum(),
    }

    return metrics

fit

fit(df, target, settings)

Fit the model using training data.

Parameters:

Name Type Description Default
df DataFrame

Training data.

required
target str

Field name of the target variable.

required
settings Dict[str, Any]

Settings dictionary.

required
Source code in openavmkit/inference.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def fit(self, df: pd.DataFrame, target: str, settings: Dict[str, Any]) -> None:
    """
    Fit the model using training data.

    Parameters
    ----------
    df : pd.DataFrame
        Training data.
    target : str
        Field name of the target variable.
    settings : Dict[str, Any]
        Settings dictionary.
    """
    proxies = settings.get("proxies", [])
    locations = settings.get("locations", [])
    group_by = settings.get("group_by", [])

    # Add global grouping
    locations.append("___everything___")
    df["___everything___"] = "1"

    self.proxy_ratios = {}
    self.proxy_stats = {}

    # Calculate ratios for each proxy
    for proxy in proxies:
        # Handle missing values
        valid_mask = (
            df[target].notna()
            & df[proxy].notna()
            & df[proxy].gt(0)
            & df[target].gt(0)
        )

        if valid_mask.sum() == 0:
            warnings.warn(f"No valid data for proxy {proxy}")
            continue

        # Calculate ratios
        df_valid = df[valid_mask].copy()
        df_valid[f"ratio_{proxy}"] = df_valid[target] / df_valid[proxy]

        # Remove outliers
        q1, q99 = df_valid[f"ratio_{proxy}"].quantile([0.01, 0.99])
        valid_range = (df_valid[f"ratio_{proxy}"] >= q1) & (
            df_valid[f"ratio_{proxy}"] <= q99
        )
        df_valid = df_valid[valid_range]

        # Store global ratio
        global_ratio = df_valid[f"ratio_{proxy}"].median()
        self.proxy_ratios[(proxy, ())] = global_ratio

        # Calculate ratios for each location/group combination
        for location in locations:
            if location == "___everything___":
                continue

            group_list = group_by.copy() if group_by else []
            group_list.append(location)

            try:
                grouped = df_valid.groupby(group_list)
                median_ratios = grouped[f"ratio_{proxy}"].median()
                if not median_ratios.empty:
                    self.proxy_ratios[(proxy, tuple(group_list))] = median_ratios
            except Exception as e:
                warnings.warn(
                    f"Failed to calculate grouped ratios for {proxy} with groups {group_list}: {str(e)}"
                )

predict

predict(df)

Make predictions using fitted ratios.

Parameters:

Name Type Description Default
df DataFrame

Input DataFrame for making predictions.

required

Returns:

Type Description
Series

Predicted values.

Source code in openavmkit/inference.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def predict(self, df: pd.DataFrame) -> pd.Series:
    """
    Make predictions using fitted ratios.

    Parameters
    ----------
    df : pandas.DataFrame
        Input DataFrame for making predictions.

    Returns
    -------
    pandas.Series
        Predicted values.
    """
    predictions = pd.Series(index=df.index, dtype="float64")

    for proxy, group_list in sorted(
        self.proxy_ratios.keys(), key=lambda x: len(x[1]), reverse=True
    ):
        if len(group_list) > 0:
            try:
                # Get group-specific ratios
                group_key = df[list(group_list)].astype(str).agg("_".join, axis=1)
                ratios = self.proxy_ratios[(proxy, group_list)]

                # Only apply ratios for existing group combinations
                common_keys = group_key[group_key.isin(ratios.index)]
                if not common_keys.empty:
                    # Create initial mask
                    mask = (
                        predictions.isna()
                        & df[proxy].notna()
                        & df[proxy].gt(0)
                        & group_key.isin(ratios.index)
                    )

                    # Additional validation
                    proxy_values = df.loc[mask, proxy]
                    ratio_values = ratios[group_key[mask]]
                    predicted_values = ratio_values * proxy_values

                    # Create validation mask aligned with original mask
                    valid_predictions = pd.Series(False, index=df.index)
                    valid_predictions.loc[mask] = (predicted_values > 100) & (
                        predicted_values < 100000
                    )

                    # Combine masks
                    final_mask = mask & valid_predictions

                    # Apply predictions
                    predictions.loc[final_mask] = predicted_values[
                        valid_predictions[mask]
                    ]
            except Exception as e:
                warnings.warn(
                    f"Failed to apply grouped ratios for {proxy} with groups {group_list}: {str(e)}"
                )
        else:
            # Apply global ratio to remaining missing values
            ratio = self.proxy_ratios[(proxy, ())]
            mask = predictions.isna() & df[proxy].notna() & df[proxy].gt(0)

            # Additional validation for global ratio
            proxy_values = df.loc[mask, proxy]
            predicted_values = ratio * proxy_values

            # Create validation mask aligned with original mask
            valid_predictions = pd.Series(False, index=df.index)
            valid_predictions.loc[mask] = (predicted_values > 100) & (
                predicted_values < 100000
            )

            # Combine masks
            final_mask = mask & valid_predictions

            # Apply predictions
            predictions.loc[final_mask] = ratio * df.loc[final_mask, proxy]

    return predictions

XGBoostModel

XGBoostModel()

Bases: InferenceModel

XGBoost model with improved validation and parameters.

Source code in openavmkit/inference.py
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
def __init__(self):
    self.model = xgb.XGBRegressor(
        n_estimators=200,
        max_depth=6,
        learning_rate=0.05,
        subsample=0.8,
        colsample_bytree=0.8,
        reg_alpha=0.1,
        reg_lambda=0.1,
        random_state=42,
        n_jobs=-1,
    )
    self.encoders = {}
    self.proxy_fields = None
    self.location_fields = None
    self.interaction_fields = None
    self.imputer = SimpleImputer(strategy="median")
    self.feature_order = None  # Store the order of features from training

evaluate

evaluate(df, target)

Evaluate model performance.

Parameters:

Name Type Description Default
df DataFrame

DataFrame containing features and true target values.

required
target str

Name of the target variable column in df.

required

Returns:

Type Description
Dict[str, float]

Dictionary of evaluation metrics (e.g., R², RMSE).

Source code in openavmkit/inference.py
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
def evaluate(self, df: pd.DataFrame, target: str) -> Dict[str, float]:
    """
    Evaluate model performance.

    Parameters
    ----------
    df : pandas.DataFrame
        DataFrame containing features and true target values.
    target : str
        Name of the target variable column in `df`.

    Returns
    -------
    Dict[str, float]
        Dictionary of evaluation metrics (e.g., R², RMSE).
    """
    predictions = self.predict(df)
    actuals = df[target]

    metrics = {
        "mae": np.abs(predictions - actuals).mean(),
        "mape": np.abs((predictions - actuals) / actuals).mean() * 100,
        "rmse": np.sqrt(((predictions - actuals) ** 2).mean()),
        "r2": 1
        - ((predictions - actuals) ** 2).sum()
        / ((actuals - actuals.mean()) ** 2).sum(),
    }

    return metrics

fit

fit(df, target, settings)

Fit model with proper categorical handling and interactions.

Parameters:

Name Type Description Default
df DataFrame

Training data.

required
target str

Field name of the target variable.

required
settings Dict[str, Any]

Settings dictionary.

required
Source code in openavmkit/inference.py
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
def fit(self, df: pd.DataFrame, target: str, settings: Dict[str, Any]) -> None:
    """
    Fit model with proper categorical handling and interactions.

    Parameters
    ----------
    df : pd.DataFrame
        Training data.
    target : str
        Field name of the target variable.
    settings : Dict[str, Any]
        Settings dictionary.
    """
    proxies = settings.get("proxies", [])
    locations = [
        loc for loc in settings.get("locations", []) if loc != "___everything___"
    ]
    interactions = settings.get("interactions", [])

    # Format interaction fields
    self.interaction_fields = []
    for interaction in interactions:
        if isinstance(interaction, list):
            self.interaction_fields.append("_x_".join(interaction))
        else:
            self.interaction_fields.append(interaction)

    self.proxy_fields = proxies
    self.location_fields = locations

    # Create feature matrix
    X = self._create_feature_matrix(df, fit=True)
    y = df[target].values.astype(
        float
    )  # Convert to numpy array and ensure float type

    print("\nFitting XGBoost model:")
    print(f"Features being used: {list(X.columns)}")
    if self.interaction_fields:
        print(f"Interaction features: {self.interaction_fields}")

    # Fit model
    self.model.fit(X, y)

    # Print feature importances
    importances = pd.Series(
        self.model.feature_importances_, index=X.columns
    ).sort_values(ascending=False)

    print("\nFeature importances:")
    for feat, imp in importances.items():
        print(f"--> {feat}: {imp:.4f}")

    if self.interaction_fields:
        print("\nInteraction feature importances:")
        interaction_importances = importances[
            importances.index.isin(self.interaction_fields)
        ]
        for feat, imp in interaction_importances.items():
            print(f"--> {feat}: {imp:.4f}")

predict

predict(df)

Make predictions on new data.

Parameters:

Name Type Description Default
df DataFrame

Data to perform predictions on.

required

Returns:

Type Description
Series

Predicted values of the target variable chosen during fit()

Source code in openavmkit/inference.py
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
def predict(self, df: pd.DataFrame) -> pd.Series:
    """Make predictions on new data.

    Parameters
    ----------
    df : pd.DataFrame
        Data to perform predictions on.

    Returns
    -------
    pd.Series
        Predicted values of the target variable chosen during fit()
    """
    # Create feature matrix using same process as fit
    X = self._create_feature_matrix(df, fit=False)

    # Verify we have all features
    missing_features = set(self.feature_order) - set(X.columns)
    if missing_features:
        raise ValueError(f"Missing features during prediction: {missing_features}")

    return pd.Series(self.model.predict(X), index=df.index)

perform_spatial_inference

perform_spatial_inference(df, s_infer, key, verbose=False)

Perform spatial inference using specified model(s)

Parameters:

Name Type Description Default
df DataFrame

Input GeoDataFrame

required
s_infer dict

Inference settings from config

required
key str

Key field name

required
verbose bool

Whether to print progress

False

Returns:

Type Description
GeoDataFrame

GeoDataFrame with inferred values

Source code in openavmkit/inference.py
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
def perform_spatial_inference(
    df: gpd.GeoDataFrame, s_infer: dict, key: str, verbose: bool = False
) -> gpd.GeoDataFrame:
    """Perform spatial inference using specified model(s)

    Parameters
    -----------
    df : pd.DataFrame
        Input GeoDataFrame
    s_infer : dict
        Inference settings from config
    key : str
        Key field name
    verbose : bool
        Whether to print progress

    Returns
    -------
    gpd.GeoDataFrame
        GeoDataFrame with inferred values
    """
    # Suppress all numpy warnings for the entire inference process
    with np.errstate(all="ignore"):
        df_out = df.copy()
        for field in s_infer:
            entry = s_infer[field]
            df_out = _do_perform_spatial_inference(
                df_out, entry, field, key, verbose=verbose
            )
        return df_out