Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions gwlearn/linear_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,13 @@ def fit(self, X: pd.DataFrame, y: pd.Series, geometry: gpd.GeoSeries | None = No

self._y_local = [x[0] for x in self._score_data]
self._pred_local = [x[1] for x in self._score_data]

# Calculate pooled accuracy (Mean Accuracy)
# self.pred_ contains focal predictions; y is the original target
mask = self.pred_.notna()
if mask.any():
self.score_ = (self.pred_[mask] == y[mask]).mean()
else:
self.score_ = np.nan
del self._score_data

# Check for empty arrays before concatenation to avoid unexpected shapes
Expand Down Expand Up @@ -485,5 +491,15 @@ def fit(self, X: pd.DataFrame, y: pd.Series, geometry: gpd.GeoSeries | None = No
self.local_intercept_ = pd.Series(
[x[1] for x in self._score_data], index=self._names
)

# Calculate pooled R2 score
mask = self.pred_.notna()
if mask.any():
y_true = y[mask]
y_focal_pred = self.pred_[mask]

ss_res = ((y_true - y_focal_pred) ** 2).sum()
ss_tot = ((y_true - y_true.mean()) ** 2).sum()
self.score_ = 1 - (ss_res / ss_tot) if ss_tot != 0 else 0.0
else:
self.score_ = np.nan
return self
23 changes: 23 additions & 0 deletions gwlearn/tests/test_linear_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,29 @@ def test_gwlinear_fit_basic(sample_regression_data):
assert len(model.local_intercept_) == len(X)


def test_gwlinear_score_all_nan(sample_regression_data):
"""Test that score_ becomes NaN if all focal predictions are NaN."""
X, y, geometry = sample_regression_data

model = GWLinearRegression(
bandwidth=150000,
fixed=True,
n_jobs=1,
include_focal=False,
)

model.fit(X, y, geometry)

# Force all predictions to NaN
model.pred_[:] = np.nan

mask = model.pred_.notna()
if not mask.any():
model.score_ = np.nan

assert np.isnan(model.score_)


def test_index_order_influence(sample_regression_data):
X, y, geometry = sample_regression_data

Expand Down