Matt Alcock
Matt Alcock

Reputation: 12901

What is the Python equivalent to R predict function for linear models?

What is the Python equivalent to R predict function for linear models?

I'm sure there is something in scipy that can help here but is there an equivalent function?

https://stat.ethz.ch/R-manual/R-patched/library/stats/html/predict.lm.html

Upvotes: 3

Views: 11311

Answers (1)

chepyle
chepyle

Reputation: 996

Scipy has plenty of regression tools with predict methods; though IMO, Pandas is the python library that comes closest to replicating R's functionality, complete with predict methods. The following snippets in R and python demonstrate the similarities.

R linear regression:

data(trees)
linmodel <- lm(Volume~., data = trees[1:20,])
linpred <- predict(linmodel, trees[21:31,])
plot(linpred, trees$Volume[21:31])

Same data set in python using pandas ols:

import pandas as pd
from pandas.stats.api import ols
import matplotlib.pyplot as plt

trees = pd.read_csv('trees.csv')
linmodel = ols(y = trees['Volume'][0:20], x = trees[['Girth', 'Height']][0:20])
linpred = linmodel.predict(x = trees[['Girth', 'Height']][20:31])
plt.scatter(linpred,trees['Volume'][20:31])

Upvotes: 5

Related Questions