Yashwanth
Yashwanth

Reputation: 79

How to save coefficients of polynomial linear model of degree 2 and make predicton later in R?

I have 50k customers data. I have to fit a poly linear model for each customer and save coefficients instead of saving the complete model. I want to multiply these coefficients with input features data and get a response value. for one customer model looks like ,

data <- data.table(x=c(6.831,20.34083,33.85067, 47.3605, 60.87033, 74.38017, 87.89),
           y=c(0.2098555,0.1593422,0.1191542,0.08804057,0.06445684,0.0468659 
               0.03390175))
model2 <- lm(y ~ poly(x, 2), data)
predict.lm(model2, data[,"x"])

I'll fit a model using this data . in future I get matrix 50k x 7, where each row represents data points for the model, I have to make a prediction on each row using respective customer's model

Upvotes: 0

Views: 398

Answers (2)

Adamm
Adamm

Reputation: 2306

Triss answer is correct, however I'd like to also leave a few words. Firstly show several rows of your data. Yes you can save the coefficients in df and use them later, you can just use below commands in loop:

coefs <- t(as.data.frame(coef(model2)))
res <- rbind(res,coefs)

Why do you want to multiply the coefs and what are the input features? Coefs will tell you about the direction of relation between predictor (explanatory) variables and response variable. For example if coef > 0 it means that both variables increase. Be sure that your model is built using only significant exploratory variables, check it using summary(model2) otherwise the prediction and conclusions may be wrong. Nevertheless you need whole model to do some predictions. The predict.lm will give you the value of response variable that you are looking for (e.g. the amount of the employee's raise) using given exploratory variables (employee performance, age, gender, experience etc.) as input. You can achieve this using model built with the use of data that you already have (for some number of employees). This is a type of machine learning. You built a model with some data (training set) and then you can use this model for prediction for new data (testing set).

Upvotes: 0

Triss
Triss

Reputation: 581

First to have a reproducable example:

y<-rnorm(20)
x<-matrix(rnorm(40),20,2)
model2<-lm(y~poly(x,2))
predict.lm(model2,as.data.frame(x))

of course you can save the coefficients from model2 in another variable and change them and so on. predict.lm predicts value based on your linear model. So the input of predict.lm has to be a model and data and not just coefficients. If you want to change the coefficients in model2 you can do this with model2$coefficients[]<-.... Here you can change all the coefficients of the model and do the same command as above with predict.lm

Upvotes: 1

Related Questions