File size: 35,178 Bytes
9f50319 | 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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 | from typing import Tuple, Dict
from evaluate_code.ph_utils import count_connected_components
from evaluate_code.ph_utils import check_graph_group
import statistics
import numpy as np
import json
class Evaluator:
def __init__(self, task_name):
self.task_name = task_name
def evaluate(self, graph_data, extracted_answers):
"""
Call the corresponding evaluation function based on the task type
Args:
graph_data: List of graph data objects
extracted_answers: List of dicts with number_of_features
task_type: Task type
Returns:
accuracy: accuracy
evaluation_results: dict containing detailed evaluation results and statistics
"""
task_evaluators = {
"S_0D": self.evaluate_S_0D,
"S_1D": self.evaluate_S_1D,
"S_Modification": self.evaluate_S_Modification,
"M_Merge": self.evaluate_M_Merge,
"M_Birth": self.evaluate_M_Birth,
"M_Filtration": self.evaluate_M_Filtration,
"H_Selection": self.evaluate_H_Selection,
"H_Generation": self.evaluate_H_Generation,
"R_Selection": self.evaluate_R_Selection,
"R_Generation": self.evaluate_R_Generation,
"R_Classification": self.evaluate_R_Classification,
}
if self.task_name not in task_evaluators:
raise ValueError(f"Unsupported task type: {self.task_name}")
return task_evaluators[self.task_name](graph_data, extracted_answers)
def evaluate_S_0D(self, graph_data, extracted_answers):
"""
Evaluate the accuracy of the structure_0dim_identification task
Args:
graph_data: List of graph data objects
extracted_answers: List of dicts with number_of_features
Returns:
accuracy: accuracy
evaluation_results: dict containing detailed evaluation results and statistics
"""
correct_count = 0
total_count = len(extracted_answers)
evaluation_results = []
for i, answer in enumerate(extracted_answers):
if i >= len(graph_data):
break
correct_answer = graph_data[i]["num_components"]
predicted_answer = answer.get("connected_components")
is_correct = predicted_answer == correct_answer
if is_correct:
correct_count += 1
evaluation_result = {
"is_correct": is_correct,
"predicted_answer": predicted_answer,
"correct_answer": correct_answer
}
evaluation_results.append(evaluation_result)
accuracy = correct_count / total_count if total_count > 0 else 0
stats = {
"total_samples": total_count,
"correct_count": correct_count,
"wrong_count": total_count - correct_count,
"accuracy": accuracy
}
return accuracy, {
"statistics": stats,
"detailed_results": evaluation_results
}
def evaluate_S_1D(self, graph_data, extracted_answers):
"""
Evaluate the accuracy of the structure_1dim_identification task, including two sets of metrics:
1. Whether the existence of 1-dimensional features is correctly judged (through the has_feature field)
2. For graphs with 1-dimensional features, whether the barcodes match completely
Args:
graph_data: List of graph data objects
extracted_answers: List of dicts with has_feature and persistence_pairs
Returns:
accuracy: accuracy of existence judgment
evaluation_results: dict containing detailed evaluation results and statistics
"""
correct_count = 0
total_count = len(extracted_answers)
evaluation_results = []
for i, answer in enumerate(extracted_answers):
if i >= len(graph_data):
break
correct_answer = graph_data[i]["num_holes"]
predicted_answer = answer.get("cycle_holes")
if predicted_answer is None:
evaluation_results.append({
"index": i,
"correct": correct_answer,
"predicted": None,
"match": False,
"error": "Missing 'cycle_holes'"
})
continue
is_correct = predicted_answer == correct_answer
if is_correct:
correct_count += 1
evaluation_result = {
"is_correct": is_correct,
"predicted_answer": predicted_answer,
"correct_answer": correct_answer
}
evaluation_results.append(evaluation_result)
accuracy = correct_count / total_count if total_count > 0 else 0
stats = {
"total_samples": total_count,
"correct_count": correct_count,
"wrong_count": total_count - correct_count,
"accuracy": accuracy
}
return accuracy, {
"statistics": stats,
"detailed_results": evaluation_results
}
def evaluate_S_Modification(self, graph_data, extracted_answers):
"""
Evaluate graph_0dim_modification accuracy
Args:
graph_data: List of graph data objects
extracted_answers: List of dicts with edge_to_add
Returns:
accuracy: accuracy
evaluation_results: dict containing detailed evaluation results and statistics
"""
correct_count = 0
total_count = len(graph_data)
evaluation_results = []
for i, (graph, answer) in enumerate(zip(graph_data, extracted_answers)):
# Check answer format
if "error" in answer:
evaluation_results.append({
"is_correct": False,
"error": answer["error"]
})
continue
if "edge_to_add" not in answer:
evaluation_results.append({
"is_correct": False,
"error": "Missing edge_to_add in answer"
})
continue
# Get edge to add
edge_to_add = answer["edge_to_add"]
if len(edge_to_add) != 2:
evaluation_results.append({
"is_correct": False,
"error": f"Invalid edge format: {edge_to_add}"
})
continue
# Get original edge index and node count
original_edge_index = graph["edge_index"] # Shape [2,N]
num_nodes = graph["num_nodes"]
# Ensure original_edge_index is 2D array
if len(original_edge_index.shape) == 1:
original_edge_index = original_edge_index.reshape(2, -1)
# Validate node index range
if edge_to_add[0] >= num_nodes or edge_to_add[1] >= num_nodes:
evaluation_results.append({
"is_correct": False,
"error": f"Node indices out of range: {edge_to_add}, max index is {num_nodes-1}"
})
continue
# Calculate original number of connected components
original_components = graph["num_components"]
# Add new edge, maintaining [2,N] shape
new_edge = np.array([[edge_to_add[0]], [edge_to_add[1]]], dtype=np.int64)
new_edge_index = np.concatenate([original_edge_index, new_edge], axis=1)
# Calculate new number of connected components
new_components = count_connected_components(new_edge_index, num_nodes)
# Check if correct (number of connected components should decrease)
is_correct = new_components < original_components
if is_correct:
correct_count += 1
evaluation_results.append({
"is_correct": is_correct,
"edge_added": edge_to_add,
"original_components": original_components,
"new_components": new_components
})
# Calculate accuracy
accuracy = correct_count / total_count if total_count > 0 else 0
# Add statistics
stats = {
"total_samples": total_count,
"correct_count": correct_count,
"wrong_count": total_count - correct_count,
"accuracy": accuracy
}
return accuracy, {
"statistics": stats,
"detailed_results": evaluation_results
}
def evaluate_filtration_edge_construction(self, graph_data, extracted_answers):
"""
Evaluate filtration edge construction accuracy
Args:
graph_data: List of graph data objects
extracted_answers: List of dicts with sorted_edges
Returns:
accuracy: accuracy
evaluation_results: dict containing detailed evaluation results and statistics
"""
correct_count = 0
total_count = len(extracted_answers)
evaluation_results = []
for i, answer in enumerate(extracted_answers):
if i >= len(graph_data):
break
# get correct answer (sorted_edges)
correct_edges = graph_data[i]["sorted_edges"]
# get predicted answer (filtration dictionary)
predicted_filtration = answer["filtration"]
# convert predicted filtration to edge list format
predicted_edges = []
for value, edges in predicted_filtration.items():
for u, v in edges:
predicted_edges.append((u, v, float(value)))
# sort edges by weight (ascending)
predicted_edges.sort(key=lambda x: x[2])
# check if correct
is_correct = len(predicted_edges) == len(correct_edges)
if is_correct:
for pred, corr in zip(predicted_edges, correct_edges):
if pred != corr:
is_correct = False
break
if is_correct:
correct_count += 1
# record detailed evaluation results
evaluation_result = {
"is_correct": is_correct,
"predicted_edges": predicted_edges,
"correct_edges": correct_edges,
"edge_count_match": len(predicted_edges) == len(correct_edges),
"edge_order_match": is_correct
}
evaluation_results.append(evaluation_result)
# calculate accuracy
accuracy = correct_count / total_count if total_count > 0 else 0
# prepare statistics
stats = {
"total_samples": total_count,
"correct_count": correct_count,
"wrong_count": total_count - correct_count,
"accuracy": accuracy
}
return accuracy, {
"statistics": stats,
"detailed_results": evaluation_results
}
def evaluate_simplicial_complex_construction(self, graph_data, extracted_answers):
"""
Evaluate simplicial complex construction accuracy
Args:
graph_data: List of graph data objects
extracted_answers: List of dicts with simplicial_complexes
Returns:
accuracy: accuracy
evaluation_results: dict containing detailed evaluation results and statistics
"""
correct_count = 0
total_count = len(extracted_answers)
evaluation_results = []
for i, answer in enumerate(extracted_answers):
if i >= len(graph_data):
break
# get correct answer (2-dimensional simplices)
correct_simplices = {}
for simplex, value in graph_data[i]["simplex"]:
if len(simplex) == 3: # only process 2-dimensional simplices
if value not in correct_simplices:
correct_simplices[value] = []
correct_simplices[value].append(sorted(simplex))
# get predicted answer
predicted_simplices = answer.get("simplicial_complexes", {})
is_correct = True
# check all filtration values
all_values = set(list(correct_simplices.keys()) + list(predicted_simplices.keys()))
for value in all_values:
correct = sorted([sorted(s) for s in correct_simplices.get(value, [])])
predicted = sorted([sorted(s) for s in predicted_simplices.get(value, [])])
if correct != predicted:
is_correct = False
break
if is_correct:
correct_count += 1
# record detailed evaluation results
evaluation_result = {
"is_correct": is_correct,
"predicted_simplices": predicted_simplices,
"correct_simplices": correct_simplices,
"value_match": is_correct
}
evaluation_results.append(evaluation_result)
# calculate accuracy
accuracy = correct_count / total_count if total_count > 0 else 0
stats = {
"total_samples": total_count,
"correct_count": correct_count,
"wrong_count": total_count - correct_count,
"accuracy": accuracy
}
return accuracy, {
"statistics": stats,
"detailed_results": evaluation_results
}
def evaluate_M_Merge(self, graph_data, extracted_answers):
"""
Evaluate 0-dimensional persistent homology calculation accuracy
Args:
graph_data: List of graph data objects
extracted_answers: List of dictionaries containing death time of feature
Returns:
accuracy: accuracy
evaluation_results: dict containing detailed evaluation results and statistics
"""
correct_count = 0
total_count = len(extracted_answers)
evaluation_results = []
for i, answer in enumerate(extracted_answers):
if i >= len(graph_data):
break
# get correct answer
correct_time = graph_data[i]["death_value"]
# get predicted answer
if "error" in answer:
is_correct = False
predicted_time = None
else:
predicted_time = answer.get("death_time", [None])[0] # Get first value from death_time list
is_correct = predicted_time == correct_time
if is_correct:
correct_count += 1
evaluation_result = {
"is_correct": is_correct,
"predicted_time": predicted_time,
"correct_time": correct_time
}
evaluation_results.append(evaluation_result)
accuracy = correct_count / total_count if total_count > 0 else 0
stats = {
"total_samples": total_count,
"correct_count": correct_count,
"wrong_count": total_count - correct_count,
"accuracy": accuracy
}
return accuracy, {
"statistics": stats,
"detailed_results": evaluation_results
}
def evaluate_M_Birth(self, graph_data, extracted_answers):
"""
Evaluate 1-dimensional persistent homology calculation accuracy
Args:
graph_data: List of graph data objects
extracted_answers: List of dicts with persistent_features
Returns:
accuracy: accuracy
evaluation_results: dict containing detailed evaluation results and statistics
"""
correct_count = 0
total_count = len(extracted_answers)
evaluation_results = []
for i, answer in enumerate(extracted_answers):
if i >= len(graph_data):
break
# get correct answer
correct_time = graph_data[i]["birth_value"]
# get predicted answer
if "error" in answer:
is_correct = False
predicted_time = None
else:
predicted_time = answer.get("birth_time", [None])[0] # Get first value from death_time list
is_correct = predicted_time == correct_time
if is_correct:
correct_count += 1
evaluation_result = {
"is_correct": is_correct,
"predicted_time": predicted_time,
"correct_time": correct_time
}
evaluation_results.append(evaluation_result)
accuracy = correct_count / total_count if total_count > 0 else 0
stats = {
"total_samples": total_count,
"correct_count": correct_count,
"wrong_count": total_count - correct_count,
"accuracy": accuracy
}
return accuracy, {
"statistics": stats,
"detailed_results": evaluation_results
}
def evaluate_M_Filtration(self, graph_data, extracted_answers):
"""
Evaluate filtration_features_count accuracy
Args:
graph_data: List of graph data objects
extracted_answers: filtration_features_count number
Returns:
accuracy: accuracy
evaluation_results: dict containing detailed evaluation results and statistics
"""
correct_count = 0
total_count = len(extracted_answers)
evaluation_results = []
for i, answer in enumerate(extracted_answers):
if i >= len(graph_data):
break
# get correct answer
correct_n = graph_data[i]["t3_0dim"]
# get predicted answer
if "error" in answer:
is_correct = False
predicted_count = None
else:
predicted_count = answer.get("connected_components", [None])[0] # Get first value from death_time list
is_correct = predicted_count == correct_n
if is_correct:
correct_count += 1
evaluation_result = {
"is_correct": is_correct,
"predicted_count": predicted_count,
"correct_count": correct_n
}
evaluation_results.append(evaluation_result)
accuracy = correct_count / total_count if total_count > 0 else 0
stats = {
"total_samples": total_count,
"correct_count": correct_count,
"wrong_count": total_count - correct_count,
"accuracy": accuracy
}
return accuracy, {
"statistics": stats,
"detailed_results": evaluation_results
}
def _check_edge_sorting(self, edge_sorting, graph_data):
"""Check if edge sorting is correct"""
try:
if not edge_sorting:
return False
for i in range(1, len(edge_sorting)):
if edge_sorting[i][2] < edge_sorting[i-1][2]:
return False
return True
except:
return False
def evaluate_H_Selection(self, graph_data, extracted_answers) -> Tuple[float, Dict]:
"""
Evaluate filtration method selection ranking statistics
Args:
graph_data: List of graph data objects, where graph_data[2i].better_filter contains correct answer
extracted_answers: List of dicts with selected_method
Returns:
Tuple of (accuracy, detailed results dict)
"""
detailed_results = []
all_ranks = []
top1_count = 0
top2_count = 0
top3_count = 0
for i, answer in enumerate(extracted_answers):
if answer is None or answer.get("selected_method") is None:
detailed_results.append({
"reason": "No valid answer extracted"
})
continue
graph_idx = i
if graph_idx >= len(graph_data):
break
predicted_method = answer["selected_method"]
if predicted_method == 'weight':
predicted_method = 'e'
if predicted_method == "k-shell":
predicted_method = "k_shell"
dist_features = {'dist_k_shell': graph_data[graph_idx][0]['dist_k_shell'], 'dist_closeness': graph_data[graph_idx][0]['dist_closeness'], 'dist_e': graph_data[graph_idx][0]['dist_e'], 'dist_betweenness': graph_data[graph_idx][0]['dist_betweenness'], 'dist_degree': graph_data[graph_idx][0]['dist_degree'], 'dist_eigenvector': graph_data[graph_idx][0]['dist_eigenvector']}
predicted_rank = None
current_rank = 1
current_distance = None
same_rank_count = 0
for method, distance in dist_features.items():
if current_distance is not None and distance != current_distance:
current_rank += same_rank_count
same_rank_count = 0
current_distance = distance
elif current_distance is None:
current_distance = distance
if method.replace('dist_', '') == predicted_method:
predicted_rank = current_rank
all_ranks.append(current_rank)
if current_rank == 1:
top1_count += 1
if current_rank <= 2:
top2_count += 1
if current_rank <= 3:
top3_count += 1
break
same_rank_count += 1
detailed_results.append({
"predicted": predicted_method,
"predicted_rank": predicted_rank,
"method_rankings": dict(dist_features)
})
ranking_stats = {
'mean_rank': sum(all_ranks) / len(all_ranks) if all_ranks else float('inf'),
'min_rank': min(all_ranks) if all_ranks else float('inf'),
'max_rank': max(all_ranks) if all_ranks else float('inf'),
'std_rank': statistics.stdev(all_ranks) if len(all_ranks) > 1 else 0,
'total_predictions': len(all_ranks),
'top1_count': top1_count,
'top2_count': top2_count,
'top3_count': top3_count,
'top1_ratio': top1_count / len(all_ranks) if all_ranks else 0,
'top2_ratio': top2_count / len(all_ranks) if all_ranks else 0,
'top3_ratio': top3_count / len(all_ranks) if all_ranks else 0
}
return 0.0, {
"statistics": {
**ranking_stats
},
"detailed_results": detailed_results
}
def evaluate_H_Generation(self, graph_data, extracted_answers) -> Tuple[float, Dict]:
"""
评估过滤序列选择的排名统计
Args:
graph_data: List of graph data objects
extracted_answers: List of dicts with selected_filtration_values field
Returns:
Tuple (accuracy, detailed_results_dict)
"""
total = 0
detailed_results = []
for i, answer in enumerate(extracted_answers):
if i >= len(graph_data):
break
if answer is None or "selected_filtration_values" not in answer:
detailed_results.append({
"reason": "No valid answer extracted"
})
continue
graph1 = graph_data[i][0]
selected_values = answer["selected_filtration_values"]
if isinstance(selected_values, (int, float)):
selected_values = [[selected_values]]
elif isinstance(selected_values, (list, tuple)) and not any(isinstance(x, (list, tuple)) for x in selected_values):
selected_values = [selected_values]
selected_distances = []
selected_ranks = []
for seq in selected_values:
if not isinstance(seq, (list, tuple)):
seq = [seq]
seq_tuple = tuple(sorted(float(x) if isinstance(x, (int, float)) else x for x in seq))
found_match = False
current_rank = 1
current_distance = None
same_rank_count = 0
sorted_distances = json.loads(graph1['sorted_distances'])
for item in sorted_distances:
curr_seq = item['nodes']
distance = item['distance']
curr_seq_tuple = tuple(sorted(float(x) if isinstance(x, (int, float)) else x for x in curr_seq))
if current_distance is not None and distance != current_distance:
current_rank += same_rank_count
same_rank_count = 0
current_distance = distance
elif current_distance is None:
current_distance = distance
if curr_seq_tuple == seq_tuple:
selected_distances.append(float(distance))
selected_ranks.append(current_rank)
found_match = True
break
same_rank_count += 1
if not found_match:
selected_distances.append(float('inf'))
selected_ranks.append(len(graph1.sorted_distances) + 1)
rank = sum(selected_ranks) / len(selected_ranks) if selected_ranks else float('inf')
in_top3 = sum(1 for rank in selected_ranks if rank <= 3)
in_top10 = sum(1 for rank in selected_ranks if rank <= 10)
top3 = in_top3 / len(selected_ranks) if selected_ranks else 0
top10 = in_top10 / len(selected_ranks) if selected_ranks else 0
total += 1
detailed_results.append({
"selected_ranks": selected_ranks,
"selected_distances": selected_distances,
"rank": float(rank),
"top3": float(top3),
"top10": float(top10),
"original_values": selected_values
})
valid_results = [r for r in detailed_results if "rank" in r]
rank_list = [r["rank"] for r in valid_results]
avg_stats = {
"mean_rank": float(sum(rank_list) / len(rank_list)) if rank_list else float('inf'),
"top3": float(sum(r["top3"] for r in valid_results) / len(valid_results)) if valid_results else 0.0,
"top10": float(sum(r["top10"] for r in valid_results) / len(valid_results)) if valid_results else 0.0,
"std_rank": float(statistics.stdev(rank_list)) if len(rank_list) > 1 else 0.0
}
return 0.0, {
"statistics": {
"total": int(total),
**avg_stats
},
"detailed_results": detailed_results
}
def evaluate_R_Classification(self, graph_data, extracted_answers):
correct_count = 0
total_count = len(extracted_answers)
evaluation_results = []
ground_truth_sorted = sorted([sorted([1, 2]), sorted([3, 4])])
for i, answer in enumerate(extracted_answers):
if "error" in answer or "categories" not in answer:
evaluation_results.append({
"index": i,
"is_correct": False,
"reason": "Missing or invalid 'categories' field",
"predicted": None,
"expected": ground_truth_sorted
})
continue
predicted = answer["categories"]
try:
predicted_sorted = sorted([sorted(group) for group in predicted])
is_correct = predicted_sorted == ground_truth_sorted
except Exception as e:
is_correct = False
predicted_sorted = None
if is_correct:
correct_count += 1
evaluation_results.append({
"index": i,
"is_correct": is_correct,
"predicted": predicted,
"expected": ground_truth_sorted
})
accuracy = correct_count / total_count if total_count > 0 else 0.0
stats = {
"total_samples": total_count,
"correct_count": correct_count,
"wrong_count": total_count - correct_count,
"accuracy": accuracy
}
return accuracy, {
"statistics": stats,
"detailed_results": evaluation_results
}
def evaluate_R_Selection(self, graph_data, extracted_answers):
"""
Evaluate whether the selected filtration method is correct based on method_dict.
Args:
graph_data: List of graph data entries, where each entry is a tuple (graph, ...) and graph.method_dict is a dict
extracted_answers: List of dicts with key 'selected_method'
Returns:
accuracy: float
result_summary: dict with statistics and detailed evaluation results
"""
correct_count = 0
total_count = len(extracted_answers)
evaluation_results = []
for i, answer in enumerate(extracted_answers):
if i >= len(graph_data):
break
method_dict = {
'weight': graph_data[i][0]['method_weight'],
'degree': graph_data[i][0]['method_degree'],
'betweenness': graph_data[i][0]['method_betweenness'],
'k_shell': graph_data[i][0]['method_k_shell'],
'closeness': graph_data[i][0]['method_closeness'],
'eigenvector': graph_data[i][0]['method_eigenvector']
}
if "error" in answer or "selected_method" not in answer:
evaluation_results.append({
"index": i,
"is_correct": False,
"predicted_method": answer.get("selected_method", None),
"expected_methods": [k for k, v in method_dict.items() if v],
"reason": "No valid method extracted"
})
continue
predicted_method = answer.get("selected_method")
if predicted_method not in method_dict:
return {"error": f"Invalid method selected: {predicted_method}"}
is_correct = bool(method_dict[predicted_method])
if is_correct:
correct_count += 1
evaluation_results.append({
"index": i,
"is_correct": is_correct,
"predicted_method": predicted_method,
"expected_methods": [k for k, v in method_dict.items() if v]
})
accuracy = correct_count / total_count if total_count > 0 else 0.0
stats = {
"total_samples": total_count,
"correct_count": correct_count,
"wrong_count": total_count - correct_count,
"accuracy": accuracy
}
return accuracy, {
"statistics": stats,
"detailed_results": evaluation_results
}
def evaluate_R_Generation(self, graph_data, extracted_answers):
"""
Evaluate predictions based on filtration_values using check_filt_value().
Args:
graph_data: List of graph data objects
extracted_answers: List of dicts with key 'filtration_values'
Returns:
accuracy: float
result_summary: dict with statistics and detailed evaluation results
"""
correct_count = 0
total_count = len(extracted_answers)
evaluation_results = []
for i, answer in enumerate(extracted_answers):
if i >= len(graph_data):
break
if "error" in answer or "filtration_values" not in answer:
evaluation_results.append({
"index": i,
"is_correct": False,
"predicted_values": answer.get("filtration_values", None),
"reason": "No valid filtration_values extracted"
})
continue
filtration_values = answer["filtration_values"]
is_correct,distances = check_graph_group(graph_data[i], method='weight',pre_calculate=False,filt_value=filtration_values)
if is_correct:
correct_count += 1
correct = "True"
else:
correct = "False"
evaluation_results.append({
"index": i,
"is_correct": correct,
"predicted_values": filtration_values,
"correct": correct
})
accuracy = correct_count / total_count if total_count > 0 else 0.0
stats = {
"total_samples": total_count,
"correct_count": correct_count,
"wrong_count": total_count - correct_count,
"accuracy": accuracy
}
return accuracy, {
"statistics": stats,
"detailed_results": evaluation_results
}
|