Python / Data Science Essentials Interview Questions
How do you visualise regression results and residuals using Seaborn and Matplotlib?
After fitting any regression model, visualising the residuals (actual - predicted values) is mandatory. Patterns in residuals reveal model assumptions violations: non-linearity, heteroscedasticity, or non-normality of errors.
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# Simulate some data with a non-linear relationship
rng = np.random.default_rng(42)
x = rng.uniform(0, 10, 200)
y = 2 * x + 0.5 * x**2 + rng.normal(0, 3, 200)
df = pd.DataFrame({'x': x, 'y': y})
# 1. Scatter + regression line (with confidence interval)
sns.regplot(data=df, x='x', y='y', ci=95, scatter_kws={'alpha': 0.4})
plt.title('Scatter with OLS Regression Line')
plt.show()
# 2. Residual plot — built in seaborn
sns.residplot(data=df, x='x', y='y', lowess=True,
scatter_kws={'alpha': 0.4})
plt.axhline(0, color='red', linestyle='--')
plt.title('Residuals vs x (lowess smoothed trend)')
plt.show()
# A horizontal band around 0 = good; a curve = model is missing non-linearity
# 3. Manual residuals (after sklearn model)
from sklearn.linear_model import LinearRegression
model = LinearRegression().fit(df[['x']], df['y'])
df['predicted'] = model.predict(df[['x']])
df['residual'] = df['y'] - df['predicted']
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
axes[0].scatter(df['predicted'], df['residual'], alpha=0.4)
axes[0].axhline(0, color='red', linestyle='--')
axes[0].set(xlabel='Fitted Values', ylabel='Residuals',
title='Residuals vs Fitted')
sns.histplot(df['residual'], kde=True, ax=axes[1])
axes[1].set_title('Residual Distribution')
plt.tight_layout(); plt.show()The two most diagnostic residual plots are: (1) Residuals vs Fitted — should be a random horizontal band; any curve indicates missing predictors or a need for feature transformation. (2) Residual histogram — should be approximately normal; heavy tails suggest outliers or a non-Gaussian error structure.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
