Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

r - Is there a way to 'compress' an lm() object for later prediction?

Is there a way to 'compress' an object of class lm, so that I can save it to the disk and load it up later for use with predict.lm?

I have an lm object that ends up being ~142mb upon saving, and I have a hard time believing that predict.lm needs all of the original observations / fitted values / residuals etc. to make a linear prediction. Can I remove information so that the saved model is smaller?

I have tried setting some of the variables (fitted.values, residuals, etc.) to NA, but it seems to have no effect on the saved file size.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A couple of things:

  1. This question really is a duplicate.

  2. In the narrow sense model=FALSE as was already answered in another question.

  3. In a wider sense, predict(fit, newdata) really just does a matrix-vector multiplication so you could save just the vector of predictions and multiply it with a matrix.

  4. There are alternate fitting functions. Below is an example from fastLm() in RcppArmadillo which also happens to be faster.

See below for an illustration.

R> library(RcppArmadillo)
Loading required package: Rcpp
R> flm <- fastLm(Volume ~ Girth, data=trees)
R> predict(flm, newdata=trees[1:5,])             ## can predict as with lm()
[1]  5.10315  6.62291  7.63608 16.24803 17.26120
R> object.size(flm)                              ## tiny object size ...
3608 bytes
R> stdlm <- lm(Volume ~ Girth, data=trees)
R> object.size(stdlm)                            ## ... compared to what lm() has
20264 bytes
R> stdlm <- lm(Volume ~ Girth, data=trees, model=FALSE)
R> object.size(stdlm)                            ## ... even when model=FALSE
15424 bytes
R> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...