File size: 5,457 Bytes
27411b0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
import numpy as np
import pandas as pd
from plotly import graph_objects as go
import plotly.express as px
from viewer.utils import PlotOptions
def parse_merge_runs_to_plot(df, metric_name, merge_method):
if merge_method == "none":
return [
(group["steps"], group[metric_name], f'{runname}-s{seed}')
for (runname, seed), group in df.groupby(["runname", "seed"])
]
if metric_name not in df.columns:
return []
grouped = df.groupby(['runname', 'steps']).agg({metric_name: merge_method}).reset_index()
return [
(group["steps"], group[metric_name], runname)
for (runname,), group in grouped.groupby(["runname"])
]
def prepare_plot_data(df: pd.DataFrame, metric_name: str, seed_merge_method: str,
plot_options: PlotOptions) -> pd.DataFrame:
if df is None or "steps" not in df or metric_name not in df.columns:
return pd.DataFrame()
df = df.copy().sort_values(by=["steps"])
plot_data = parse_merge_runs_to_plot(df, metric_name, seed_merge_method)
# Create DataFrame with all possible steps as index
all_steps = sorted(set(step for xs, _, _ in plot_data for step in xs))
result_df = pd.DataFrame(index=all_steps)
# Populate the DataFrame respecting xs for each series
for xs, ys, runname in plot_data:
result_df[runname] = pd.Series(index=xs.values, data=ys.values)
# Interpolate or keep NaN based on the interpolate flag
if plot_options.interpolate:
# this is done per run, as each run is in a diff column
result_df = result_df.interpolate(method='linear')
# Apply smoothing if needed
if plot_options.smoothing > 0:
result_df = result_df.rolling(window=plot_options.smoothing, min_periods=1).mean()
if plot_options.pct:
result_df = result_df * 100
return result_df
def plot_metric(plot_df: pd.DataFrame, metric_name: str, seed_merge_method: str, pct: bool, statistics: dict,
nb_stds: int, language: str = None, barplot: bool = False) -> go.Figure:
if barplot:
return plot_metric_barplot(plot_df, metric_name, seed_merge_method, pct, statistics, nb_stds, language)
return plot_metric_scatter(plot_df, metric_name, seed_merge_method, pct, statistics, nb_stds, language)
def plot_metric_scatter(plot_df: pd.DataFrame, metric_name: str, seed_merge_method: str, pct: bool, statistics: dict,
nb_stds: int, language: str = None) -> go.Figure:
fig = go.Figure()
if not isinstance(plot_df, pd.DataFrame) or plot_df.empty:
return fig
show_error_bars = nb_stds > 0 and not np.isnan(statistics["mean_std"])
error_value = statistics["mean_std"] * nb_stds * (100 if pct else 1) if show_error_bars else 0.0
last_y_values = {runname: plot_df[runname].iloc[-1] for runname in plot_df.columns}
sorted_runnames = sorted(last_y_values, key=last_y_values.get, reverse=True)
for runname in sorted_runnames:
fig.add_trace(
go.Scatter(x=plot_df.index, y=plot_df[runname], mode='lines+markers', name=runname,
hovertemplate=f'%{{y:.2f}} ({runname})<extra></extra>',
error_y=dict(
type='constant', # Use a constant error value
value=error_value, # Single error value
visible=show_error_bars # Show error bars
))
)
lang_string = f" ({language})" if language else ""
fig.update_layout(
title=f"Run comparisons{lang_string}: {metric_name}" +
(f" ({seed_merge_method} over seeds)" if seed_merge_method != "none" else "") + (f" [%]" if pct else ""),
xaxis_title="Training steps",
yaxis_title=metric_name,
hovermode="x unified"
)
return fig
def plot_metric_barplot(plot_df: pd.DataFrame, metric_name: str, seed_merge_method: str, pct: bool, statistics: dict,
nb_stds: int, language: str = None) -> go.Figure:
fig = go.Figure()
if not isinstance(plot_df, pd.DataFrame) or plot_df.empty:
return fig
show_error_bars = nb_stds > 0 and not np.isnan(statistics["mean_std"])
error_value = statistics["mean_std"] * nb_stds * (100 if pct else 1) if show_error_bars else 0.0
last_values = {runname: plot_df[runname].iloc[-1] for runname in plot_df.columns}
sorted_runnames = sorted(last_values, key=last_values.get, reverse=True)
# Create color map for consistent colors
colors = px.colors.qualitative.Set1
color_map = {run: colors[i % len(colors)] for i, run in enumerate(plot_df.columns)}
fig.add_trace(
go.Bar(
x=sorted_runnames,
y=[last_values[run] for run in sorted_runnames],
marker_color=[color_map[run] for run in sorted_runnames],
error_y=dict(
type='constant',
value=error_value,
visible=show_error_bars
),
hovertemplate='%{y:.2f}<extra></extra>'
)
)
lang_string = f" ({language})" if language else ""
fig.update_layout(
title=f"Run comparisons{lang_string}: {metric_name}" +
(f" ({seed_merge_method} over seeds)" if seed_merge_method != "none" else "") + (
f" [%]" if pct else ""),
xaxis_title="Runs",
yaxis_title=metric_name,
hovermode="x"
)
return fig |