简体   繁体   中英

Calculating a polynomial kernel matrix in R

I am trying to compute a polynomial kernel matrix in R. I have a tribble given as below:

library(tidyverse)
tribble(
  ~x, ~y,
  -0.5, 1,
  -1, -1.5,
  -1.5, 1.5,
  1.5, -0.5,
  0.5, -0.5,
  ) %>% as.matrix()

I have already transformed it to a matrix but I want to calculate a polynomial kernel matrix (gram matrix) of degree 2 defined as 多项式函数

I want to have the matrix as below:

结果

I am aware of the vector recycling concept in R using outer() and base implementation but find it very challenging to code it up in R.

tcrossprod(df)**2
       [,1]    [,2]    [,3]   [,4]   [,5]
[1,] 1.5625  1.0000  5.0625 1.5625 0.5625
[2,] 1.0000 10.5625  0.5625 0.5625 0.0625
[3,] 5.0625  0.5625 20.2500 9.0000 2.2500
[4,] 1.5625  0.5625  9.0000 6.2500 1.0000
[5,] 0.5625  0.0625  2.2500 1.0000 0.2500

simply put: (df %*% t(df))^2

We can use crossprod

crossprod(t(df))^2

-output

#        [,1]    [,2]    [,3]   [,4]   [,5]
#[1,] 1.5625  1.0000  5.0625 1.5625 0.5625
#[2,] 1.0000 10.5625  0.5625 0.5625 0.0625
#[3,] 5.0625  0.5625 20.2500 9.0000 2.2500
#[4,] 1.5625  0.5625  9.0000 6.2500 1.0000
#[5,] 0.5625  0.0625  2.2500 1.0000 0.2500

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM