← All articles

By ·

Geographically Weighted Regression (GWR) Explained: When One Coefficient Is Not Enough, Tested on Punjab's 36 Districts

GWR vs OLS on Punjab's 36 districts: OLS left residual Moran's I at 0.36. GWR raised R² from 0.56 to 0.84 and found a slope three times steeper in the south.

Geographically weighted regression (GWR) fits a separate regression around every location, so a coefficient can change across a map. On Punjab's 36 districts, an ordinary regression of children out of school on women's literacy explained 56% of the variation but left its errors clustered in the south (Moran's I = 0.36). GWR raised R² to 0.84 and showed why: in the southern districts the slope was about three times steeper than around Faisalabad and Lahore.

This article walks through that test from start to finish: the global model, the residual check that says something spatial is missing, the GWR fit, how to read its maps without fooling yourself, and the simpler model that GWR pointed to.

What problem does GWR solve?

A standard regression, ordinary least squares (OLS), estimates one coefficient per predictor for the whole study area. That is a strong assumption. It says the effect of a predictor is the same in Rajanpur as in Rawalpindi.

When that assumption fails, two things go wrong:

  1. The coefficient becomes an average of different local relationships, and may describe no place well.
  2. The errors cluster in space. Districts where the true effect is stronger sit together on the map, and all of them get under-predicted together.

GWR, introduced by Brunsdon, Fotheringham and Charlton (1996), drops the assumption. For each location it fits a weighted regression in which nearby observations count more than distant ones. The output is a coefficient for every location, which you can map.

What data did I use?

The example uses district data that also sits behind this site's Punjab education map:

I kept to one predictor on purpose. With 36 observations, each local regression only has a couple of dozen neighbours to learn from, and one predictor keeps the method visible. The same district data was used for hot spot analysis with Moran's I and Getis-Ord Gi*, which is a good primer on the spatial statistics used below.

Step 1: Fit the global model

The OLS model is simple and, on its face, convincing:

TermCoefficientStd. errortp
Intercept32.503.1610.30< 0.001
Women's literacy (%)−0.3700.057−6.55< 0.001

R² = 0.56. Each 10-point rise in women's literacy goes with about 3.7 fewer percentage points of children out of school. Most reports would stop here.

Step 2: Check the residuals for spatial autocorrelation

Before trusting any regression on map data, map its residuals and test them. I used Queen contiguity weights, where districts that share a border are neighbours, and a permutation test with 9,999 draws.

Moran's I of the OLS residuals = 0.36, p < 0.001.

That is strong clustering. The three largest positive residuals, meaning more children out of school than literacy predicts, were all in the far south: Rahim Yar Khan (+12.0 points), Bahawalpur (+10.9) and Rajanpur (+10.6). The largest negative residuals were in the centre: Jhang (−7.7) and Chiniot (−6.0). The left map in the figure below shows the pattern.

Clustered residuals mean three things for the OLS model. Its standard errors are too small, so the p-value overstates certainty. Its single coefficient is an average across regions that behave differently. And there is a spatial process the model has not captured.

Step 3: Fit GWR

GWR needs two choices: a kernel, which sets how weight falls off with distance, and a bandwidth, which sets how far it reaches.

ModelR²Adj. R²AICcResidual Moran's I
OLS0.560.55216.40.36 (p < 0.001)
GWR (bw = 23)0.840.80196.80.10 (p = 0.12)

GWR used the equivalent of 6.8 parameters instead of 2 and still came out about 20 AICc points better, a large margin. Its residuals are no longer significantly clustered. A Monte Carlo test of whether the literacy coefficient really varies across space, in which the district locations are reshuffled and the model refitted, gave p < 0.02.

Three panels. Left: OLS residuals by Punjab district, positive in the south and negative in the centre. Middle: GWR local slope of women's literacy, steepest in the south-west and close to zero and not significant in the north-east. Right: scatter of out-of-school rate against women's literacy, with southern districts in red on a steeper line than the rest

Step 4: Read the coefficient map

The local slope for women's literacy ranged from −0.55 to −0.07:

DistrictDivisionLocal slopeSignificant?
Rahim Yar KhanBahawalpur−0.55Yes
RajanpurDera Ghazi Khan−0.55Yes
BahawalpurBahawalpur−0.52Yes
MultanMultan−0.45Yes
RawalpindiRawalpindi−0.19Yes
LahoreLahore−0.15No
JhangFaisalabad−0.12No
FaisalabadFaisalabad−0.07No

Averaged by division, the slope was −0.46 in Dera Ghazi Khan and −0.44 in Bahawalpur, against −0.11 in Faisalabad and Sahiwal. In plain words: in the south, a 10-point gain in women's literacy goes with about 5 fewer points of children out of school. In central Punjab it goes with about 1.

Significance needs care. GWR runs one test per location, 36 here, and the tests overlap because neighbouring regressions share data. A plain 5% threshold would flag too many. I used the correction of da Silva and Fotheringham (2016), built into mgwr as filter_tvals(). After it, the slope was significant in 21 of 36 districts. The 15 that were not, hatched in the middle map, form one block in central and north-eastern Punjab.

Is the variation really spatial, or just a curve?

This is the question I would ask of any GWR result, and it often goes unasked. If the true relationship is curved, flattening out as literacy rises, then low-literacy districts will show steep slopes and high-literacy districts flat ones. Because low-literacy districts cluster in the south, GWR will paint that curve as a spatial pattern.

So I tested non-spatial alternatives:

ModelParametersR²Residual Moran's I
OLS, straight line20.560.36 (p < 0.001)
OLS with a quadratic term30.640.25 (p = 0.007)
OLS on log of out-of-school rate20.620.35 (p = 0.001)
OLS with a south indicator and interaction40.760.01 (p = 0.34)
GWR6.8 effective0.840.10 (p = 0.12)

A curve helps a little but leaves the residuals clustered. A simple regional split does almost all the work. With an indicator for the three southern divisions (Bahawalpur, Dera Ghazi Khan and Multan, 11 districts) and its interaction with literacy, the slope is −0.59 in the south and −0.19 elsewhere, and the residual clustering disappears.

That is how I would use GWR in practice: as a diagnostic that finds where a relationship changes, followed by a simpler, explainable model that names the change. The likely reasons behind the southern pattern, such as poverty, distance to the nearest girls' school, and seasonal farm work in the cotton belt, are what the next model should measure directly.

How do you run GWR in Python?

The mgwr package from PySAL does bandwidth selection, fitting, inference and multiscale GWR:

import geopandas as gpd
import numpy as np
from libpysal.weights import Queen
from esda.moran import Moran
from mgwr.sel_bw import Sel_BW
from mgwr.gwr import GWR
import statsmodels.api as sm

g = gpd.read_file("punjab_districts.gpkg").to_crs(32643)  # projected, metres
y = g[["oos_primary"]].values
X = g[["lit_women"]].values

# 1. Global model and residual check
ols = sm.OLS(y, sm.add_constant(X)).fit()
w = Queen.from_dataframe(g); w.transform = "r"
print(Moran(ols.resid, w, permutations=9999).I)

# 2. Bandwidth by AICc, then GWR
coords = np.c_[g.centroid.x, g.centroid.y]
bw = Sel_BW(coords, y, X, kernel="bisquare", fixed=False).search(
    criterion="AICc", bw_min=8, bw_max=len(g))
res = GWR(coords, y, X, bw, kernel="bisquare", fixed=False).fit()

g["slope"] = res.params[:, 1]
g["slope_sig"] = res.filter_tvals()[:, 1] != 0   # corrected for multiple tests
g["local_r2"] = res.localR2.ravel()
print(bw, res.R2, res.aicc)

Three practical notes:

When is GWR the wrong tool?

What are the limits of this example?

What should you take from this?

Always map the residuals of a regression on spatial data and test them with Moran's I. If they cluster, a single coefficient is hiding something. GWR is a quick, honest way to see what: where the relationship is strong, where it fades, and whether the difference survives a correction for multiple tests. Then use what it shows to build a simpler model you can explain to a ministry or a client, with the regional difference written into it.

If you need a regression or targeting analysis on district, tract or customer data that accounts for where things are, email me at mahad.imran29@gmail.com.

Frequently asked questions

What is geographically weighted regression in simple terms?

Geographically weighted regression fits a separate regression at every location, using nearby observations with more weight than distant ones. Instead of one coefficient for the whole study area, you get a map of coefficients that shows where a relationship is stronger, weaker or absent.

When should I use GWR instead of OLS?

Fit OLS first and test its residuals for spatial autocorrelation with Moran's I. If the residuals cluster, the model is missing something spatial. GWR is a good next step when you suspect the relationship itself changes across space. In a test on Punjab's 36 districts, OLS residuals had a Moran's I of 0.36 (p < 0.001), and GWR raised R² from 0.56 to 0.84 and removed the significant residual clustering.

How many observations do you need for GWR?

There is no fixed rule, but each local regression needs enough neighbours to estimate its coefficients. With a few dozen units, like Punjab's 36 districts, GWR works as an exploratory tool with one or two predictors. For confident inference on several predictors, a few hundred observations is a more comfortable starting point.

What is the difference between GWR and MGWR?

Standard GWR uses one bandwidth for every coefficient, so every relationship is assumed to vary at the same spatial scale. Multiscale GWR (MGWR) gives each coefficient its own bandwidth, so one predictor can act globally while another varies locally. MGWR is usually the better default when you have several predictors and enough data.

How do I run GWR in Python?

Use the mgwr package from PySAL. Select a bandwidth with Sel_BW using AICc, fit the model with GWR(coords, y, X, bw).fit(), and read the local coefficients from results.params. Use results.filter_tvals() to mark coefficients that stay significant after correcting for the many local tests.

Let's talk.

Best way to reach me is email. I respond to most things.