def classification_report_to_dict(report): lines = report.split('\n') lines = [line.strip() for line in lines if line.strip()] classes = [] class_dict = {} for line in lines[1:]: t = line.split() if len(t) == 1: class_name = t[0] classes.append(class_name) class_dict[class_name] = {} else: class_dict[class_name]['precision'] = float(t[0]) class_dict[class_name]['recall'] = float(t[1]) class_dict[class_name]['f1-score'] = float(t[2]) class_dict[class_name]['support'] = int(t[3]) macro_avg = lines[-3].split() micro_avg = lines[-2].split() class_dict['macro avg'] = {'precision': float(macro_avg[1]), 'recall': float(macro_avg[2]), 'f1-score': float(macro_avg[3]), 'support': int(macro_avg[4])} class_dict['micro avg'] = {'precision': float(micro_avg[1]), 'recall': float(micro_avg[2]), 'f1-score': float(micro_avg[3]), 'support': int(micro_avg[4])} return class_dict def classification_report_from_dict(report_dict): classes = list(report_dict.keys()) classes.remove('macro avg') classes.remove('micro avg') lines = [' precision recall f1-score support\n\n'] for class_name in classes: line = f"{class_name.ljust(15)}{report_dict[class_name]['precision']:.2f} {report_dict[class_name]['recall']:.2f} {report_dict[class_name]['f1-score']:.2f} {report_dict[class_name]['support']:5d}\n" lines.append(line) lines.append('\n') macro_avg = report_dict['macro avg'] line = f"{'macro avg'.ljust(15)}{macro_avg['precision']:.2f} {macro_avg['recall']:.2f} {macro_avg['f1-score']:.2f} {macro_avg['support']:5d}\n" lines.append(line) micro_avg = report_dict['micro avg'] line = f"{'micro avg'.ljust(15)}{micro_avg['precision']:.2f} {micro_avg['recall']:.2f} {micro_avg['f1-score']:.2f} {micro_avg['support']:5d}\n" lines.append(line) report_str = ''.join(lines) return report_str for i, report in enumerate(report): report_dict[f'report_{i + 1}'] = classification_report_to_dict(report) report_df = pd.DataFrame.from_dict(report_dict, orient='index') avg_report_dict = report_df.mean().to_dict() avg_report_str = classification_report_from_dict(avg_report_dict) print(avg_report_str)出现local variable 'class_name' referenced before assignment怎么解决
时间: 2024-01-31 07:03:49 浏览: 140
whmap.rar_WHmap_classification_delphi Gauge.p
这个错误通常是因为在使用变量之前没有对其进行初始化或赋值,或者在使用变量之前使用了删除、重命名或声明之前的变量名。在你提供的代码中,我无法确定错误具体出现在哪一行,但是最可能的原因是在 `classification_report_from_dict` 函数中的 `classes` 列表为空,导致 `class_name` 变量没有被初始化。你可以在调用 `classification_report_from_dict` 函数之前,检查 `report_dict` 是否包含正确的数据。你也可以在 `classification_report_from_dict` 函数中添加一些错误处理机制,以避免出现未定义变量的情况。
阅读全文