TroglodyteDerivations commited on
Commit
e953abb
Β·
verified Β·
1 Parent(s): 965c7aa

Upload 2 files

Browse files
Generate Error Analysis Visualizations/updated_enhanced_error_analysis.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # enhanced_error_analysis.py
2
+ import json
3
+ import plotly.graph_objects as go
4
+ from plotly.subplots import make_subplots
5
+ import pandas as pd
6
+ from typing import List, Dict, Any
7
+
8
+ # Error categories with detailed descriptions
9
+ ERROR_CATEGORIES = {
10
+ "multi_step": "Chain-of-thought reasoning failures in multi-step problems",
11
+ "percentage": "Percentage and ratio calculations",
12
+ "logic": "Logical reasoning and problem setup failures",
13
+ "unit_conversion": "Measurement and unit conversion errors"
14
+ }
15
+
16
+ # Define colors for each category
17
+ ERROR_CATEGORY_COLORS = {
18
+ "multi_step": "red",
19
+ "percentage": "blue",
20
+ "logic": "orange",
21
+ "unit_conversion": "purple"
22
+ }
23
+
24
+ def refined_classify_error_type(result: Dict[str, Any]) -> str:
25
+ """
26
+ More precise error classification that distinguishes between error types
27
+ """
28
+ question = result["question"].lower()
29
+ ground_truth = str(result["ground_truth"]).lower()
30
+ predicted = str(result["predicted_answer"]).lower()
31
+
32
+ # Check for percentage problems
33
+ if any(term in question for term in ['%', 'percent', 'percentage']):
34
+ return "percentage"
35
+
36
+ # Check for unit conversion issues - prioritize this over multi-step
37
+ if any(unit in question for unit in ['pound', 'pounds', 'ounce', 'ounces', 'gallon', 'gallons',
38
+ 'mile', 'miles', 'hour', 'hours', 'minute', 'minutes',
39
+ 'second', 'seconds', 'dollar', 'dollars', 'cent', 'cents']):
40
+ return "unit_conversion"
41
+
42
+ # Check for multi-step problems (complex wording)
43
+ # Exclude simple arithmetic problems that happen to have "twice", "half", etc.
44
+ multi_step_indicators = [
45
+ len(question.split()) > 30, # Longer questions are more complex
46
+ any(connector in question for connector in ['if', 'then', 'after', 'before', 'when', 'however', 'since']),
47
+ question.count('and') > 3, # More connections indicate complexity
48
+ any(phrase in question for phrase in ['first', 'then', 'next', 'finally', 'after that']),
49
+ any(term in question for term in ['each', 'every', 'per', 'total', 'combined'])
50
+ ]
51
+
52
+ # Additional check to exclude simple problems with basic operations
53
+ simple_arithmetic_indicators = [
54
+ question.count('+') > 0,
55
+ question.count('-') > 0,
56
+ question.count('*') > 0,
57
+ question.count('/') > 0,
58
+ question.count('times') > 0,
59
+ question.count('plus') > 0,
60
+ question.count('minus') > 0
61
+ ]
62
+
63
+ # Only classify as multi-step if it has multiple complexity indicators
64
+ # but doesn't look like simple arithmetic
65
+ complexity_score = sum(multi_step_indicators)
66
+ if complexity_score >= 3 and sum(simple_arithmetic_indicators) <= 2:
67
+ return "multi_step"
68
+
69
+ # Default to logic if other categories don't fit
70
+ return "logic"
71
+
72
+ def load_results(filename: str = "few_shot_results_errors_only.json") -> List[Dict[str, Any]]:
73
+ """Load the evaluation results from JSON file"""
74
+ try:
75
+ with open(filename, 'r') as f:
76
+ data = json.load(f)
77
+
78
+ # Handle both formats: full results and error-only results
79
+ if "results" in data:
80
+ results = data.get("results", [])
81
+ # For error-only files, ensure all are marked as incorrect
82
+ for result in results:
83
+ result["is_correct"] = False
84
+ return results
85
+ else:
86
+ # Assume it's a list of results directly
87
+ return data
88
+
89
+ except FileNotFoundError:
90
+ print(f"Error: File {filename} not found.")
91
+ return []
92
+ except json.JSONDecodeError:
93
+ print(f"Error: Invalid JSON format in {filename}.")
94
+ return []
95
+
96
+ def create_comprehensive_visualization(results: List[Dict], num_samples: int):
97
+ """Create a comprehensive visualization showing all errors with proper categorization"""
98
+
99
+ # Categorize errors
100
+ errors = [r for r in results if not r.get("is_correct", True)]
101
+ error_categories = {category: [] for category in ERROR_CATEGORIES}
102
+
103
+ for error in errors:
104
+ category = refined_classify_error_type(error)
105
+ error_categories[category].append(error)
106
+
107
+ # Prepare data for visualization
108
+ categories = list(error_categories.keys())
109
+ counts = [len(error_categories[cat]) for cat in categories]
110
+ percentages = [count/len(errors)*100 if errors else 0 for count in counts]
111
+
112
+ # Create detailed error list for scatter plot
113
+ error_details = []
114
+ for category, errors_list in error_categories.items():
115
+ for error in errors_list:
116
+ error_details.append({
117
+ "sample_index": error.get("index", 0),
118
+ "category": category,
119
+ "ground_truth": error["ground_truth"],
120
+ "predicted": error["predicted_answer"],
121
+ "question_preview": error["question"][:50] + "..." if len(error["question"]) > 50 else error["question"]
122
+ })
123
+
124
+ error_df = pd.DataFrame(error_details)
125
+
126
+ # Create visualization
127
+ fig = make_subplots(
128
+ rows=2, cols=2,
129
+ subplot_titles=(
130
+ 'Error Category Distribution',
131
+ 'Error Samples by Index',
132
+ 'Ground Truth vs Predicted Values',
133
+ 'Error Analysis Summary'
134
+ ),
135
+ specs=[[{"type": "pie"}, {"type": "scatter"}],
136
+ [{"type": "scatter"}, {"type": "table"}]]
137
+ )
138
+
139
+ # Pie chart - Error distribution with specified colors
140
+ fig.add_trace(
141
+ go.Pie(
142
+ labels=categories,
143
+ values=counts,
144
+ hole=0.4,
145
+ textinfo='label+value+percent',
146
+ hoverinfo='label+value+percent',
147
+ name="Error Types",
148
+ marker=dict(colors=[ERROR_CATEGORY_COLORS[cat] for cat in categories])
149
+ ),
150
+ row=1, col=1
151
+ )
152
+
153
+ # Scatter plot - Error samples by index
154
+ for category in categories:
155
+ category_errors = error_df[error_df['category'] == category]
156
+ if not category_errors.empty:
157
+ fig.add_trace(
158
+ go.Scatter(
159
+ x=category_errors['sample_index'],
160
+ y=[1] * len(category_errors),
161
+ mode='markers',
162
+ marker=dict(size=12, color=ERROR_CATEGORY_COLORS[category]),
163
+ name=category,
164
+ text=category_errors['question_preview'],
165
+ hoverinfo='text+x+y+name'
166
+ ),
167
+ row=1, col=2
168
+ )
169
+
170
+ # Scatter plot - Ground truth vs predicted
171
+ if not error_df.empty:
172
+ fig.add_trace(
173
+ go.Scatter(
174
+ x=error_df['ground_truth'].astype(float),
175
+ y=error_df['predicted'].astype(float),
176
+ mode='markers',
177
+ marker=dict(
178
+ size=10,
179
+ color=[ERROR_CATEGORY_COLORS[cat] for cat in error_df['category']],
180
+ opacity=0.7
181
+ ),
182
+ text=error_df['category'] + ": Sample " + error_df['sample_index'].astype(str),
183
+ hoverinfo='text+x+y',
184
+ name='GT vs Predicted'
185
+ ),
186
+ row=2, col=1
187
+ )
188
+
189
+ # Add ideal line
190
+ max_val = max(max(error_df['ground_truth'].astype(float)), max(error_df['predicted'].astype(float))) + 10
191
+ fig.add_trace(
192
+ go.Scatter(
193
+ x=[0, max_val],
194
+ y=[0, max_val],
195
+ mode='lines',
196
+ line=dict(dash='dash', color='gray'),
197
+ name='Ideal',
198
+ showlegend=False
199
+ ),
200
+ row=2, col=1
201
+ )
202
+
203
+ # Table - Error summary
204
+ summary_data = []
205
+ for category in categories:
206
+ for error in error_categories[category]:
207
+ summary_data.append([
208
+ error.get("index", "N/A"),
209
+ category,
210
+ error["ground_truth"],
211
+ error["predicted_answer"],
212
+ "βœ“" if error["ground_truth"] == error["predicted_answer"] else "βœ—"
213
+ ])
214
+
215
+ if summary_data:
216
+ fig.add_trace(
217
+ go.Table(
218
+ header=dict(values=['Sample', 'Category', 'Ground Truth', 'Predicted', 'Correct']),
219
+ cells=dict(values=[
220
+ [row[0] for row in summary_data],
221
+ [row[1] for row in summary_data],
222
+ [row[2] for row in summary_data],
223
+ [row[3] for row in summary_data],
224
+ [row[4] for row in summary_data]
225
+ ]),
226
+ name='Error Details'
227
+ ),
228
+ row=2, col=2
229
+ )
230
+
231
+ # Update layout
232
+ fig.update_layout(
233
+ title=f"Comprehensive Error Analysis - {num_samples} Samples ({len(errors)} Errors)",
234
+ height=1000,
235
+ width=1400,
236
+ showlegend=True
237
+ )
238
+
239
+ fig.update_xaxes(title_text="Sample Index", row=1, col=2)
240
+ fig.update_yaxes(title_text="", row=1, col=2, showticklabels=False)
241
+ fig.update_xaxes(title_text="Ground Truth", row=2, col=1)
242
+ fig.update_yaxes(title_text="Predicted", row=2, col=1)
243
+
244
+ return fig, error_categories
245
+
246
+ def generate_detailed_error_report(error_categories: Dict, num_samples: int):
247
+ """Generate a detailed report with analysis of each error category"""
248
+
249
+ total_errors = sum(len(errors) for errors in error_categories.values())
250
+ accuracy = (num_samples - total_errors) / num_samples * 100 if num_samples > 0 else 0
251
+
252
+ report = ["# Detailed Error Analysis Report", ""]
253
+ report.append(f"**Total Samples**: {num_samples}")
254
+ report.append(f"**Total Errors**: {total_errors}")
255
+ report.append(f"**Overall Accuracy**: {accuracy:.1f}%")
256
+ report.append("")
257
+
258
+ for category, errors in error_categories.items():
259
+ if errors:
260
+ report.append(f"## {category.upper()} Errors ({len(errors)} errors)")
261
+ report.append("")
262
+
263
+ for i, error in enumerate(errors, 1):
264
+ report.append(f"### Error {i}: Sample {error.get('index', 'N/A')}")
265
+ report.append("**Question:**")
266
+ report.append(f"> {error['question']}")
267
+ report.append("")
268
+ report.append("**Ground Truth:**")
269
+ report.append(f"`{error['ground_truth']}`")
270
+ report.append("")
271
+ report.append("**Model Prediction:**")
272
+ report.append(f"`{error['predicted_answer']}`")
273
+ report.append("")
274
+ report.append("**Error Analysis:**")
275
+ report.append(analyze_specific_error(error, category))
276
+ report.append("")
277
+ report.append("**Suggested Improvement:**")
278
+ report.append(suggest_improvement(error, category))
279
+ report.append("---")
280
+ report.append("")
281
+
282
+ return "\n".join(report)
283
+
284
+ def analyze_specific_error(error: Dict, category: str) -> str:
285
+ """Provide specific analysis for each error"""
286
+ question = error["question"]
287
+ generated = error.get("generated_text", "")
288
+
289
+ if category == "percentage":
290
+ return "Percentage calculation error - likely misunderstanding of percentage relationships or incorrect application of percentage formulas."
291
+
292
+ elif category == "multi_step":
293
+ # Check for specific multi-step failure patterns
294
+ if "then" not in generated.lower() and "so" not in generated.lower():
295
+ return "Missing logical connectors - model failed to show step-by-step reasoning process."
296
+ elif generated.count('\n') < 3:
297
+ return "Insufficient step breakdown - model attempted to solve in too few steps."
298
+ else:
299
+ return "Complex multi-step reasoning failure - model understood individual steps but failed to combine them correctly."
300
+
301
+ elif category == "unit_conversion":
302
+ return "Unit conversion error - likely misunderstanding of measurement units or incorrect conversion between units."
303
+
304
+ return "General reasoning error - model struggled with the problem structure."
305
+
306
+ def suggest_improvement(error: Dict, category: str) -> str:
307
+ """Provide specific improvement suggestions"""
308
+ if category == "percentage":
309
+ return "Train on more percentage word problems with varied contexts. Implement percentage-specific prompting strategies."
310
+
311
+ elif category == "multi_step":
312
+ return "Use chain-of-thought fine-tuning. Break complex problems into sub-tasks. Add intermediate supervision during training."
313
+
314
+ elif category == "unit_conversion":
315
+ return "Practice unit conversion problems with step-by-step solutions. Focus on measurement and currency conversion scenarios. Train on real-world unit conversion applications."
316
+
317
+ return "General reasoning training with diverse problem types and increased context understanding."
318
+
319
+ def main():
320
+ # Load results
321
+ results = load_results('few_shot_results_errors_only.json')
322
+
323
+ if not results:
324
+ print("❌ No results found. Exiting.")
325
+ return
326
+
327
+ num_samples = len(results)
328
+ print(f"πŸ” Performing comprehensive error analysis on {num_samples} error samples...")
329
+
330
+ fig, error_categories = create_comprehensive_visualization(results, num_samples)
331
+
332
+ # Save visualization
333
+ fig.write_html("enhanced_error_analysis.html")
334
+ print("πŸ’Ύ Enhanced visualization saved to enhanced_error_analysis.html")
335
+
336
+ # Generate detailed report
337
+ report = generate_detailed_error_report(error_categories, num_samples)
338
+ with open("detailed_error_report.md", "w") as f:
339
+ f.write(report)
340
+ print("πŸ“ Detailed report saved to detailed_error_report.md")
341
+
342
+ # Print summary
343
+ total_errors = sum(len(errors) for errors in error_categories.values())
344
+ print(f"\nπŸ“Š Error Summary:")
345
+ for category, errors in error_categories.items():
346
+ if errors:
347
+ percentage = len(errors)/total_errors*100 if total_errors > 0 else 0
348
+ print(f" {category.upper()}: {len(errors)} errors ({percentage:.1f}%)")
349
+
350
+ print(f" Overall Accuracy: {((num_samples - total_errors) / num_samples * 100):.1f}%" if num_samples > 0 else "N/A")
351
+
352
+ if __name__ == "__main__":
353
+ main()
Generate Error Analysis Visualizations/updated_error_analysis.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # updated_error_analysis.py
2
+ import json
3
+ import plotly.graph_objects as go
4
+ from plotly.subplots import make_subplots
5
+ import plotly.express as px
6
+ import pandas as pd
7
+ from typing import Dict, List, Any
8
+ import argparse
9
+
10
+ # Error categories with detailed descriptions
11
+ ERROR_CATEGORIES = {
12
+ "multi_step": "Chain-of-thought reasoning failures in multi-step problems",
13
+ "percentage": "Percentage and ratio calculations",
14
+ "logic": "Logical reasoning and problem setup failures",
15
+ "unit_conversion": "Measurement and unit conversion errors"
16
+ }
17
+
18
+ def classify_error_type(result: Dict[str, Any]) -> str:
19
+ """
20
+ Classify the type of error based on the question, ground truth, and predicted answer
21
+ """
22
+ question = result["question"].lower()
23
+ ground_truth = str(result["ground_truth"]).lower()
24
+ predicted = str(result["predicted_answer"]).lower()
25
+
26
+ # Check for percentage problems
27
+ if any(term in question for term in ['%', 'percent', 'percentage']):
28
+ return "percentage"
29
+
30
+ # Check for unit conversion issues - prioritize this over multi-step
31
+ if any(unit in question for unit in ['pound', 'pounds', 'ounce', 'ounces', 'gallon', 'gallons',
32
+ 'mile', 'miles', 'hour', 'hours', 'minute', 'minutes',
33
+ 'second', 'seconds', 'dollar', 'dollars', 'cent', 'cents']):
34
+ return "unit_conversion"
35
+
36
+ # Check for multi-step problems (complex wording)
37
+ # Exclude simple arithmetic problems that happen to have "twice", "half", etc.
38
+ multi_step_indicators = [
39
+ len(question.split()) > 30, # Longer questions are more complex
40
+ any(connector in question for connector in ['if', 'then', 'after', 'before', 'when', 'however', 'since']),
41
+ question.count('and') > 3, # More connections indicate complexity
42
+ any(phrase in question for phrase in ['first', 'then', 'next', 'finally', 'after that']),
43
+ any(term in question for term in ['each', 'every', 'per', 'total', 'combined'])
44
+ ]
45
+
46
+ # Additional check to exclude simple problems with basic operations
47
+ simple_arithmetic_indicators = [
48
+ question.count('+') > 0,
49
+ question.count('-') > 0,
50
+ question.count('*') > 0,
51
+ question.count('/') > 0,
52
+ question.count('times') > 0,
53
+ question.count('plus') > 0,
54
+ question.count('minus') > 0
55
+ ]
56
+
57
+ # Only classify as multi-step if it has multiple complexity indicators
58
+ # but doesn't look like simple arithmetic
59
+ complexity_score = sum(multi_step_indicators)
60
+ if complexity_score >= 3 and sum(simple_arithmetic_indicators) <= 2:
61
+ return "multi_step"
62
+
63
+ # Default to logic if other categories don't fit
64
+ return "logic"
65
+
66
+ def load_results(filename: str = "few_shot_results_errors_only.json") -> List[Dict[str, Any]]:
67
+ """Load the evaluation results from JSON file"""
68
+ try:
69
+ with open(filename, 'r') as f:
70
+ data = json.load(f)
71
+
72
+ # Handle both formats: full results and error-only results
73
+ if "results" in data:
74
+ results = data.get("results", [])
75
+ # For error-only files, ensure all are marked as incorrect
76
+ for result in results:
77
+ result["is_correct"] = False
78
+ return results
79
+ else:
80
+ # Assume it's a list of results directly
81
+ return data
82
+
83
+ except FileNotFoundError:
84
+ print(f"Error: File {filename} not found.")
85
+ return []
86
+ except json.JSONDecodeError:
87
+ print(f"Error: Invalid JSON format in {filename}.")
88
+ return []
89
+
90
+ def analyze_errors(results: List[Dict[str, Any]]) -> Dict[str, Any]:
91
+ """Perform comprehensive error analysis"""
92
+ total_samples = len(results)
93
+
94
+ # For error-only analysis, all samples are incorrect
95
+ correct_count = 0
96
+ incorrect_count = total_samples
97
+
98
+ # Categorize errors
99
+ error_categories = {category: [] for category in ERROR_CATEGORIES}
100
+ error_categories["correct"] = []
101
+
102
+ for result in results:
103
+ if result["is_correct"]:
104
+ error_categories["correct"].append(result)
105
+ else:
106
+ error_type = classify_error_type(result)
107
+ error_categories[error_type].append(result)
108
+
109
+ # Calculate statistics
110
+ accuracy = (correct_count / total_samples) * 100 if total_samples > 0 else 0
111
+
112
+ category_stats = {
113
+ "total_samples": total_samples,
114
+ "correct_count": correct_count,
115
+ "incorrect_count": incorrect_count,
116
+ "accuracy": accuracy,
117
+ "category_counts": {cat: len(errors) for cat, errors in error_categories.items()},
118
+ "category_percentages": {
119
+ cat: (len(errors) / total_samples * 100) if total_samples > 0 else 0
120
+ for cat, errors in error_categories.items()
121
+ },
122
+ "detailed_errors": error_categories
123
+ }
124
+
125
+ return category_stats
126
+
127
+ def create_visualizations(stats: Dict[str, Any], num_samples: int):
128
+ """Create interactive Plotly visualizations with specified color scheme"""
129
+
130
+ # Prepare data for visualizations
131
+ categories = list(ERROR_CATEGORIES.keys()) + ["correct"]
132
+ counts = [stats["category_counts"].get(cat, 0) for cat in categories]
133
+ percentages = [stats["category_percentages"].get(cat, 0) for cat in categories]
134
+
135
+ # Create subplots
136
+ fig = make_subplots(
137
+ rows=2, cols=2,
138
+ subplot_titles=(
139
+ f'Error Distribution (n={num_samples})',
140
+ 'Error Category Breakdown',
141
+ 'Error Percentage by Category',
142
+ 'Sample Index vs Error Type'
143
+ ),
144
+ specs=[[{"type": "pie"}, {"type": "bar"}],
145
+ [{"type": "scatter"}, {"type": "scatter"}]]
146
+ )
147
+
148
+ # Define color scheme
149
+ color_map = {
150
+ 'multi_step': 'red',
151
+ 'percentage': 'blue',
152
+ 'logic': 'orange',
153
+ 'unit_conversion': 'purple',
154
+ 'correct': 'green'
155
+ }
156
+
157
+ # Pie chart - Error distribution
158
+ error_categories_pie = [cat for cat in categories if cat != "correct" and stats["category_counts"].get(cat, 0) > 0]
159
+ error_counts_pie = [stats["category_counts"].get(cat, 0) for cat in error_categories_pie]
160
+ pie_colors = [color_map.get(cat, 'gray') for cat in error_categories_pie]
161
+
162
+ fig.add_trace(
163
+ go.Pie(
164
+ labels=error_categories_pie,
165
+ values=error_counts_pie,
166
+ name="Error Types",
167
+ hole=0.4,
168
+ textinfo='label+percent',
169
+ hoverinfo='label+value+percent',
170
+ marker=dict(colors=pie_colors),
171
+ showlegend=False
172
+ ),
173
+ row=1, col=1
174
+ )
175
+
176
+ # Bar chart - Category counts
177
+ non_zero_categories = [cat for cat in categories if cat != "correct" and stats["category_counts"].get(cat, 0) > 0]
178
+ non_zero_counts = [stats["category_counts"].get(cat, 0) for cat in non_zero_categories]
179
+ non_zero_percentages = [stats["category_percentages"].get(cat, 0) for cat in non_zero_categories]
180
+ bar_colors = [color_map.get(cat, 'gray') for cat in non_zero_categories]
181
+
182
+ fig.add_trace(
183
+ go.Bar(
184
+ x=non_zero_categories,
185
+ y=non_zero_counts,
186
+ name="Count by Category",
187
+ marker_color=bar_colors,
188
+ text=[f"{count}<br>{percent:.1f}%" for count, percent in zip(non_zero_counts, non_zero_percentages)],
189
+ textposition='auto',
190
+ hoverinfo='x+y'
191
+ ),
192
+ row=1, col=2
193
+ )
194
+
195
+ # Scatter plot - Error percentage by category
196
+ error_df = pd.DataFrame({
197
+ 'Category': categories,
198
+ 'Percentage': percentages,
199
+ 'Count': counts
200
+ })
201
+ error_df = error_df[error_df['Count'] > 0] # Only show categories with samples
202
+ scatter_colors = [color_map.get(cat, 'gray') for cat in error_df['Category']]
203
+
204
+ fig.add_trace(
205
+ go.Scatter(
206
+ x=error_df['Category'],
207
+ y=error_df['Percentage'],
208
+ mode='markers+text',
209
+ marker=dict(
210
+ size=error_df['Count']*2 + 10,
211
+ color=scatter_colors,
212
+ opacity=0.8
213
+ ),
214
+ text=error_df['Count'],
215
+ textposition='middle center',
216
+ name='Error Percentage',
217
+ hoverinfo='text',
218
+ hovertext=[f"{cat}: {pct:.1f}% ({cnt} samples)" for cat, pct, cnt in
219
+ zip(error_df['Category'], error_df['Percentage'], error_df['Count'])]
220
+ ),
221
+ row=2, col=1
222
+ )
223
+
224
+ # Scatter plot - Sample index vs error type
225
+ all_results = []
226
+ for category in ERROR_CATEGORIES:
227
+ for result in stats["detailed_errors"][category]:
228
+ all_results.append((result, category))
229
+
230
+ # Sort by sample index
231
+ all_results.sort(key=lambda x: x[0].get("index", 0))
232
+
233
+ sample_indices = [result[0].get("index", i+1) for i, result in enumerate(all_results)]
234
+ error_types = [result[1] for result in all_results]
235
+ error_colors = [color_map.get(error_type, 'gray') for error_type in error_types]
236
+
237
+ fig.add_trace(
238
+ go.Scatter(
239
+ x=sample_indices,
240
+ y=[1] * len(all_results), # All are errors, so y=1
241
+ mode='markers',
242
+ marker=dict(
243
+ color=error_colors,
244
+ size=12,
245
+ opacity=0.7
246
+ ),
247
+ name='Error Types by Sample',
248
+ hoverinfo='x+y+text',
249
+ hovertext=[f"Sample {result[0].get('index', 'N/A')}: {result[1]}" for result in all_results]
250
+ ),
251
+ row=2, col=2
252
+ )
253
+
254
+ # Update layout
255
+ fig.update_layout(
256
+ title=f"Symbolic-Math-Qwen2.5-1.5B-LoRA Error Analysis (n={num_samples} errors)",
257
+ height=1000,
258
+ width=1200,
259
+ showlegend=False
260
+ )
261
+
262
+ fig.update_xaxes(title_text="Error Categories", row=1, col=2)
263
+ fig.update_yaxes(title_text="Number of Errors", row=1, col=2)
264
+ fig.update_xaxes(title_text="Categories", row=2, col=1)
265
+ fig.update_yaxes(title_text="Percentage (%)", row=2, col=1)
266
+ fig.update_xaxes(title_text="Sample Index", row=2, col=2)
267
+ fig.update_yaxes(title_text="Error Type", row=2, col=2, tickvals=[1], ticktext=["Errors"])
268
+
269
+ return fig
270
+
271
+ def generate_detailed_report(stats: Dict[str, Any]):
272
+ """Generate a detailed text report of the analysis"""
273
+ report = []
274
+
275
+ report.append("=" * 60)
276
+ report.append("SYMBOLIC-MATH-QWEN2.5-1.5B-LoRA ERROR ANALYSIS REPORT")
277
+ report.append("=" * 60)
278
+ report.append(f"Total Error Samples: {stats['total_samples']}")
279
+ report.append(f"Overall Accuracy: {stats['accuracy']:.2f}%")
280
+ report.append("")
281
+
282
+ report.append("ERROR CATEGORY BREAKDOWN:")
283
+ report.append("-" * 40)
284
+ for category, count in stats['category_counts'].items():
285
+ if category != "correct" and count > 0:
286
+ percentage = stats['category_percentages'][category]
287
+ report.append(f"{category.upper():<20}: {count:>3} errors ({percentage:>5.1f}%)")
288
+
289
+ report.append("")
290
+ report.append("RECOMMENDATIONS:")
291
+ report.append("-" * 40)
292
+
293
+ # Generate recommendations based on error patterns
294
+ if stats['category_counts'].get('percentage', 0) > 0:
295
+ report.append("β€’ Add percentage calculation training examples")
296
+ report.append("β€’ Implement percentage-specific prompting strategies")
297
+ report.append("β€’ Train on more percentage word problems with varied contexts")
298
+
299
+ if stats['category_counts'].get('multi_step', 0) > 0:
300
+ report.append("β€’ Focus on chain-of-thought reasoning training")
301
+ report.append("β€’ Break down complex problems into sub-steps")
302
+ report.append("β€’ Add intermediate supervision during training")
303
+
304
+ if stats['category_counts'].get('logic', 0) > 0:
305
+ report.append("β€’ Improve logical reasoning capabilities")
306
+ report.append("β€’ Train on problem setup and structure understanding")
307
+ report.append("β€’ General reasoning training with diverse problem types")
308
+
309
+ if stats['category_counts'].get('unit_conversion', 0) > 0:
310
+ report.append("β€’ Practice unit conversion problems")
311
+ report.append("β€’ Focus on measurement and currency conversions")
312
+ report.append("β€’ Train on real-world unit conversion scenarios")
313
+
314
+ return "\n".join(report)
315
+
316
+ def main():
317
+ parser = argparse.ArgumentParser(description="Analyze Symbolic-Math-Qwen2.5-1.5B-LoRA errors on GSM8K dataset")
318
+ parser.add_argument("--samples", type=int, default=16, help="Number of error samples analyzed")
319
+ parser.add_argument("--input", type=str, default="few_shot_results_errors_only.json", help="Input JSON file")
320
+ parser.add_argument("--output", type=str, default="error_analysis.html", help="Output HTML file")
321
+
322
+ args = parser.parse_args()
323
+
324
+ print(f"πŸ” Analyzing {args.samples} error samples...")
325
+ print(f"πŸ“ Loading results from {args.input}")
326
+
327
+ # Load and analyze results
328
+ results = load_results(args.input)
329
+ if not results:
330
+ print("❌ No results found. Exiting.")
331
+ return
332
+
333
+ # Limit to specified number of samples
334
+ results = results[:args.samples]
335
+
336
+ print("πŸ“Š Performing error analysis...")
337
+ stats = analyze_errors(results)
338
+
339
+ # Generate visualizations
340
+ print("πŸ“ˆ Creating visualizations...")
341
+ fig = create_visualizations(stats, args.samples)
342
+
343
+ # Save visualizations
344
+ fig.write_html(args.output)
345
+ print(f"πŸ’Ύ Visualizations saved to {args.output}")
346
+
347
+ # Generate and print detailed report
348
+ report = generate_detailed_report(stats)
349
+ print("\n" + report)
350
+
351
+ # Save report to file
352
+ report_filename = f"error_analysis_report_{args.samples}_errors.txt"
353
+ with open(report_filename, 'w') as f:
354
+ f.write(report)
355
+ print(f"πŸ“ Detailed report saved to {report_filename}")
356
+
357
+ print(f"\n🎯 Error analysis complete! Found {stats['total_samples']} error samples")
358
+ print("πŸ‘‰ Open the HTML file in your browser to view interactive visualizations")
359
+
360
+ if __name__ == "__main__":
361
+ main()