I’m working on a distributed linear regression calculation in R for Hadoop, but before implementing it, I’d like to verify that my calculations agree with the results of the lm function.
I have the following functions which attempt to implement the generic “summation” framework discussed by Andrew Ng et al. in the paper Map-Reduce for Machine Learning on Multicore.
For linear regression, this involves mapping each row y_i and x_i to P_i and Q_i such that:
P_i = x_i * transpose(x_i)
Q_i = x_i * y_i
Then reducing to solve for the coefficients, theta:
theta = (sum(P_i))^-1 * sum(Q_i)
The R functions to do this are:
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)
}
You can implement it on some synthetic data by running:
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
Unfortunately, the outputs don’t match, so obviously I’m doing something wrong. Any ideas how I can fix it?
The inverse you take in
reduce_pqneeds to be a matrix inverse. Also I changed some of the functions a little bit.