我应该在 R 中使用 crossprod 还是基函数来计算两个向量距离的平方范数?

Should I use crossprod or base functions in R to calculate squared norm of distace of two vectors?

我在很多地方看到过(比如in the rbfdot function here and here)人们用下面的公式计算两个向量距离的平方范数

R 编程语言中,这变为

crossprod(x) - 2*crossprod(x, y) + crossprod(y)

在上面的链接以及许多其他地方,人们使用上面的 r 公式来计算两个向量距离的平方范数。但是,我试图通过简单地对条目进行平方和求和来对其进行基准测试,即

sum( (x-y)^2 )

在我看来,基础 R 版本更快:

# Create reproducible vectors
set.seed(123)
n <- 10^7
x <- rnorm(n)
y <- rnorm(n)
system.time(crossprod(x) - 2*crossprod(x, y) + crossprod(y))
#   user  system elapsed 
#  0.054   0.000   0.054 
system.time(sum( (x-y)^2 ))
#   user  system elapsed 
#  0.027   0.024   0.051

我错过了什么?

我想知道哪个选项更快,因为我正在尝试编写代码以使用 RBF 函数获取内核矩阵。

crossprod() 是一个非常隐蔽的函数,应该被更多地使用。要比较计算时间,您应该使用能够更精确地进行计算的包。

我们可以使用microbenchmark包比较计算时间:

set.seed(123)
n <- 10^8
x <- rnorm(n)
y <- rnorm(n)
microbenchmark::microbenchmark(crossprod(x) - 2*crossprod(x, y) + crossprod(y), 
                               crossprod(x-y), 
                               sum((x-y)^2))


Unit: milliseconds
                                              expr      min       lq      mean   median        uq      max neval cld
 crossprod(x) - 2 * crossprod(x, y) + crossprod(y) 470.7079 491.7889  537.0879 502.9029  525.2929 1392.929   100  a 
                                  crossprod(x - y) 533.9799 575.4948  870.1463 588.7248  615.8091 4524.261   100   b
                                    sum((x - y)^2) 542.8631 589.2234 1087.4885 610.5433 1220.1261 5423.189   100   b