Linear Regression in Python: scikit-learn vs statsmodels

Fit a linear regression in Python with scikit-learn and statsmodels, read the coefficients and confidence intervals, handle categories and curves, and plot the results.

To fit a linear regression in Python, use LinearRegression().fit(X, y) from scikit-learn when you want predictions, or smf.ols("y ~ x", data=df).fit() from statsmodels when you want standard errors, p-values, and confidence intervals. Both solve the same least squares problem and return the same coefficients.

Quick Example

This example makes up rents for 400 apartments, then fits a line of rent against floor area with both libraries.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from sklearn.linear_model import LinearRegression

rng = np.random.default_rng(12)
n = 400
sqft = rng.uniform(350, 1500, n).round()
distance_km = rng.gamma(2.0, 2.5, n).round(1)
building = rng.choice(["walk-up", "mid-rise", "tower"], n, p=[0.4, 0.35, 0.25])
premium = pd.Series(building).map({"walk-up": 0, "mid-rise": 140, "tower": 390})
rent = 900 + 1.6 * sqft - 55 * distance_km + premium + rng.normal(0, 180, n)
apartments = pd.DataFrame({
    "rent": rent.round(), "sqft": sqft,
    "distance_km": distance_km, "building": building,
})

# scikit-learn: X is a 2D table, y is a column
sk_model = LinearRegression().fit(apartments[["sqft"]], apartments["rent"])
print("scikit-learn:", sk_model.intercept_.round(2), sk_model.coef_.round(4))

# statsmodels: describe the model with a formula
ols = smf.ols("rent ~ sqft", data=apartments).fit()
print("statsmodels: ", ols.params.round(4).to_dict())
print("R-squared:", round(ols.rsquared, 3))

grid = pd.DataFrame({"sqft": np.linspace(350, 1500, 100)})
band = ols.get_prediction(grid).summary_frame(alpha=0.05)

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
ax.scatter(apartments.sqft, apartments.rent, s=18, color="#64748b", alpha=0.6,
           label="Apartments")
ax.plot(grid.sqft, band["mean"], color="#b91c1c", lw=2.5, label="Fitted line")
ax.fill_between(grid.sqft, band.obs_ci_lower, band.obs_ci_upper,
                color="#b91c1c", alpha=0.1, label="95% prediction interval")
ax.fill_between(grid.sqft, band.mean_ci_lower, band.mean_ci_upper,
                color="#b91c1c", alpha=0.35, label="95% confidence interval")
ax.set(title="Monthly rent by floor area", xlabel="Floor area (sq ft)",
       ylabel="Rent ($)")
ax.legend(loc="upper left")
plt.show()

Scatter plot of monthly rent against floor area with a rising fitted line, a narrow 95% confidence band and a much wider 95% prediction band

Each extra square foot adds about $1.60 of monthly rent (95% confidence interval $1.51 to $1.70), and floor area alone explains 73% of the variation. The two bands answer different questions. The confidence interval is where the average rent at that size probably lies, about ±$65 at 350 sq ft. The prediction interval is where a single new apartment is likely to fall, about ±$670.

scikit-learn vs statsmodels: Which Should I Use?

Task scikit-learn statsmodels
Fit the model LinearRegression().fit(X, y) smf.ols(formula, data).fit()
Coefficients coef_, intercept_ params
Standard errors, p-values Not provided summary(), bse, pvalues
Confidence intervals Not provided conf_int(), get_prediction()
Intercept Added by default Added by formulas; use sm.add_constant with sm.OLS
Text categories Encode them first, for example with OneHotEncoder Handled by the formula
Cross-validation and pipelines Built in Not built in

Use statsmodels to explain a relationship: how much rent changes per square foot, and how certain that number is. Use scikit-learn to predict new rows and to compare linear regression with other models using the same code.

Fit Multiple Linear Regression with statsmodels

Add terms to the formula with +. A text column such as building is converted to indicator columns automatically, with one level held out as the reference.

full = smf.ols(
    "rent ~ sqft + distance_km + C(building, Treatment('walk-up'))",
    data=apartments,
).fit()
print(full.summary())

The parts of the summary to read first:

  • coef is the change in rent for a one-unit change in that column, with the other columns held fixed.
  • std err, P>|t|, and [0.025, 0.975] describe the uncertainty in each coefficient.
  • R-squared is the share of the variation in rent that the model accounts for.

Adding distance and building type raises R-squared from 0.73 to 0.92. A tower rents for about $386 more than a walk-up of the same size and distance, and each kilometer from the center takes off about $59. The note about a large condition number comes from the columns' scales here, with square feet in the hundreds next to 0/1 indicators. After standardizing the columns it drops to about 1.6, so correlated features are not the cause.

Plot Regression Coefficients with Confidence Intervals

conf_int() returns the interval for each coefficient. Plot the slopes on separate panels when their units differ, because a per-square-foot effect and a building premium don't belong on one axis.

coefs = pd.DataFrame({"estimate": full.params, "low": full.conf_int()[0],
                      "high": full.conf_int()[1]}).drop("Intercept")
coefs.index = ["Mid-rise vs walk-up", "Tower vs walk-up",
               "Per sq ft", "Per km from center"]
print(coefs.round(2))

panels = [("Building type", ["Mid-rise vs walk-up", "Tower vs walk-up"]),
          ("Floor area", ["Per sq ft"]),
          ("Distance", ["Per km from center"])]

fig, axes = plt.subplots(3, 1, figsize=(8, 5), layout="constrained",
                         height_ratios=[2, 1, 1])
for ax, (title, rows) in zip(axes, panels):
    part = coefs.loc[rows]
    errors = [part.estimate - part.low, part.high - part.estimate]
    ax.errorbar(part.estimate, rows, xerr=errors, fmt="o", color="#1d4ed8",
                capsize=4, lw=2)
    ax.axvline(0, color="#334155", ls="--", lw=1)
    ax.set_title(title, loc="left", fontsize=11)
    ax.margins(x=0.15, y=0.4)
    ax.invert_yaxis()
fig.suptitle("Change in monthly rent ($), with 95% confidence intervals")
plt.show()

Coefficient plot with 95% confidence intervals: about 123 dollars for mid-rise and 386 dollars for tower buildings, 1.57 dollars per square foot and minus 59 dollars per kilometer

An interval that crosses zero means the data is consistent with no effect at the 95% level. None of these do.

Predict with scikit-learn and Check a Test Set

scikit-learn needs numbers, so encode building inside a pipeline. ColumnTransformer one-hot encodes that column and passes the others through. drop names the reference level, so each coefficient means the same thing as in the statsmodels formula.

from sklearn.compose import ColumnTransformer
from sklearn.metrics import PredictionErrorDisplay, r2_score, root_mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder

features = ["sqft", "distance_km", "building"]
X_train, X_test, y_train, y_test = train_test_split(
    apartments[features], apartments["rent"], test_size=0.25, random_state=12)

encode = ColumnTransformer(
    [("building", OneHotEncoder(drop=["walk-up"]), ["building"])],
    remainder="passthrough")
pipeline = make_pipeline(encode, LinearRegression()).fit(X_train, y_train)
predicted = pipeline.predict(X_test)

print("test R-squared:", round(r2_score(y_test, predicted), 3))
print("test RMSE:", round(root_mean_squared_error(y_test, predicted), 1))

new = pd.DataFrame({"sqft": [800], "distance_km": [3.0], "building": ["tower"]})
print("predicted rent:", pipeline.predict(new).round())

fig, ax = plt.subplots(figsize=(6, 6), layout="constrained")
PredictionErrorDisplay.from_predictions(
    y_test, predicted, kind="actual_vs_predicted", ax=ax,
    scatter_kwargs={"color": "#047857", "alpha": 0.7})
ax.set_title("Predicted vs actual rent (test set)")
plt.show()

Predicted versus actual rent for the test set, with points scattered closely around the diagonal

On the 100 test apartments, R-squared is 0.91 and the typical error (RMSE) is about $193. An 800 sq ft tower apartment 3 km out is predicted at $2,438 a month. The coefficients differ slightly from the statsmodels table because the pipeline was fit on 300 rows instead of 400.

For a fuller look at splitting data, see how to draw learning and validation curves.

Model a Curved Relationship

A linear model is linear in its coefficients, so it can still fit a curve. Add a transformed column to the formula, such as I(x ** 2) or np.log(x). This example makes up heating use that falls as outdoor temperature rises, then levels off.

temp = rng.uniform(-10, 22, 150)
kwh = 14 + 0.09 * (22 - temp) ** 2 + rng.normal(0, 5, 150)
heating = pd.DataFrame({"temp": temp, "kwh": kwh})

line = smf.ols("kwh ~ temp", data=heating).fit()
curve = smf.ols("kwh ~ temp + I(temp ** 2)", data=heating).fit()

grid = pd.DataFrame({"temp": np.linspace(-10, 22, 100)})
fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
ax.scatter(heating.temp, heating.kwh, s=18, color="#64748b", alpha=0.7)
for result, label, color in [(line, "Straight line", "#c2410c"),
                             (curve, "With temp²", "#6d28d9")]:
    ax.plot(grid.temp, result.predict(grid), color=color, lw=2.5,
            label=f"{label} (R² = {result.rsquared:.3f})")
ax.set(title="Daily heating use by outdoor temperature",
       xlabel="Outdoor temperature (°C)", ylabel="Energy (kWh)")
ax.legend()
plt.show()

Heating energy against outdoor temperature, where a straight line misses the curve and a model with a squared temperature term follows it

The straight line already has an R-squared of 0.925, yet it predicts negative energy use on the warmest days and runs too low at both ends. The squared term fixes the shape and reaches 0.976. I() tells the formula to treat ** as arithmetic. In scikit-learn, add PolynomialFeatures(degree=2, include_bias=False) to the pipeline.

Check the Assumptions

A high R-squared doesn't show that a line is the right shape. Before trusting the intervals and p-values:

  • Draw a residual plot. A curve in the residuals means a term is missing.
  • If the residuals fan out, use robust standard errors with smf.ols(...).fit(cov_type="HC3"), or model the log of the target.
  • Check residual normality with a Q-Q plot when the sample is small and you need prediction intervals.
  • Rows should be independent. Repeated measurements of the same unit need clustered standard errors or a different model.

Practical Tips

  • sm.OLS(y, X) does not add an intercept. Pass sm.add_constant(X), or use the formula interface.
  • Don't rank features by raw coefficient size. The size depends on the units: rent per square foot and rent per kilometer are not comparable.
  • Strongly correlated columns make individual coefficients unstable. Check a correlation heatmap before interpreting them.
  • For a quick fitted line on a chart without a model object, Seaborn's regplot draws one in a single call.

Similar Topics