|
| 1 | +"""Training report generation for classifier cross-validation results.""" |
| 2 | + |
| 3 | +from dataclasses import dataclass, field |
| 4 | +from datetime import datetime |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +from tabulate import tabulate |
| 9 | + |
| 10 | + |
| 11 | +@dataclass |
| 12 | +class CrossValidationResult: |
| 13 | + """Results from a single cross-validation iteration. |
| 14 | +
|
| 15 | + Attributes: |
| 16 | + iteration: The iteration number (1-indexed) |
| 17 | + test_video: Name of the video used for testing |
| 18 | + test_identity: Identity label used for testing |
| 19 | + accuracy: Classification accuracy (0.0 to 1.0) |
| 20 | + precision_behavior: Precision for behavior class |
| 21 | + precision_not_behavior: Precision for not-behavior class |
| 22 | + recall_behavior: Recall for behavior class |
| 23 | + recall_not_behavior: Recall for not-behavior class |
| 24 | + f1_behavior: F1 score for behavior class |
| 25 | + support_behavior: Number of behavior frames in test set |
| 26 | + support_not_behavior: Number of not-behavior frames in test set |
| 27 | + confusion_matrix: 2x2 confusion matrix |
| 28 | + top_features: List of (feature_name, importance) tuples for this iteration |
| 29 | + """ |
| 30 | + |
| 31 | + iteration: int |
| 32 | + test_video: str |
| 33 | + test_identity: str |
| 34 | + accuracy: float |
| 35 | + precision_behavior: float |
| 36 | + precision_not_behavior: float |
| 37 | + recall_behavior: float |
| 38 | + recall_not_behavior: float |
| 39 | + f1_behavior: float |
| 40 | + support_behavior: int |
| 41 | + support_not_behavior: int |
| 42 | + confusion_matrix: np.ndarray |
| 43 | + top_features: list[tuple[str, float]] = field(default_factory=list) |
| 44 | + |
| 45 | + |
| 46 | +@dataclass |
| 47 | +class TrainingReportData: |
| 48 | + """Complete training information for generating a report. |
| 49 | +
|
| 50 | + Attributes: |
| 51 | + behavior_name: Name of the behavior being trained |
| 52 | + classifier_type: Type/name of the classifier (e.g., "Random Forest") |
| 53 | + window_size: Window size used for feature extraction |
| 54 | + balance_training_labels: Whether training labels were balanced |
| 55 | + symmetric_behavior: Whether the behavior is symmetric |
| 56 | + distance_unit: Unit used for distance features ("cm" or "pixel") |
| 57 | + cv_results: List of CrossValidationResult objects, one per iteration |
| 58 | + final_top_features: Top features from final model (trained on all data) |
| 59 | + frames_behavior: Total number of frames labeled as behavior |
| 60 | + frames_not_behavior: Total number of frames labeled as not behavior |
| 61 | + bouts_behavior: Total number of behavior bouts labeled |
| 62 | + bouts_not_behavior: Total number of not-behavior bouts labeled |
| 63 | + training_time_ms: Total training time in milliseconds |
| 64 | + timestamp: Datetime when training was completed |
| 65 | + """ |
| 66 | + |
| 67 | + behavior_name: str |
| 68 | + classifier_type: str |
| 69 | + window_size: int |
| 70 | + balance_training_labels: bool |
| 71 | + symmetric_behavior: bool |
| 72 | + distance_unit: str |
| 73 | + cv_results: list[CrossValidationResult] |
| 74 | + final_top_features: list[tuple[str, float]] |
| 75 | + frames_behavior: int |
| 76 | + frames_not_behavior: int |
| 77 | + bouts_behavior: int |
| 78 | + bouts_not_behavior: int |
| 79 | + training_time_ms: int |
| 80 | + timestamp: datetime |
| 81 | + |
| 82 | + |
| 83 | +def _escape_markdown(text: str) -> str: |
| 84 | + """Escape markdown special characters in text. |
| 85 | +
|
| 86 | + Args: |
| 87 | + text: Text that may contain markdown special characters |
| 88 | +
|
| 89 | + Returns: |
| 90 | + Text with markdown special characters escaped |
| 91 | + """ |
| 92 | + # Escape common markdown characters that might appear in filenames |
| 93 | + # Most important: _ (underscore) which creates italics |
| 94 | + # Also escape: * (asterisk), [ ] (brackets), ( ) (parentheses) |
| 95 | + chars_to_escape = ["_", "*", "[", "]", "(", ")", "`", "#"] |
| 96 | + for char in chars_to_escape: |
| 97 | + text = text.replace(char, f"\\{char}") |
| 98 | + return text |
| 99 | + |
| 100 | + |
| 101 | +def generate_markdown_report(data: TrainingReportData) -> str: |
| 102 | + """Generate a markdown-formatted training report. |
| 103 | +
|
| 104 | + Args: |
| 105 | + data: TrainingData object containing all training information |
| 106 | +
|
| 107 | + Returns: |
| 108 | + Markdown-formatted string |
| 109 | + """ |
| 110 | + lines = [] |
| 111 | + |
| 112 | + lines.append(f"# Training Report: {data.behavior_name}") |
| 113 | + lines.append("") |
| 114 | + lines.append(f"**Date:** {data.timestamp.strftime('%B %d, %Y at %I:%M:%S %p')}") |
| 115 | + lines.append("") |
| 116 | + |
| 117 | + lines.append("## Training Summary") |
| 118 | + lines.append("") |
| 119 | + lines.append(f"- **Behavior:** {data.behavior_name}") |
| 120 | + lines.append(f"- **Classifier:** {data.classifier_type}") |
| 121 | + lines.append(f"- **Window Size:** {data.window_size}") |
| 122 | + lines.append( |
| 123 | + f"- **Balanced Training Labels:** {'Yes' if data.balance_training_labels else 'No'}" |
| 124 | + ) |
| 125 | + lines.append(f"- **Symmetric Behavior:** {'Yes' if data.symmetric_behavior else 'No'}") |
| 126 | + lines.append(f"- **Distance Unit:** {data.distance_unit}") |
| 127 | + lines.append(f"- **Training Time:** {data.training_time_ms / 1000:.2f} seconds") |
| 128 | + lines.append("") |
| 129 | + |
| 130 | + lines.append("### Label Counts") |
| 131 | + lines.append("") |
| 132 | + lines.append(f"- **Behavior frames:** {data.frames_behavior:,}") |
| 133 | + lines.append(f"- **Not-behavior frames:** {data.frames_not_behavior:,}") |
| 134 | + lines.append(f"- **Behavior bouts:** {data.bouts_behavior:,}") |
| 135 | + lines.append(f"- **Not-behavior bouts:** {data.bouts_not_behavior:,}") |
| 136 | + lines.append("") |
| 137 | + |
| 138 | + # Cross-validation results |
| 139 | + if data.cv_results: |
| 140 | + lines.append("## Cross-Validation Results") |
| 141 | + lines.append("") |
| 142 | + |
| 143 | + # Summary statistics |
| 144 | + accuracies = [r.accuracy for r in data.cv_results] |
| 145 | + f1_behavior = [r.f1_behavior for r in data.cv_results] |
| 146 | + |
| 147 | + lines.append("### Performance Summary") |
| 148 | + lines.append("") |
| 149 | + lines.append( |
| 150 | + f"- **Mean Accuracy:** {np.mean(accuracies):.4f} (± {np.std(accuracies):.4f})" |
| 151 | + ) |
| 152 | + lines.append( |
| 153 | + f"- **Mean F1 Score (Behavior):** {np.mean(f1_behavior):.4f} (± {np.std(f1_behavior):.4f})" |
| 154 | + ) |
| 155 | + lines.append("") |
| 156 | + |
| 157 | + # Detailed results table |
| 158 | + lines.append("### Iteration Details") |
| 159 | + lines.append("") |
| 160 | + |
| 161 | + table_data = [] |
| 162 | + for result in data.cv_results: |
| 163 | + # Escape markdown special characters in video |
| 164 | + escaped_video = _escape_markdown(result.test_video) |
| 165 | + |
| 166 | + table_data.append( |
| 167 | + [ |
| 168 | + result.iteration, |
| 169 | + f"{result.accuracy:.4f}", |
| 170 | + f"{result.precision_not_behavior:.4f}", |
| 171 | + f"{result.precision_behavior:.4f}", |
| 172 | + f"{result.recall_not_behavior:.4f}", |
| 173 | + f"{result.recall_behavior:.4f}", |
| 174 | + f"{result.f1_behavior:.4f}", |
| 175 | + f"{escaped_video} [{result.test_identity}]", |
| 176 | + ] |
| 177 | + ) |
| 178 | + |
| 179 | + headers = [ |
| 180 | + "Iter", |
| 181 | + "Accuracy", |
| 182 | + "Precision (Not Behavior)", |
| 183 | + "Precision (Behavior)", |
| 184 | + "Recall (Not Behavior)", |
| 185 | + "Recall (Behavior)", |
| 186 | + "F1 Score", |
| 187 | + "Test Group (Video [Identity])", |
| 188 | + ] |
| 189 | + |
| 190 | + table_markdown = tabulate(table_data, headers=headers, tablefmt="github") |
| 191 | + lines.append(table_markdown) |
| 192 | + lines.append("") |
| 193 | + else: |
| 194 | + # No cross-validation was performed |
| 195 | + lines.append("## Cross-Validation") |
| 196 | + lines.append("") |
| 197 | + lines.append("*No cross-validation was performed for this training.*") |
| 198 | + lines.append("") |
| 199 | + |
| 200 | + # Final model feature importance |
| 201 | + lines.append("## Feature Importance") |
| 202 | + lines.append("") |
| 203 | + lines.append("Top 20 features from final model (trained on all labeled data):") |
| 204 | + lines.append("") |
| 205 | + |
| 206 | + feature_table = [] |
| 207 | + for rank, (feature_name, importance) in enumerate(data.final_top_features, start=1): |
| 208 | + feature_table.append([rank, _escape_markdown(feature_name), f"{importance:.2f}"]) |
| 209 | + |
| 210 | + feature_markdown = tabulate( |
| 211 | + feature_table, headers=["Rank", "Feature Name", "Importance"], tablefmt="github" |
| 212 | + ) |
| 213 | + lines.append(feature_markdown) |
| 214 | + lines.append("") |
| 215 | + |
| 216 | + return "\n".join(lines) |
| 217 | + |
| 218 | + |
| 219 | +def save_training_report(data: TrainingReportData, output_path: Path) -> None: |
| 220 | + """Generate and save a training report as markdown. |
| 221 | +
|
| 222 | + Args: |
| 223 | + data: TrainingData object containing all training information |
| 224 | + output_path: Path where the markdown file should be saved |
| 225 | + """ |
| 226 | + markdown_content = generate_markdown_report(data) |
| 227 | + with open(output_path, "w", encoding="utf-8") as f: |
| 228 | + f.write(markdown_content) |
0 commit comments