user24318
user24318

Reputation: 485

compute gram matrix in R

I need some help to compute a nXn gram matrix K for a given kernel. Here is my R code that generates simulated data. I could be any positive definite matrix. Taking diagonal matrix for simplicity.

     set.seed(3)
     n=20
     x=runif(n)
     y=rnorm(n)
    df<-cbind(x,y)

  I=diag(2)

kernel<-function(x,y) {
    t(x)%*%I%*%y
     }
   # for example 
#K[1,1]
    t(df[1,])%*%I%*%df[1,]
          [,1]
    [1,] 0.5829376
#K[1,2]
t(df[1,])%*%I%*%df[2,]
          [,1]
[1,] 0.978207

Upvotes: 2

Views: 1093

Answers (1)

Isadore Nabi
Isadore Nabi

Reputation: 11

Example in the case of a linear regression model for a database call data with a response Y and predictors X1 and X2:

#The regression model
model=lm(Y~X1+X2, data)

#Estimating residuals
r=model$res

#Estimating hat values
h=hatvalues(model)

#Computing Gramm matrix
d=r/(1-h)

#Estimating Gramm determinant (which summarizes the information in the Gramm matrix)
press=t(d)%*%d
round(press,2)

I hope, despite the delay, this may be useful for someone. Best regards.

Upvotes: 1

Related Questions