12

When I use the following R code,

model_glm=glm(V1~. , data=xx,family="binomial");
save(file="modelfile",model_glm);

The size of modelfile will be as much as the data, which will be 1gig in my case. How can I remove the data part in the result of model_glm, so I can only save a small file.

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
Indicator
  • 361
  • 2
  • 13

4 Answers4

11

Setting model = FALSE in your call to glm should prevent the model.frame from being returned. Also setting y = FALSE will prevent the response vector from being returned. x = FALSE is the default setting and prevents the model.matrix from being returned.

This combination should shrink the size of your glm object.

Of course, you can also extract the coefficients with coef(model_glm) or, with standard errors,

summary(model_glm)$coef
BenBarnes
  • 19,114
  • 6
  • 56
  • 74
  • 1
    Have you looked at resulting model? It is still very heavy: residuals, fitted values and the full qr matrix. The `biglm` package returns much lighter model objects. – hadley Nov 15 '12 at 04:00
  • Yes, the `bigglm` function may be a viable alternative. If you post it an an answer, it'd get a vote from me. Nonetheless, it's still possible to select only the desired components from the `glm` object before saving. – BenBarnes Nov 15 '12 at 05:34
8

I had this issue where I was running the GLM as part of an R in production and the size of the GLM greatly slowed me down. I found I needed to kill off more than just the $data. Here is my post on it, with an example below.

> object.size(sg)
96499472 bytes
> sg$residuals <- NULL
> sg$weights <- NULL
> sg$fitted.values <- NULL
> sg$prior.weights <- NULL
> sg$na.action<- NULL
> sg$linear.predictors <- NULL
> sg$fitted.values <- NULL
> sg$effects <-NULL
> sg$data <- NULL
> object.size(sg)
3483976 bytes
> sg$qr$qr <- NULL
> object.size(sg)
79736 bytes
Nic
  • 6,211
  • 10
  • 46
  • 69
Levi Bowles
  • 81
  • 1
  • 2
1

object.size() is misleading because it ignores the environment attributes. If you want to assess the true size, use:

length(serialize(model_glm, NULL))

Apart from the data stored, if you want to significantly reduce the size of your glm do:

rm(list=ls(envir = attr(model_glm$terms, ".Environment")),
     envir = attr(model_glm$terms,
              ".Environment"))

This comes from a well detailed article

T.Gulea
  • 101
  • 1
  • 3
0

You can NULL the data in the model object before saving it. I did a quick test and still generated predictions.

model_glm$data <- NULL
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Anon
  • 1