File size: 6,899 Bytes
cfb5e7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
"""Visualization utilities for Myanmar Ghost project."""

from pathlib import Path
from typing import Any, Dict, List, Optional

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns


def plot_training_curves(
    history: Dict[str, List[float]],
    metrics: List[str] = None,
    title: str = "Training Curves",
    output_path: Optional[str] = None,
    figsize: tuple = (12, 8),
) -> plt.Figure:
    """Plot training curves for multiple metrics.
    
    Args:
        history: Dictionary mapping metric names to lists of values
        metrics: List of metrics to plot (default: all)
        title: Plot title
        output_path: Path to save figure
        figsize: Figure size
    
    Returns:
        Matplotlib figure
    """
    if metrics is None:
        metrics = list(history.keys())
    
    n_metrics = len(metrics)
    n_cols = min(2, n_metrics)
    n_rows = (n_metrics + n_cols - 1) // n_cols
    
    fig, axes = plt.subplots(n_rows, n_cols, figsize=figsize)
    fig.suptitle(title, fontsize=16)
    
    if n_metrics == 1:
        axes = [axes]
    else:
        axes = axes.flatten() if hasattr(axes, 'flatten') else axes
    
    for i, metric in enumerate(metrics):
        ax = axes[i] if i < len(axes) else axes[0]
        
        if metric in history:
            values = history[metric]
            steps = list(range(len(values)))
            
            ax.plot(steps, values, marker='o', markersize=3)
            ax.set_xlabel('Step/Epoch')
            ax.set_ylabel(metric.capitalize())
            ax.set_title(metric.capitalize())
            ax.grid(True, alpha=0.3)
    
    # Hide unused subplots
    for i in range(n_metrics, len(axes)):
        axes[i].set_visible(False)
    
    plt.tight_layout()
    
    if output_path:
        Path(output_path).parent.mkdir(parents=True, exist_ok=True)
        plt.savefig(output_path, dpi=150, bbox_inches='tight')
    
    return fig


def plot_confusion_matrix(
    cm: np.ndarray,
    class_names: List[str],
    title: str = "Confusion Matrix",
    output_path: Optional[str] = None,
    figsize: tuple = (10, 8),
    normalize: bool = False,
) -> plt.Figure:
    """Plot confusion matrix.
    
    Args:
        cm: Confusion matrix
        class_names: Names of classes
        title: Plot title
        output_path: Path to save figure
        figsize: Figure size
        normalize: Whether to normalize
    
    Returns:
        Matplotlib figure
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    
    fig, ax = plt.subplots(figsize=figsize)
    
    sns.heatmap(
        cm,
        annot=True,
        fmt='.2f' if normalize else 'd',
        cmap='Blues',
        xticklabels=class_names,
        yticklabels=class_names,
        ax=ax,
    )
    
    ax.set_xlabel('Predicted')
    ax.set_ylabel('True')
    ax.set_title(title)
    
    plt.tight_layout()
    
    if output_path:
        Path(output_path).parent.mkdir(parents=True, exist_ok=True)
        plt.savefig(output_path, dpi=150, bbox_inches='tight')
    
    return fig


def plot_label_distribution(
    labels: List[Any],
    class_names: Optional[List[str]] = None,
    title: str = "Label Distribution",
    output_path: Optional[str] = None,
    figsize: tuple = (10, 6),
) -> plt.Figure:
    """Plot distribution of labels.
    
    Args:
        labels: List of labels
        class_names: Names of classes
        title: Plot title
        output_path: Path to save figure
        figsize: Figure size
    
    Returns:
        Matplotlib figure
    """
    from collections import Counter
    
    counts = Counter(labels)
    
    if class_names:
        labels_order = class_names
        values = [counts.get(l, 0) for l in labels_order]
    else:
        labels_order = list(counts.keys())
        values = list(counts.values())
    
    fig, ax = plt.subplots(figsize=figsize)
    
    bars = ax.bar(labels_order, values, color='steelblue', alpha=0.7)
    
    # Add count labels on bars
    for bar, count in zip(bars, values):
        height = bar.get_height()
        ax.text(
            bar.get_x() + bar.get_width() / 2.,
            height,
            f'{int(count)}',
            ha='center',
            va='bottom',
        )
    
    ax.set_xlabel('Class')
    ax.set_ylabel('Count')
    ax.set_title(title)
    ax.grid(True, alpha=0.3, axis='y')
    
    plt.tight_layout()
    
    if output_path:
        Path(output_path).parent.mkdir(parents=True, exist_ok=True)
        plt.savefig(output_path, dpi=150, bbox_inches='tight')
    
    return fig


def plot_attention_weights(
    attention_weights: np.ndarray,
    tokens: List[str],
    title: str = "Attention Weights",
    output_path: Optional[str] = None,
    figsize: tuple = (12, 10),
) -> plt.Figure:
    """Plot attention weights heatmap.
    
    Args:
        attention_weights: Attention weight matrix
        tokens: List of tokens
        title: Plot title
        output_path: Path to save figure
        figsize: Figure size
    
    Returns:
        Matplotlib figure
    """
    fig, ax = plt.subplots(figsize=figsize)
    
    sns.heatmap(
        attention_weights,
        xticklabels=tokens,
        yticklabels=tokens,
        cmap='viridis',
        ax=ax,
        cbar_kw={'label': 'Attention Weight'},
    )
    
    ax.set_xlabel('Key Tokens')
    ax.set_ylabel('Query Tokens')
    ax.set_title(title)
    
    plt.tight_layout()
    
    if output_path:
        Path(output_path).parent.mkdir(parents=True, exist_ok=True)
        plt.savefig(output_path, dpi=150, bbox_inches='tight')
    
    return fig


def plot_loss_landscape(
    losses: np.ndarray,
    xlabel: str = "x",
    ylabel: str = "y",
    title: str = "Loss Landscape",
    output_path: Optional[str] = None,
    figsize: tuple = (10, 6),
) -> plt.Figure:
    """Plot loss landscape.
    
    Args:
        losses: 2D array of loss values
        xlabel: Label for x-axis
        ylabel: Label for y-axis
        title: Plot title
        output_path: Path to save figure
        figsize: Figure size
    
    Returns:
        Matplotlib figure
    """
    fig, ax = plt.subplots(figsize=figsize)
    
    if losses.ndim == 1:
        ax.plot(losses)
    else:
        sns.heatmap(losses, ax=ax, cmap='viridis')
    
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_title(title)
    
    plt.tight_layout()
    
    if output_path:
        Path(output_path).parent.mkdir(parents=True, exist_ok=True)
        plt.savefig(output_path, dpi=150, bbox_inches='tight')
    
    return fig


if __name__ == "__main__":
    print("Visualization utilities loaded")
    print("Available functions:")
    print("  - plot_training_curves")
    print("  - plot_confusion_matrix")
    print("  - plot_label_distribution")
    print("  - plot_attention_weights")
    print("  - plot_loss_landscape")