R中加权最小二乘方协方差矩阵的加速逆 [英] Speed-up inverse of weighted least squares covariance matrix in R

查看:181
本文介绍了R中加权最小二乘方协方差矩阵的加速逆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要加快R中WLS协方差矩阵的逆的计算速度,其中矩阵wls.cov.matrix由(下面的完整示例)给出:

I need to speed up the calculation of the inverse of a WLS covariance matrix in R, where the matrix, wls.cov.matrix, is given by (full example below):

n = 10000
X = matrix(c(rnorm(n,1,2), sample(c(1,-1), n, replace = TRUE), rnorm(n,2,0.5)), nrow = 1000, ncol = 3)
Q = diag(rnorm(n, 1.5, 0.3))
wls.cov.matrix = solve(t(X)%*%diag(1/diag(Q))%*%X)

是否可以加快计算速度?

Is it possible to speed up this calculation?

与最终目标非常相关的更多信息: 这仍然是很少的信息,请允许我解释更多我的目标,并且如果可以加快我的代码的速度,将会更加清楚.
我运行了10,000次wls.cov.matrix,所以我需要它要快得多.

MORE INFO VERY RELEVANT TO THE FINAL GOAL: This is still little information, let me explain more my goal and will be clearer if there are ways to speed up my code.
I run 1,0000s of times wls.cov.matrix so I need it to be much faster.

但是,每次运行时,我都使用相同的X,唯一改变的矩阵是Q,这是一个对角矩阵.

However, each time I run it I use the same X, the only matrix that changes is Q, which is a diagonal matrix.

如果X是与Q一样暗的方阵,我可以预先计算X^-1(X^T)^(-1)

If X was a square matrix, of same dim as Q, I could just precompute X^-1 and (X^T)^(-1),

X.inv = solve(X)
X.inv.trans = solve(t(X))

,然后对于每次迭代运行:

and then for each iteration run:

Q.inv = diag(1/diag(Q))
wls.cov.matrix = X.inv%*%Q.inv%*%X.inv.trans

但是我的X不是方形的,所以还有其他技巧吗?

But my X is not square, so is there any other trick?

推荐答案

这里主要的耗时部分是t(X)%*%diag(1/diag(Q))%*%X,而不是其反函数的计算.

The main time-consuming part here is t(X)%*%diag(1/diag(Q))%*%X, not the calculation of its inverse.

一个不错的技巧是将其计算为

A nice trick is to calculate it as

crossprod(X / sqrt(diag(Q)));

确认:

all.equal( (t(X) %*% diag(1/diag(Q)) %*% X) , crossprod(X / sqrt(diag(Q))) );

[1] TRUE

要比较计时运行:

Qdiag = diag(Q);
system.time({(t(X) %*% diag(1/Qdiag) %*% X)})
system.time({crossprod(X / sqrt(Qdiag))})

这篇关于R中加权最小二乘方协方差矩阵的加速逆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆