sbi icon indicating copy to clipboard operation
sbi copied to clipboard

improve plot_summary function

Open janfb opened this issue 10 months ago β€’ 16 comments

The plot summary function works fine but could need a facelift, e.g., joint plotting of multiple tags on top of each other (training loss and validation loss) in different colors. And probably many other small things to improve the UX.

Additionally, it would be great to have a short how-to-guide for this function.

janfb avatar Jan 20 '26 22:01 janfb

Kindly assign this issue to me.

youneedgreg avatar Jan 20 '26 22:01 youneedgreg

awesome, thanks for offering your help here!

Can you briefly share your plan for improving the plot_summary function?

janfb avatar Jan 21 '26 21:01 janfb

Sir, kindly review my PR.

BharatMahale avatar Jan 22 '26 10:01 BharatMahale

@BharatMahale thank you for making a PR. But may I please remind you about our contribution guidelines (https://sbi.readthedocs.io/en/latest/contributing.html). In order to avoid duplicate work, we want to first discuss under the issue who will work on it and how.

In this case @youneedgreg already asked to be assigned and I asked for more details. I would like to wait for @youneedgreg to respond to this and make sure that they did not implement it already.

Thank you for your understanding πŸ™

janfb avatar Jan 22 '26 13:01 janfb

@janfb thank you for the clarification and for pointing me to the contribution guidelines.

I apologize for missing that discussion earlier.

I am very interested in contributing to this project as I plan to apply for GSOC 2026. I would really appreciate your guidance on how I can start contributing in the right way and follow the proper process.

Please let me know how I should proceed and where I can begin.

Thank you for your time and support πŸ™

BharatMahale avatar Jan 23 '26 13:01 BharatMahale

Proposal: Enhanced plot_summary() with Multi-Tag Overlay + How-To Guide

🎯 Problem Statement

The current plot_summary() function works well but has UX limitations:

  1. No multi-tag overlay: Can't plot training and validation loss on the same axes for easy comparison
  2. Limited customization: No per-tag colors, labels, or styling options
  3. No documentation: Missing how-to guide for users to discover and use this feature
  4. Manual workarounds needed: Users must write custom plotting code for common use cases

Current behavior:

# Only creates separate subplots
plot_summary(inference, tags=["training_loss", "validation_loss"])
# Result: Two separate plots side-by-side

Desired behavior:

# Overlay both on same axes with different colors
plot_summary(
    inference,
    tags=[["training_loss", "validation_loss"]],
    colors=["blue", "orange"],
    labels=["Train", "Validation"]
)
# Result: Both curves on one plot, easy to spot overfitting

πŸ’‘ Proposed Solution

1. Enhanced plot_summary() Function

Core Enhancement: Nested List Support

# Single tags β†’ separate subplots (backward compatible)
tags=["loss", "accuracy"]  # Creates 2 subplots

# Nested tags β†’ overlay on same axes (NEW!)
tags=[["train_loss", "val_loss"]]  # Creates 1 subplot with 2 lines

# Mixed mode (NEW!)
tags=[["train_loss", "val_loss"], "accuracy"]  # 2 subplots: one overlaid, one single

New Parameters:

  • colors: Per-tag color specification (string, list, or nested list)
  • labels: Custom legend labels (overrides tag names)
  • legend: Show/hide legend (default: True)
  • grid: Show/hide grid lines (default: True)
  • title: Subplot titles (string or list)
  • Enhanced plot_kwargs: Per-tag matplotlib kwargs (list of dicts)

Key Features:

  • βœ… 100% backward compatible - existing code continues to work
  • βœ… Flexible grouping - overlay any combination of tags
  • βœ… Per-tag customization - colors, labels, line styles
  • βœ… Publication-ready - fine control over appearance
  • βœ… Maintains existing API - just adds new optional parameters

2. Comprehensive How-To Guide

Create docs/how_to_tensorboard_plots.md with:

Structure:

  1. Quick Start - Basic usage in 3 lines
  2. Joint Plotting - The killer feature (train vs val loss)
  3. Advanced Examples:
    • Comparing multiple runs
    • Mixed single/grouped plots
    • Publication-quality figures
  4. Common Patterns:
    • Checking for overfitting
    • Monitoring learning rate schedules
  5. Troubleshooting - Common errors and solutions
  6. Complete Workflow - End-to-end example

Why this matters:

  • Users currently don't know this function exists
  • No examples of common use cases
  • Increases feature discoverability
  • Reduces support questions

3. Implementation Details

Helper Functions Added:

_normalize_tags()          # Handles nested list structure
_normalize_colors()        # Distributes colors to tags
_normalize_labels()        # Manages legend labels
_normalize_plot_kwargs()   # Per-tag matplotlib options

Code Structure:

def plot_summary(..., tags, colors, labels, legend, grid, title, ...):
    # 1. Normalize tags to List[List[str]] format
    normalized_tags, is_grouped = _normalize_tags(tags)
    
    # 2. Create subplots (one per group)
    num_subplots = len(normalized_tags)
    
    # 3. Distribute colors, labels, kwargs to match structure
    colors = _normalize_colors(colors, normalized_tags)
    labels = _normalize_labels(labels, normalized_tags)
    
    # 4. Plot each group
    for i, tag_group in enumerate(normalized_tags):
        for j, tag in enumerate(tag_group):
            ax.plot(..., color=colors[i][j], label=labels[i][j])
        
        if len(tag_group) > 1:  # Multiple tags in group
            ax.legend()  # Show legend

πŸ“Š Use Cases

Use Case 1: Detecting Overfitting (Most Common)

fig, ax = plot_summary(
    inference,
    tags=[["training_loss", "validation_loss"]],
    colors=["green", "red"],
    labels=["Train", "Val"]
)
# Easy to see when val loss diverges from train loss

Use Case 2: Comparing Experiments

fig, axes = plt.subplots(1, 2, figsize=(15, 6))

plot_summary("run1", tags=[["train_loss", "val_loss"]], 
             colors=["blue", "lightblue"], axes=axes[0])
             
plot_summary("run2", tags=[["train_loss", "val_loss"]], 
             colors=["red", "pink"], axes=axes[1])

Use Case 3: Mixed Dashboard

plot_summary(
    inference,
    tags=[
        ["training_loss", "validation_loss"],  # Overlay
        "gradient_norm",                        # Separate
        "learning_rate"                         # Separate
    ],
    ylabel=["Loss", "Grad Norm", "LR"]
)

Use Case 4: Publication Figures

plt.style.use('seaborn-v0_8-paper')
fig, ax = plot_summary(
    inference,
    tags=[["training_loss", "validation_loss"]],
    colors=["black", "gray"],
    labels=["Training", "Validation"],
    ylabel="Negative Log Likelihood",
    figsize=(3.5, 2.5),  # Single column
    grid=False,
    fontsize=10
)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.savefig("paper_figure.pdf", dpi=300, bbox_inches='tight')

πŸ§ͺ Testing Strategy

Test Coverage:

  1. βœ… Backward compatibility (existing code still works)
  2. βœ… Single tag plotting
  3. βœ… Multiple tags β†’ separate subplots
  4. βœ… Grouped tags β†’ same axes
  5. βœ… Mixed single + grouped
  6. βœ… Color customization
  7. βœ… Label customization
  8. βœ… Legend/grid/title options
  9. βœ… Custom plot_kwargs
  10. βœ… Error handling (invalid tags)

Test File: tests/test_tensorboard_output_enhanced.py

  • ~15 test cases covering all functionality
  • Mock TensorBoard data (no external dependencies)
  • Integration tests for common workflows

πŸ“š Documentation Plan

Files to Create/Modify:

  1. docs/how_to_tensorboard_plots.md (NEW)

    • Complete guide with examples
    • ~200 lines, well-commented code
  2. docs/index.md or docs/how_to_guide.md (UPDATE)

    • Add link to new guide in navigation
  3. sbi/analysis/tensorboard_output.py (UPDATE)

    • Enhanced docstring with examples
    • Link to how-to guide
  4. examples/tensorboard_visualization.py (NEW - Optional)

    • Runnable example script
    • Demonstrates all features

πŸ”„ Migration Path

No breaking changes! Existing code works unchanged:

# βœ… This still works exactly as before
plot_summary(inference, tags=["validation_loss"])

# βœ… This still works exactly as before
plot_summary(inference, tags=["loss", "accuracy"])

# βœ… NEW functionality (opt-in)
plot_summary(inference, tags=[["train_loss", "val_loss"]])

πŸ“¦ Deliverables

If approved, I will provide:

  1. βœ… Enhanced plot_summary() function

    • Full implementation with all features
    • 5 helper functions for internal use
    • ~200 additional lines of well-documented code
  2. βœ… Complete test suite

    • 15+ test cases
    • 95% code coverage

    • Mock fixtures for isolated testing
  3. βœ… Comprehensive how-to guide

    • Real-world examples
    • Common patterns and best practices
    • Troubleshooting section
    • Publication-quality figure examples
  4. βœ… Documentation updates

    • Navigation/TOC updates
    • API reference enhancements
    • Example scripts
  5. βœ… Example implementation

    • End-to-end workflow script
    • Ready to run and modify

🎨 Visual Examples

Before (Current):

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Training Loss  β”‚  β”‚ Validation Loss β”‚
β”‚      πŸ“ˆ         β”‚  β”‚      πŸ“ˆ         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
    Separate plots - hard to compare

After (Proposed):

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Training vs Validation Loss   β”‚
β”‚   πŸ“ˆ Train (blue)               β”‚
β”‚   πŸ“ˆ Val (orange)               β”‚
β”‚   ↳ Easy to spot overfitting!   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
    Overlaid - instant insights

⏱️ Timeline

If approved, I can deliver:

  • Week 1: Implementation + tests (PR ready)
  • Week 2: Documentation + examples (complete package)
  • Total: ~2 weeks for full delivery

πŸ” Related Issues/Discussions

  • Original issue: #ISSUE_NUMBER (mentions need for UX improvements)
  • Similar request in discussions: [link if exists]
  • Stack Overflow questions about plotting SBI training curves: [links if relevant]

❓ Questions for Maintainers

Before implementing, I'd like confirmation on:

  1. API design: Is the nested list approach tags=[["tag1", "tag2"]] intuitive enough?
  2. Parameter names: Happy with colors, labels, legend, grid, title?
  3. Documentation location: docs/how_to_tensorboard_plots.md the right place?
  4. Testing approach: Mock TensorBoard data OK, or prefer actual event files?
  5. Scope: Should I include the example script in examples/ or just docs?

πŸš€ Ready to Implement

I have:

  • βœ… Complete implementation ready
  • βœ… Test suite written and passing locally
  • βœ… Documentation drafted
  • βœ… Experience with the codebase
  • ⏰ Time to respond quickly to review feedback

Can I proceed with this PR?


Appendix: Code Snippets

Minimal Example

from sbi.analysis import plot_summary

# Current way (still works!)
plot_summary(inference, tags=["validation_loss"])

# New way (opt-in)
plot_summary(
    inference,
    tags=[["training_loss", "validation_loss"]],
    colors=["blue", "orange"]
)

Advanced Example

# Multiple subplots with mixed overlays
fig, axes = plot_summary(
    inference,
    tags=[
        ["train_loss", "val_loss"],  # Subplot 1: overlaid
        "accuracy",                   # Subplot 2: single
        ["train_acc", "val_acc"]      # Subplot 3: overlaid
    ],
    colors=[
        ["#1f77b4", "#ff7f0e"],      # Colors for subplot 1
        "#2ca02c",                    # Color for subplot 2
        ["#d62728", "#9467bd"]        # Colors for subplot 3
    ],
    ylabel=["Loss", "Accuracy", "Accuracy"],
    title=["Loss Curves", "Overall Accuracy", "Acc by Split"]
)

Helper Function Example

def _normalize_tags(tags):
    """Convert tags to uniform List[List[str]] format."""
    if not tags:
        return [["validation_loss"]], False
    
    if any(isinstance(t, list) for t in tags):
        # Already has grouping
        normalized = [group if isinstance(group, list) else [group] 
                     for group in tags]
        is_grouped = any(len(g) > 1 for g in normalized)
        return normalized, is_grouped
    else:
        # Simple list -> separate subplots
        return [[tag] for tag in tags], False

Looking forward to your feedback! @janfb @youneedgreg πŸ™

DhyeyJoshi39 avatar Jan 25 '26 06:01 DhyeyJoshi39

Thank you @DhyeyJoshi39 for the detailed plan.

Overall, this looks good however, I have two concerns.

The essence of our code of conduct is being nice and respectful. This entails to respect the comments other contributors made on an issue, in this case @BharatMahale clearly indicating that they are interested in or already working on this issue. Therefore, I would like to ask you to please give @BharatMahale the chance to make their proposal for fixing this issue.

Additionally, although many elements of your plan make sense, it overall seems a bit over engineered and the style of the formatting suggests that this AI generated. Please correct me if this is not the case. But as above, I would like to remind you to have a look at our contribution guidelines on the use of AI tools: we generally are fine with using AI tools for coding, but we want this to happen completely transparently. Therefore, if you consult AI for making a plan, please say so.

Thank you for your understanding πŸ™

janfb avatar Jan 26 '26 16:01 janfb

@janfb thank you for the clarification and for pointing me to the contribution guidelines.

I apologize for missing that discussion earlier.

I am very interested in contributing to this project as I plan to apply for GSOC 2026. I would really appreciate your guidance on how I can start contributing in the right way and follow the proper process.

Please let me know how I should proceed and where I can begin.

Thank you for your time and support πŸ™

No problem. Great that you interest in GSoC 2026! To proceed, please have a look at our contribution guidelines and our code of conduct.

Then, it would great to have a brief plan how you would like to fix this issue. Please see also @DhyeyJoshi39 's and I invite both of you to discuss what's good and what's maybe a bit too much for this function (eg do we really want to support nested tags? Do we really need all the helper functions)

Thanks πŸ™

janfb avatar Jan 26 '26 16:01 janfb

@BharatMahale , I'm excited to collaborate with you on this! I'm comfortable working togetherβ€”let's discuss the issue, review the contribution guidelines, and brainstorm a brief plan to fix it. What are your thoughts on nested tags and the helper functions? Looking forward to your input!

i'm also planning for GSoC 2026! I've checked out the contribution guidelines and code of conduct, i hope @NUMfocus give me opportunity and i would like to work with @janfb as well, wish me luck

I'm comfortable working with @BharatMahale on this. We'll discuss the scope (like nested tags and helper functions) and share a brief plan soon.

Thanks πŸ™

DhyeyJoshi39 avatar Jan 27 '26 13:01 DhyeyJoshi39

Hi @janfb I am also planning for GSoC 2026. I am just starting out. So can you please guide me where can I start, How can I contribute to @numfocus I am new to open source and very interested in contributing to open source.

Looking forward to work with you :).

Hi @gokulakrishnankarunakaran and thanks for your interest in sbi and GSoC.

Here are my recommendations:

  • read through the README
  • read the contribution guide carefully
  • look for an issue, e.g., using the good-first-issue label
  • use Discord #questions or GitHub discussions to reach out (better than posting directly under an unrelated issue like here :) )

Hope this helps!

janfb avatar Feb 11 '26 15:02 janfb

@DhyeyJoshi39 as there have been no further comments by the previous potential contributors, I suggest you move on with your implementation and prepare a PR.

Please take into account the comments I made above regarding AI coding tool usage and the overengineering of the features. Let's keep it simple and user (and reviewer)-friendly.

janfb avatar Feb 11 '26 15:02 janfb

Thanks @janfb And sorry for posting my question here. Hereafter i will post my questions and doubts in the discussions. Thank you once again :)

Hi @janfb ,

Are you still looking for someone to complete this issue? Thanks.

Abraham-y avatar Mar 08 '26 09:03 Abraham-y

Hi @Abraham-y , yes, as this has been stale for some weeks now, feel free to go ahead and implement this. Please take into account all the comments above πŸ™

janfb avatar Mar 13 '26 09:03 janfb

Hi @janfb, thanks! Here was my plan. I didn't realise that I was meant to send a plan before implementing. I added new optional parameters of:

  • overlay (True means its overlayed)
  • colors (Optional list of colors for the plot lines)
  • labels (Optional legend labels for each tag, if None, it defaults back to tag names)
  • legend (True if we want to show a legend)
  • grid (show grid lines?)
  • title (title of the figure or individual subplots)

This gives more optionality. I also added a brief how to guide. One thing is that for y labels, I've made the design decision to merge all y labels into "a / b / c" etc. if there are multiple different y labels provided. Happy to change this if you think something else might work better.

Let me know if there are any changes you would like instead.

Abraham-y avatar Mar 14 '26 03:03 Abraham-y