r - Map Reduce base R 中的线性回归

标签 r mapreduce linear-regression

我正在为 Hadoop 在 R 中进行分布式线性回归计算,但在实现之前,我想验证我的计算是否与 lm 的结果一致功能。

我有以下函数试图实现 Andrew Ng 等人讨论的通用“求和”框架。在论文中Map-Reduce for Machine Learning on Multicore .

对于线性回归,这涉及将每一行 y_i 和 x_i 映射到 P_i 和 Q_i,这样:

P_i = x_i * transpose(x_i)
Q_i = x_i * y_i

然后减少求解系数,theta: theta = (sum(P_i))^-1 * sum(Q_i)

执行此操作的 R 函数是:

calculate_p <- function(dat_row) {
  dat_row %*% t(dat_row)
}

calculate_q <- function(dat_row) {
  dat_row[1,1] * dat_row[, -1]
}

calculate_pq <- function(dat_row) {
  c(calculate_p(matrix(dat_row[-1], nrow=1)), calculate_q(matrix(dat_row, nrow=1)))
}

map_pq <- function(dat) {
  t(apply(dat, 1, calculate_pq))
}

reduce_pq <- function(pq) {
  (1 / sum(pq[, 1])) * apply(pq[, -1], 2, sum)
}

您可以通过运行以下命令在一些合成数据上实现它:

X <- matrix(rnorm(20*5), ncol = 5)
y <- as.matrix(rnorm(20))
reduce_pq(map_pq(cbind(y, X)))
[1]  0.010755882 -0.006339951 -0.034797768  0.067438662 -0.033557351
coef(lm.fit(X, y))
          x1           x2           x3           x4           x5 
-0.038556283 -0.002963991 -0.195897701  0.422552974 -0.029823962

不幸的是,输出不匹配,所以显然我做错了什么。有什么办法可以解决吗?

最佳答案

reduce_pq 中的逆矩阵需要是逆矩阵。我也稍微改变了一些功能。

calculate_p <- function(dat_row) { 
    dat_row %*% t(dat_row)
}

calculate_q <- function(dat_row) { 
    dat_row[1] * dat_row[-1] 
}

calculate_pq <- function(dat_row) {
    c(calculate_p(dat_row[-1]), calculate_q(dat_row)) 
}

map_pq <- function(dat) {
    t(apply(dat, 1, calculate_pq))
}

reduce_pq <- function(pq) { 
    solve(matrix(apply(pq[, 1:(ncol(X) * ncol(X))], 2, sum), nrow=ncol(X))) %*% apply(pq[, 1:ncol(X) + ncol(X)*ncol(X)], 2, sum)
}


set.seed(1)
X <- matrix(rnorm(20*5), ncol = 5)
y <- as.matrix(rnorm(20))

t(reduce_pq(map_pq(cbind(y, X))))
          [,1]      [,2]      [,3]       [,4]        [,5]
[1,] 0.1236914 0.2482445 0.5120975 -0.1104451 -0.04080922

coef(lm.fit(X,y))
         x1          x2          x3          x4          x5 
 0.12369137  0.24824449  0.51209753 -0.11044507 -0.04080922 

> all.equal(as.numeric(t(reduce_pq(map_pq(cbind(y, X))))), as.numeric(coef(lm.fit(X,y))))
[1] TRUE

关于r - Map Reduce base R 中的线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12829577/

相关文章:

python - 分析异常 : u"cannot resolve 'name' given input columns: [ list] in sqlContext in spark

r - R 中的假设检验

r - 在 dplyr 中一起使用 summarize_all 和 summarize

r - 将由left_join()产生的所有列前缀为原始表名

java - 在我们所有商店中按产品类别查找销售明细

Hadoop:中间合并失败

hadoop - 在 AWS Elastic Map Reduce 中禁用 Gzip 输入解压缩

r - 当我的随机森林混淆矩阵显示该模型不擅长预测疾病时,为什么我的 ROC 图和 AUC 值看起来不错?

r - 按列名称对数据框中的值进行排序

r - 如何在 r 中拟合指数回归?(又名基数变化幂)