Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 804
Matt Alcock Avatar asked Apr 14 '26 16:04

Matt Alcock


1 Answers

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])
like image 200
chepyle Avatar answered Apr 17 '26 05:04

chepyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!