0

I'm trying to find the optimum bandwidth for local regression (GWR), but I get an error which I don't understand how to fix. All my code runs fine until I ask for the optimum one. Any suggestions and/or explanations please? The purpose is to do spatial weighting, OLS, GWR and MGWR models, eventually though visualizing them with various maps.

# Get GWR model information
gwr_data.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3340 entries, 0 to 3339
Data columns (total 24 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   Neighbourhood      3340 non-null   object 
 1   PopDenKM           3340 non-null   int64  
 2   AvInc              3340 non-null   int64  
 3   NonImmPer          3340 non-null   float64
 4   ImmPer             3340 non-null   float64
 5   NoEduPer           3340 non-null   float64
 6   BacDegPer          3340 non-null   float64
 7   EmploymentRate     3340 non-null   float64
 8   UnemploymentRate   3340 non-null   float64
 9   TheftRate2016      3340 non-null   float64
 10  X                  3340 non-null   object 
 11  Y                  3340 non-null   object 
 12  NeighbourhoodName  3340 non-null   object 
 13  Location_Type      3340 non-null   object 
 14  Premises_Type      3340 non-null   object 
 15  Bike_Make          3340 non-null   object 
 16  Bike_Speed         3340 non-null   int64  
 17  Bike_Colour        3340 non-null   object 
 18  Cost_of_Bike       3340 non-null   float64
 19  Recovered          3340 non-null   int64  
 20  Stolen             3340 non-null   int64  
 21  Status             3340 non-null   object 
 22  Longitude          3340 non-null   object 
 23  Latitude           3340 non-null   object 
dtypes: float64(8), int64(5), object(11)
memory usage: 652.3+ KB

#Prepare dataset inputs
g_y = gwr_data['TheftRate2016'].values.reshape((-1,1))
g_X = gwr_data[['AvInc','NoEduPer','Cost_of_Bike', 'UnemploymentRate']].values
u = gwr_data['X']
v = gwr_data['Y']
g_coords = list(zip(u,v))
​
# Standardised our data to have mean of 0 and standard deviation of 1
g_X = (g_X - g_X.mean(axis=0)) / g_X.std(axis=0)
​
g_y = g_y.reshape((-1,1))
​
g_y = (g_y - g_y.mean(axis=0)) / g_y.std(axis=0)

# Select bandwidth for kernel
bw = mgwr.sel_bw.Sel_BW(g_coords, 
                  g_y, # Independent variable
                  g_X, # Dependent variable
                  fixed=False, # True for fixed bandwidth and false for adaptive bandwidth
                  spherical=True) # Spherical coordinates (long-lat) or projected coordinates

# Calculate the optimum bandwidth for our local regression?
bw.search()
---------------------------------------------------------------------------
TypingError                               Traceback (most recent call last)
Input In [201], in <cell line: 2>()
      1 # Calculate the optimum bandwidth for our local regression?
----> 2 bw.search()

File /opt/conda/lib/python3.9/site-packages/mgwr/sel_bw.py:319, in Sel_BW.search(self, search_method, criterion, bw_min, bw_max, interval, tol, max_iter, init_multi, tol_multi, rss_score, max_iter_multi, multi_bw_min, multi_bw_max, bws_same_times, pool, verbose)
    316     self.bw_init = self.bw[
    317         -1]  #scalar, optimal bw from initial gwr model
    318 else:
--> 319     self._bw()
    320     self.sel_hist = self.bw[-1]
    322 self.pool = None

File /opt/conda/lib/python3.9/site-packages/mgwr/sel_bw.py:337, in Sel_BW._bw(self)
    334     a, c = self._init_section(self.X_glob, self.X_loc, self.coords,
    335                               self.constant)
    336     delta = 0.38197  #1 - (np.sqrt(5.0)-1.0)/2.0
--> 337     self.bw = golden_section(a, c, delta, gwr_func, self.tol,
    338                              self.max_iter, self.int_score,
    339                              self.verbose)
    340 elif self.search_method == 'interval':
    341     self.bw = equal_interval(self.bw_min, self.bw_max, self.interval,
    342                              gwr_func, self.int_score, self.verbose)

File /opt/conda/lib/python3.9/site-packages/mgwr/search.py:62, in golden_section(a, c, delta, function, tol, max_iter, int_score, verbose)
     60     score_b = dict[b]
     61 else:
---> 62     score_b = function(b)
     63     dict[b] = score_b
     64     if verbose:

File /opt/conda/lib/python3.9/site-packages/mgwr/sel_bw.py:326, in Sel_BW._bw.<locals>.<lambda>(bw)
    325 def _bw(self):
--> 326     gwr_func = lambda bw: getDiag[self.criterion](GWR(
    327         self.coords, self.y, self.X_loc, bw, family=self.family, kernel=
    328         self.kernel, fixed=self.fixed, constant=self.constant, offset=self.
    329         offset, spherical=self.spherical).fit(lite=True, pool=self.pool))
    331     self._optimized_function = gwr_func
    333     if self.search_method == 'golden_section':

File /opt/conda/lib/python3.9/site-packages/mgwr/gwr.py:335, in GWR.fit(self, ini_params, tol, max_iter, solve, lite, pool)
    332 else:
    333     rslt = map(self._local_fit, range(m))  #sequential
--> 335 rslt_list = list(zip(*rslt))
    336 influ = np.array(rslt_list[0]).reshape(-1, 1)
    337 resid = np.array(rslt_list[1]).reshape(-1, 1)

File /opt/conda/lib/python3.9/site-packages/mgwr/gwr.py:248, in GWR._local_fit(self, i)
    244 def _local_fit(self, i):
    245     """
    246     Local fitting at location i.
    247     """
--> 248     wi = self._build_wi(i, self.bw).reshape(-1, 1)  #local spatial weights
    250     if isinstance(self.family, Gaussian):
    251         betas, inv_xtx_xt = _compute_betas_gwr(self.y, self.X, wi)

File /opt/conda/lib/python3.9/site-packages/mgwr/gwr.py:236, in GWR._build_wi(self, i, bw)
    233 def _build_wi(self, i, bw):
    235     try:
--> 236         wi = Kernel(i, self.coords, bw, fixed=self.fixed,
    237                     function=self.kernel, points=self.points,
    238                     spherical=self.spherical).kernel
    239     except BaseException:
    240         raise  # TypeError('Unsupported kernel function  ', kernel)

File /opt/conda/lib/python3.9/site-packages/mgwr/kernels.py:47, in Kernel.__init__(self, i, data, bw, fixed, function, eps, ids, points, spherical)
     43 def __init__(self, i, data, bw=None, fixed=True, function='triangular',
     44              eps=1.0000001, ids=None, points=None, spherical=False):
     46     if points is None:
---> 47         self.dvec = local_cdist(data[i], data, spherical).reshape(-1)
     48     else:
     49         self.dvec = local_cdist(points[i], data, spherical).reshape(-1)

File /opt/conda/lib/python3.9/site-packages/numba/core/dispatcher.py:468, in _DispatcherBase._compile_for_args(self, *args, **kws)
    464         msg = (f"{str(e).rstrip()} \n\nThis error may have been caused "
    465                f"by the following argument(s):\n{args_str}\n")
    466         e.patch_message(msg)
--> 468     error_rewrite(e, 'typing')
    469 except errors.UnsupportedError as e:
    470     # Something unsupported is present in the user code, add help info
    471     error_rewrite(e, 'unsupported_error')

File /opt/conda/lib/python3.9/site-packages/numba/core/dispatcher.py:409, in _DispatcherBase._compile_for_args.<locals>.error_rewrite(e, issue_type)
    407     raise e
    408 else:
--> 409     raise e.with_traceback(None)

TypingError: Failed in nopython mode pipeline (step: nopython frontend)
No implementation of function Function(<built-in function sub>) found for signature:
 
 >>> sub(array([unichr x 16], 1d, A), [unichr x 16])
 
There are 12 candidate implementations:
    - Of which 10 did not match due to:
    Overload of function 'sub': File: <numerous>: Line N/A.
      With argument(s): '(array([unichr x 16], 1d, A), [unichr x 16])':
     No match.
    - Of which 2 did not match due to:
    Operator Overload in function 'sub': File: unknown: Line unknown.
      With argument(s): '(array([unichr x 16], 1d, A), [unichr x 16])':
     No match for registered cases:
      * (int64, int64) -> int64
      * (int64, uint64) -> int64
      * (uint64, int64) -> int64
      * (uint64, uint64) -> uint64
      * (float32, float32) -> float32
      * (float64, float64) -> float64
      * (complex64, complex64) -> complex64
      * (complex128, complex128) -> complex128

During: typing of intrinsic-call at /opt/conda/lib/python3.9/site-packages/mgwr/kernels.py (24)

File "../../opt/conda/lib/python3.9/site-packages/mgwr/kernels.py", line 24:
def local_cdist(coords_i, coords, spherical):
    <source elided>
    if spherical:
        dLat = np.radians(coords[:, 1] - coords_i[1])
        ^
Tsyvarev
  • 60,011
  • 17
  • 110
  • 153

0 Answers0