[R-sig-Geo] computing the hat matrix for gwr in spgwr?

Roger Bivand Roger.Bivand at nhh.no
Wed Aug 4 16:49:58 CEST 2010


On Wed, 4 Aug 2010, Seth J Myers wrote:

> Hi,
>
> I'm trying to calculate the hat matrix for gwr by hand using matrix 
> manipulation in R.  The hope is that once I get it to match the output 
> that gwr gives, I can do the matrix algebra row-/column-wise.  This will 
> allow me to estimate the effective number of parameter using the trace 
> of the hat matrix on a data set that is too large to do this using the 
> computer resources I have using gwr as is.  The first row of the hat 
> matrix described on page 55 of fotheringham et als gwr book.  It is the 
> hat matrix multiplied by a distance-based weighting function.  The code 
> below returns 4.661219 for the trace while gwr returns 3.400793. 
> Anything jump out to anyone?  Thanks, Seth Myers

w[j,j] <- exp((-0.5) * ((dist/bw)^2)) matches gwr.Gauss()
w[j,j]<-exp(-((dist/bw)^2)) matches gwr.gauss()

gwr.Gauss() became default from spgwr 0.5. Otherwise OK.

Hope this helps,

Roger

>
> library(spgwr)
> data(columbus)
> bw=10
> crime.gwr<-gwr(crime~income, data=columbus, coords=cbind(columbus$x,columbus$y), bandwidth=bw,gweight=gwr.Gauss,longlat=FALSE,hatmatrix=TRUE)
> v1.gwr<-crime.gwr$results$v1 #what I am trying to calculate by hand, the trace of the S (or hat) matrix)
> xmat<-mat.or.vec(nrow(columbus),2)
> coor<-mat.or.vec(nrow(columbus),2)
> xmat[ ,1]<-1
> xmat[ ,2]<-columbus$income
> coor[ ,1]<-columbus$x
> coor[ ,2]<-columbus$y
> #creating matrices for use in following loops
> xtw<-mat.or.vec(2,nrow(columbus))
> w<-mat.or.vec(nrow(columbus),nrow(columbus))
> xrow<-mat.or.vec(1,2)
> smat<-mat.or.vec(nrow(columbus),nrow(columbus))
> for (i in 1:nrow(columbus)){
> print(i)
> for (j in 1:nrow(columbus)){
> dist<-( (coor[i,1]-coor[j,1])^2 + (coor[i,2]-coor[j,2])^2)^.5 #finding distances between observations
> w[j,j]<-exp(-((dist/bw)^2))#computing weight matrix for observation i
> }
> xtw<-t(xmat)%*%w #finding crossproduct of transpose of x matrix and w matrix
> xtwx<-xtw%*%xmat #finding crossproduct of above and x matrix
>
> xtwx.inv<-solve(xtwx) #finding inverse of above
>
> xrow<-xmat[i, ] #getting row i of x matrix
> x.xtwx.inv<-xrow%*%xtwx.inv # crossproduct of above and inverse of xtwx
> temp<-x.xtwx.inv%*%xtw #crossproduct of above and xtw
> smat[i, ]<-temp#populate row i of S matrix
> }
> mytry<-sum(diag(smat))#my try at calculating the trace of the S (or hat) matrix
>
> 	[[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at stat.math.ethz.ch
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Helleveien 30, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no



More information about the R-sig-Geo mailing list