Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to Machine Learning Notes
Topic #204

Matplotlib for Machine Learning

Matplotlib is Python's foundational plotting library. In ML, you'll reach for it constantly — not for polished dashboards, but for fast diagnostic plots that reveal whether your data and model are behaving as expected.

The Plots You'll Actually Use

import matplotlib.pyplot as plt
import numpy as np

# 1. Distribution of a feature — spot skew and outliers
plt.hist(df["income"], bins=30)
plt.xlabel("Income"); plt.ylabel("Count"); plt.title("Income Distribution")
plt.show()

# 2. Relationship between two features — spot correlation, non-linearity
plt.scatter(df["sqft"], df["price"], alpha=0.5)
plt.xlabel("Square Feet"); plt.ylabel("Price"); plt.show()

# 3. Predicted vs actual — the single most useful regression diagnostic plot
plt.scatter(y_test, predictions, alpha=0.5)
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--')  # perfect-prediction line
plt.xlabel("Actual"); plt.ylabel("Predicted"); plt.show()

In the predicted-vs-actual plot, points falling on the red dashed line are perfect predictions; the tighter the scatter hugs that line, the better the model. Systematic curvature away from the line is a strong sign the model is missing a non-linear pattern.

Plotting a Model's Training Curve

train_losses = [0.9, 0.6, 0.4, 0.3, 0.25, 0.22, 0.21]
val_losses   = [0.95, 0.65, 0.5, 0.42, 0.40, 0.41, 0.44]   # starts rising -> overfitting

plt.plot(train_losses, label="Train Loss")
plt.plot(val_losses, label="Validation Loss")
plt.xlabel("Epoch"); plt.ylabel("Loss"); plt.legend(); plt.show()

This exact plot shape — validation loss rising while training loss keeps falling — is the visual signature of overfitting.

Practical Use Cases

  • Feature distribution checks before modeling (skew, outliers)
  • Predicted-vs-actual and residual plots to diagnose regression models
  • Training/validation loss curves to catch overfitting early
  • Confusion matrix heatmaps (often combined with Seaborn)

Common Mistakes

  • Skipping visualization entirely and relying only on summary statistics — a dataset can have identical mean/variance to a very different-looking one (see Distribution Analysis); always plot before trusting a summary number.
  • Forgetting axis labels and titles on diagnostic plots — makes them useless when revisited later or shared with teammates.

Interview Relevance

Q: "How would you visually check if a regression model is a good fit?" A predicted-vs-actual scatter plot with a diagonal reference line — tight clustering along the diagonal indicates a good fit; a curved or fan-shaped pattern indicates the model is systematically wrong in some regions.

Practice Question

You train a regression model and plot predicted vs actual values. The points form a clear U-shape around the diagonal reference line instead of hugging it. What does this suggest about the model?

Related ML Notes

Want to go beyond the notes?

Join CodingNow's Machine Learning course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →