Linear Regression Quickstart#
Already know what's what with linear regression, just need to know how to tackle it in Python? We're here for you! If not, continue on to the next section.
We're going to ignore the nuance of what we're doing in this notebook, it's really just for people who need to see the process.
Pandas for our data#
As is typical, we'll be using pandas dataframes for the data.
import pandas as pd
df = pd.DataFrame([
{ 'sold': 0, 'revenue': 0 },
{ 'sold': 4, 'revenue': 8 },
{ 'sold': 16, 'revenue': 32 },
])
df
Performing a regression#
The statsmodels package is your best friend when it comes to regression. In theory you can do it using other techniques or libraries, but statsmodels is just so simple.
For the regression below, I'm using the formula method of describing the regression. If that makes you grumpy, check the regression reference page for more details.
import statsmodels.formula.api as smf
model = smf.ols("revenue ~ sold", data=df)
results = model.fit()
results.summary()
For each unit sold, we get 2 revenue. That's about it.
Multivariable regression#
Multivariable regression is easy-peasy. Let's add a couple more columns to our dataset, adding tips to the equation.
import pandas as pd
df = pd.DataFrame([
{ 'sold': 0, 'revenue': 0, 'tips': 0, 'charge_amount': 0 },
{ 'sold': 4, 'revenue': 8, 'tips': 1, 'charge_amount': 9 },
{ 'sold': 16, 'revenue': 32, 'tips': 2, 'charge_amount': 34 },
])
df
import statsmodels.formula.api as smf
model = smf.ols("charge_amount ~ sold + tips", data=df)
results = model.fit()
results.summary()
There you go!
If you'd like more details, you can continue on in this section. If you'd just like the how-to-do-an-exact-thing explanations, check out the regression reference page.