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.
More Related questions...