File size: 25,537 Bytes
64bce2a | 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 | import matplotlib.pyplot as plt
import torch
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import os
def plot_losses(losses, title="Training Loss", xlabel="Iteration", ylabel="Loss", save_path=None):
"""
Plot training losses.
Args:
losses (list): List of loss values
title (str): Plot title
xlabel (str): X-axis label
ylabel (str): Y-axis label
save_path (str): Optional path to save the figure
"""
plt.figure(figsize=(10, 6))
plt.plot(losses, 'o-')
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.grid(True)
if save_path:
plt.savefig(save_path)
print(f"Loss plot saved to {save_path}")
plt.show()
def plot_multiple_losses(loss_dict, title="Training Losses", xlabel="Iteration", ylabel="Loss", save_path=None):
"""
Plot multiple loss curves for comparison.
Args:
loss_dict (dict): Dictionary mapping loss names to lists of loss values
title (str): Plot title
xlabel (str): X-axis label
ylabel (str): Y-axis label
save_path (str): Optional path to save the figure
"""
plt.figure(figsize=(12, 7))
for name, losses in loss_dict.items():
plt.plot(losses, '-', label=name)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.grid(True)
plt.legend()
if save_path:
plt.savefig(save_path)
print(f"Multiple losses plot saved to {save_path}")
plt.show()
def plot_multiple_accuracies(acc_dict, title="Classification Accuracy", xlabel="Percent Labeled", ylabel="Accuracy", save_path=None):
"""
Plot multiple accuracy curves for comparison.
Args:
acc_dict (dict): Dictionary mapping method names to [x_values, accuracy_values]
title (str): Plot title
xlabel (str): X-axis label
ylabel (str): Y-axis label
save_path (str): Optional path to save the figure
"""
plt.figure(figsize=(14, 8))
markers = ['o', 's', '^', 'v', 'd', '*', 'x', '+', 'h', 'p']
colors = plt.cm.tab10.colors
for i, (name, (x_values, acc_values)) in enumerate(acc_dict.items()):
marker = markers[i % len(markers)]
color = colors[i % len(colors)]
plt.plot(x_values, acc_values, marker=marker, color=color, linewidth=2, markersize=8, label=name)
plt.xlabel(xlabel, fontsize=14)
plt.ylabel(ylabel, fontsize=14)
plt.title(title, fontsize=16)
plt.grid(True)
plt.legend(fontsize=12)
plt.ylim(0, 1)
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Accuracy comparison plot saved to {save_path}")
plt.show()
def plot_swiss_roll_3d(xyz, labels, title="Swiss Roll in 3D", save_path=None, figsize=(10, 8)):
"""
Plot 3D Swiss roll with color-coded labels.
Args:
xyz (numpy.ndarray): 3D coordinates of points
labels (numpy.ndarray): Labels for coloring points
title (str): Plot title
save_path (str): Optional path to save the figure
figsize (tuple): Figure size
"""
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111, projection='3d')
scatter = ax.scatter(
xyz[:, 0],
xyz[:, 1],
xyz[:, 2],
c=labels,
cmap='bwr',
s=40
)
legend = ax.legend(*scatter.legend_elements(), title="Classes")
ax.add_artist(legend)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_title(title)
if save_path:
plt.savefig(save_path)
print(f"3D plot saved to {save_path}")
plt.show()
def plot_laplacian_comparison(real_lap, pred_lap, title="Laplacian Comparison", save_path=None):
"""
Plot comparison between real and predicted Laplacian matrices.
Args:
real_lap (numpy.ndarray): Real Laplacian matrix
pred_lap (numpy.ndarray): Predicted Laplacian matrix
title (str): Plot title
save_path (str): Optional path to save the figure
"""
# Convert to numpy if tensors
if isinstance(real_lap, torch.Tensor):
real_lap = real_lap.cpu().numpy()
if isinstance(pred_lap, torch.Tensor):
pred_lap = pred_lap.cpu().numpy()
diff = pred_lap - real_lap
fig, axs = plt.subplots(1, 3, figsize=(18, 6))
# Plot real Laplacian
im0 = axs[0].imshow(real_lap, cmap='viridis')
axs[0].set_title("Real Laplacian")
plt.colorbar(im0, ax=axs[0])
# Plot predicted Laplacian
im1 = axs[1].imshow(pred_lap, cmap='viridis')
axs[1].set_title("Predicted Laplacian")
plt.colorbar(im1, ax=axs[1])
# Plot difference
im2 = axs[2].imshow(diff, cmap='bwr')
axs[2].set_title("Difference (Predicted - Real)")
plt.colorbar(im2, ax=axs[2])
plt.suptitle(title, fontsize=16)
plt.tight_layout()
if save_path:
plt.savefig(save_path)
print(f"Laplacian comparison plot saved to {save_path}")
plt.show()
# Return Frobenius norm of the difference
return np.sqrt(np.sum(diff**2))
def plot_eigenvector_comparison(real_evecs, pred_evecs, k=3, title="Eigenvector Comparison", save_path=None):
"""
Plot comparison between real and predicted eigenvectors.
Args:
real_evecs (numpy.ndarray): Real eigenvectors
pred_evecs (numpy.ndarray): Predicted eigenvectors
k (int): Number of eigenvectors to plot
title (str): Plot title
save_path (str): Optional path to save the figure
"""
# Convert to numpy if tensors
if isinstance(real_evecs, torch.Tensor):
real_evecs = real_evecs.cpu().numpy()
if isinstance(pred_evecs, torch.Tensor):
pred_evecs = pred_evecs.cpu().numpy()
# Normalize eigenvectors
real_evecs_norm = real_evecs / np.linalg.norm(real_evecs, axis=0, keepdims=True)
pred_evecs_norm = pred_evecs / np.linalg.norm(pred_evecs, axis=0, keepdims=True)
# Plot comparisons
fig, axs = plt.subplots(k, 1, figsize=(10, 4*k))
if k == 1:
axs = [axs]
for i in range(k):
# Handle sign ambiguity
corr_pos = np.corrcoef(real_evecs_norm[:, i], pred_evecs_norm[:, i])[0, 1]
corr_neg = np.corrcoef(real_evecs_norm[:, i], -pred_evecs_norm[:, i])[0, 1]
pred_ev_to_plot = -pred_evecs_norm[:, i] if abs(corr_neg) > abs(corr_pos) else pred_evecs_norm[:, i]
corr = max(abs(corr_pos), abs(corr_neg))
axs[i].plot(real_evecs_norm[:, i], 'b-', label='Real')
axs[i].plot(pred_ev_to_plot, 'r--', label='Predicted')
axs[i].grid(True)
axs[i].set_title(f"Eigenvector {i+1} (Correlation: {corr:.4f})")
axs[i].legend()
plt.suptitle(title, fontsize=16)
plt.tight_layout()
if save_path:
plt.savefig(save_path)
print(f"Eigenvector comparison plot saved to {save_path}")
plt.show()
def plot_embedding_3d(embeddings, labels, title="3D Embedding", save_path=None):
"""
Plot 3D embedding of points with color-coded labels.
Args:
embeddings (numpy.ndarray): Embedding coordinates (n_samples, 3)
labels (numpy.ndarray): Labels for coloring points
title (str): Plot title
save_path (str): Optional path to save the figure
"""
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
scatter = ax.scatter(
embeddings[:, 0],
embeddings[:, 1],
embeddings[:, 2],
c=labels,
cmap='bwr',
s=40
)
legend = ax.legend(*scatter.legend_elements(), title="Classes")
ax.add_artist(legend)
ax.set_xlabel("Component 1")
ax.set_ylabel("Component 2")
ax.set_zlabel("Component 3")
ax.set_title(title)
if save_path:
plt.savefig(save_path)
print(f"3D embedding plot saved to {save_path}")
plt.show()
def create_multi_embedding_plot(embeddings_dict, labels, title="Embedding Comparison", save_path=None):
"""
Create a multi-panel plot comparing different embeddings.
Args:
embeddings_dict (dict): Dictionary mapping names to embedding arrays
labels (numpy.ndarray): Labels for coloring points
title (str): Plot title
save_path (str): Optional path to save the figure
"""
n_embeddings = len(embeddings_dict)
n_cols = min(3, n_embeddings)
n_rows = (n_embeddings + n_cols - 1) // n_cols
fig = plt.figure(figsize=(6*n_cols, 5*n_rows))
for i, (name, embedding) in enumerate(embeddings_dict.items()):
ax = fig.add_subplot(n_rows, n_cols, i+1, projection='3d')
scatter = ax.scatter(
embedding[:, 0],
embedding[:, 1],
embedding[:, 2],
c=labels,
cmap='bwr',
s=30
)
if i == 0:
legend = ax.legend(*scatter.legend_elements(), title="Classes")
ax.add_artist(legend)
ax.set_xlabel("Component 1")
ax.set_ylabel("Component 2")
ax.set_zlabel("Component 3")
ax.set_title(name)
plt.suptitle(title, fontsize=16)
plt.tight_layout(rect=[0, 0, 1, 0.95]) # Adjust for the super title
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Multi-embedding plot saved to {save_path}")
plt.show()
def plot_accuracy_vs_context(acc_results, title="Accuracy vs Context Size", xlabel="Context Size", ylabel="Accuracy", save_path=None):
"""
Plot accuracy as a function of context size.
Args:
acc_results (dict): Dictionary mapping context size to accuracy
title (str): Plot title
xlabel (str): X-axis label
ylabel (str): Y-axis label
save_path (str): Optional path to save the figure
"""
import matplotlib.pyplot as plt
# Extract data
context_sizes = sorted(acc_results.keys())
accuracies = [acc_results[c] for c in context_sizes]
# Create plot
plt.figure(figsize=(10, 6))
plt.plot(context_sizes, accuracies, 'o-', linewidth=2, markersize=8)
plt.xlabel(xlabel, fontsize=14)
plt.ylabel(ylabel, fontsize=14)
plt.title(title, fontsize=16)
plt.grid(True)
plt.ylim(0, 1)
# Add specific annotations for min and max accuracies
min_acc = min(accuracies)
max_acc = max(accuracies)
min_idx = accuracies.index(min_acc)
max_idx = accuracies.index(max_acc)
plt.annotate(f'Min: {min_acc:.3f}',
xy=(context_sizes[min_idx], min_acc),
xytext=(10, 20),
textcoords='offset points',
arrowprops=dict(arrowstyle='->'))
plt.annotate(f'Max: {max_acc:.3f}',
xy=(context_sizes[max_idx], max_acc),
xytext=(10, -20),
textcoords='offset points',
arrowprops=dict(arrowstyle='->'))
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Accuracy vs context plot saved to {save_path}")
plt.show()
def plot_embedding_comparison(raw_coords, embedding, labels, title="Embedding Comparison", save_path=None):
"""
Create side-by-side plots comparing raw coordinates with embedding.
Args:
raw_coords (numpy.ndarray): Raw coordinates [n_samples, 2]
embedding (numpy.ndarray): Embedding coordinates [n_samples, n_components]
labels (numpy.ndarray): Labels for coloring points
title (str): Plot title
save_path (str): Optional path to save the figure
"""
import matplotlib.pyplot as plt
import numpy as np
# Create figure
fig, axs = plt.subplots(1, 2, figsize=(14, 6))
# Plot raw coordinates
scatter1 = axs[0].scatter(
raw_coords[:, 0],
raw_coords[:, 1],
c=labels,
cmap='bwr',
s=40,
alpha=0.8
)
axs[0].set_xlabel("X")
axs[0].set_ylabel("Y")
axs[0].set_title("Raw Coordinates")
axs[0].grid(True)
# Plot embedding (first 2 components)
if embedding.shape[1] >= 2:
scatter2 = axs[1].scatter(
embedding[:, 0],
embedding[:, 1],
c=labels,
cmap='bwr',
s=40,
alpha=0.8
)
axs[1].set_xlabel("Component 1")
axs[1].set_ylabel("Component 2")
axs[1].set_title("Embedding")
axs[1].grid(True)
# Add legend
legend = axs[0].legend(*scatter1.legend_elements(), title="Classes")
axs[0].add_artist(legend)
plt.suptitle(title, fontsize=16)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Embedding comparison plot saved to {save_path}")
plt.show()
def plot_swiss_roll_colored_by_embedding(xyz, embedding, component_idx=0, title="Swiss Roll Colored by Embedding", save_path=None):
"""
Plot 3D Swiss roll colored by embedding component values.
Args:
xyz (numpy.ndarray): 3D coordinates of points
embedding (numpy.ndarray): Embedding values
component_idx (int): Index of embedding component to use for coloring
title (str): Plot title
save_path (str): Optional path to save the figure
"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
# Extract the selected component
if embedding.ndim > 1:
color_values = embedding[:, component_idx]
else:
color_values = embedding
# Normalize values for coloring
normalized_values = (color_values - np.min(color_values)) / (np.max(color_values) - np.min(color_values))
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
scatter = ax.scatter(
xyz[:, 0],
xyz[:, 1],
xyz[:, 2],
c=normalized_values,
cmap='viridis',
s=40
)
# Add a color bar
cbar = plt.colorbar(scatter)
cbar.set_label(f"Normalized Component {component_idx+1} Values")
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_title(title)
if save_path:
plt.savefig(save_path)
print(f"3D embedding plot saved to {save_path}")
plt.show()
import matplotlib.pyplot as plt
import numpy as np
import os
import datetime
def plot_test_results(args, results, n_samples=100, figure_dir='../figures'):
"""
Plot test results across different context sizes.
Args:
args: Command line arguments containing test_mode, data_type, etc.
results: Dictionary containing the test results for each context size
n_samples: Total number of samples per graph
figure_dir: Directory to save the figures
"""
# Create timestamp for unique filenames
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
# Create directory structure based on test_mode and data_type
specific_dir = os.path.join(figure_dir, f"test_mode_{args.test_mode}", f"data_{args.data_type}")
os.makedirs(specific_dir, exist_ok=True)
# Extract context sizes and convert to percentages
context_sizes = list(results.keys())
context_percentages = [ctx_size / n_samples * 100 for ctx_size in context_sizes]
# Extract average accuracies and standard deviations for each method
avg_icl = [sum(results[ctx]['icl_accs']) / len(results[ctx]['icl_accs']) for ctx in context_sizes]
avg_lr = [sum(results[ctx]['lr_accs']) / len(results[ctx]['lr_accs']) for ctx in context_sizes]
avg_rkhs = [sum(results[ctx]['rkhs_accs']) / len(results[ctx]['rkhs_accs']) for ctx in context_sizes]
avg_raw_lr = [sum(results[ctx]['raw_lr_accs']) / len(results[ctx]['raw_lr_accs']) for ctx in context_sizes]
avg_raw_rkhs = [sum(results[ctx]['raw_rkhs_accs']) / len(results[ctx]['raw_rkhs_accs']) for ctx in context_sizes]
std_icl = [np.std(results[ctx]['icl_accs']) for ctx in context_sizes]
std_lr = [np.std(results[ctx]['lr_accs']) for ctx in context_sizes]
std_rkhs = [np.std(results[ctx]['rkhs_accs']) for ctx in context_sizes]
std_raw_lr = [np.std(results[ctx]['raw_lr_accs']) for ctx in context_sizes]
std_raw_rkhs = [np.std(results[ctx]['raw_rkhs_accs']) for ctx in context_sizes]
# Generate a base filename with test details
base_filename = f"mode_{args.test_mode}_data_{args.data_type}_samples_{n_samples}_{timestamp}"
# Create the main plot
plt.figure(figsize=(10, 6))
# Plot each method with error bars
plt.errorbar(context_percentages, avg_icl, yerr=std_icl, fmt='o-', label='ICL', capsize=4, linewidth=2)
plt.errorbar(context_percentages, avg_lr, yerr=std_lr, fmt='s-', label='LR (PE)', capsize=4, linewidth=2)
plt.errorbar(context_percentages, avg_rkhs, yerr=std_rkhs, fmt='^-', label='RKHS (PE)', capsize=4, linewidth=2)
plt.errorbar(context_percentages, avg_raw_lr, yerr=std_raw_lr, fmt='d--', label='LR (Raw)', capsize=4, linewidth=2)
plt.errorbar(context_percentages, avg_raw_rkhs, yerr=std_raw_rkhs, fmt='v--', label='RKHS (Raw)', capsize=4, linewidth=2)
# Add labels and title
plt.xlabel('Context Size (% of Total Samples)')
plt.ylabel('Accuracy')
title_str = f'Classification Performance vs. Context Size\n(Mode: {args.test_mode}, Data: {args.data_type})'
plt.title(title_str)
plt.grid(True, alpha=0.3)
plt.legend(loc='lower right')
# Adjust x-axis to show percentages
plt.xticks(context_percentages)
# Save the figure
plt.tight_layout()
fig_path = os.path.join(specific_dir, f"{base_filename}_all_methods.png")
plt.savefig(fig_path, dpi=300)
print(f"Figure saved to {fig_path}")
# Create a second plot: Just PE methods vs Raw methods
plt.figure(figsize=(10, 6))
# Group PE and Raw methods
plt.errorbar(context_percentages, avg_lr, yerr=std_lr, fmt='s-', label='LR (PE)', capsize=4, linewidth=2, color='blue')
plt.errorbar(context_percentages, avg_rkhs, yerr=std_rkhs, fmt='^-', label='RKHS (PE)', capsize=4, linewidth=2, color='green')
plt.errorbar(context_percentages, avg_raw_lr, yerr=std_raw_lr, fmt='s--', label='LR (Raw)', capsize=4, linewidth=2, color='blue', alpha=0.5)
plt.errorbar(context_percentages, avg_raw_rkhs, yerr=std_raw_rkhs, fmt='^--', label='RKHS (Raw)', capsize=4, linewidth=2, color='green', alpha=0.5)
# Add labels and title
plt.xlabel('Context Size (% of Total Samples)')
plt.ylabel('Accuracy')
title_str = f'PE Features vs. Raw Features Performance\n(Mode: {args.test_mode}, Data: {args.data_type})'
plt.title(title_str)
plt.grid(True, alpha=0.3)
plt.legend(loc='lower right')
# Adjust x-axis to show percentages
plt.xticks(context_percentages)
# Save the figure
plt.tight_layout()
fig_path = os.path.join(specific_dir, f"{base_filename}_pe_vs_raw.png")
plt.savefig(fig_path, dpi=300)
print(f"Figure saved to {fig_path}")
# Create a third plot: ICL vs best traditional method
plt.figure(figsize=(10, 6))
import matplotlib.pyplot as plt
import numpy as np
import os
import datetime
import json
def plot_individual_accuracies(args, results, n_samples=100, figure_dir='../figures'):
"""
Plot individual accuracy metrics across different context sizes.
Args:
args: Command line arguments containing test_mode, data_type, etc.
results: Dictionary containing the test results for each context size
n_samples: Total number of samples per graph
figure_dir: Directory to save the figures
"""
# Create timestamp for unique filenames
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
# Create directory structure based on test_mode and data_type
specific_dir = os.path.join(figure_dir, f"test_mode_{args.test_mode}", f"data_{args.data_type}", "individual_plots")
os.makedirs(specific_dir, exist_ok=True)
# Extract context sizes and convert to percentages
context_sizes = list(results.keys())
context_percentages = [ctx_size / n_samples * 100 for ctx_size in context_sizes]
# Extract average accuracies and standard deviations for each method
avg_icl = [sum(results[ctx]['icl_accs']) / len(results[ctx]['icl_accs']) for ctx in context_sizes]
avg_lr = [sum(results[ctx]['lr_accs']) / len(results[ctx]['lr_accs']) for ctx in context_sizes]
avg_rkhs = [sum(results[ctx]['rkhs_accs']) / len(results[ctx]['rkhs_accs']) for ctx in context_sizes]
avg_raw_lr = [sum(results[ctx]['raw_lr_accs']) / len(results[ctx]['raw_lr_accs']) for ctx in context_sizes]
avg_raw_rkhs = [sum(results[ctx]['raw_rkhs_accs']) / len(results[ctx]['raw_rkhs_accs']) for ctx in context_sizes]
std_icl = [np.std(results[ctx]['icl_accs']) for ctx in context_sizes]
std_lr = [np.std(results[ctx]['lr_accs']) for ctx in context_sizes]
std_rkhs = [np.std(results[ctx]['rkhs_accs']) for ctx in context_sizes]
std_raw_lr = [np.std(results[ctx]['raw_lr_accs']) for ctx in context_sizes]
std_raw_rkhs = [np.std(results[ctx]['raw_rkhs_accs']) for ctx in context_sizes]
# Define metrics to plot individually
metrics = [
{'name': 'ICL', 'avg': avg_icl, 'std': std_icl, 'color': 'red', 'marker': 'o'},
{'name': 'LR (PE)', 'avg': avg_lr, 'std': std_lr, 'color': 'blue', 'marker': 's'},
{'name': 'RKHS (PE)', 'avg': avg_rkhs, 'std': std_rkhs, 'color': 'green', 'marker': '^'},
{'name': 'LR (Raw)', 'avg': avg_raw_lr, 'std': std_raw_lr, 'color': 'purple', 'marker': 'd'},
{'name': 'RKHS (Raw)', 'avg': avg_raw_rkhs, 'std': std_raw_rkhs, 'color': 'orange', 'marker': 'v'}
]
# Plot each metric individually
for metric in metrics:
plt.figure(figsize=(8, 5))
# Plot with error bars
plt.errorbar(
context_percentages,
metric['avg'],
yerr=metric['std'],
fmt=f"{metric['marker']}-",
label=metric['name'],
capsize=4,
linewidth=2,
color=metric['color']
)
# Add labels and title
plt.xlabel('Context Size (% of Total Samples)')
plt.ylabel('Accuracy')
title_str = f"{metric['name']} Accuracy vs. Context Size\n(Mode: {args.test_mode}, Data: {args.data_type})"
plt.title(title_str)
plt.grid(True, alpha=0.3)
# Generate filename
safe_name = metric['name'].replace(' ', '_').replace('(', '').replace(')', '')
base_filename = f"mode_{args.test_mode}_data_{args.data_type}_samples_{n_samples}_{timestamp}"
filename = f"{base_filename}_{safe_name}.png"
# Adjust x-axis to show percentages
plt.xticks(context_percentages)
# Set y-axis range from 0.5 to 1.0 for better comparison
plt.ylim([0.5, 1.0])
# Add exact values as text annotations
for i, (x, y, std) in enumerate(zip(context_percentages, metric['avg'], metric['std'])):
plt.annotate(
f"{y:.3f}±{std:.3f}",
xy=(x, y),
xytext=(0, 10),
textcoords='offset points',
ha='center',
fontsize=8,
bbox=dict(boxstyle='round,pad=0.3', fc='white', alpha=0.7)
)
# Save the figure
plt.tight_layout()
fig_path = os.path.join(specific_dir, filename)
plt.savefig(fig_path, dpi=300)
print(f"Individual {metric['name']} plot saved to {fig_path}")
plt.close()
# Create a tabular summary and save as CSV
import pandas as pd
# Create DataFrame
summary_data = {
'Context_Size': context_sizes,
'Context_Percentage': context_percentages,
'ICL_Mean': avg_icl,
'ICL_Std': std_icl,
'LR_PE_Mean': avg_lr,
'LR_PE_Std': std_lr,
'RKHS_PE_Mean': avg_rkhs,
'RKHS_PE_Std': std_rkhs,
'LR_Raw_Mean': avg_raw_lr,
'LR_Raw_Std': std_raw_lr,
'RKHS_Raw_Mean': avg_raw_rkhs,
'RKHS_Raw_Std': std_raw_rkhs
}
df = pd.DataFrame(summary_data)
# Save as CSV
csv_path = os.path.join(specific_dir, f"{base_filename}_summary.csv")
df.to_csv(csv_path, index=False)
print(f"Summary data saved to {csv_path}")
# Also generate a formatted table as text
text_table = "Context Size | ICL | LR (PE) | RKHS (PE) | LR (Raw) | RKHS (Raw)\n"
text_table += "------------|-----|---------|-----------|----------|------------\n"
for i, ctx in enumerate(context_sizes):
text_table += f"{ctx:^12} | {avg_icl[i]:.3f}±{std_icl[i]:.3f} | {avg_lr[i]:.3f}±{std_lr[i]:.3f} | "
text_table += f"{avg_rkhs[i]:.3f}±{std_rkhs[i]:.3f} | {avg_raw_lr[i]:.3f}±{std_raw_lr[i]:.3f} | "
text_table += f"{avg_raw_rkhs[i]:.3f}±{std_raw_rkhs[i]:.3f}\n"
# Save table as txt
txt_path = os.path.join(specific_dir, f"{base_filename}_table.txt")
with open(txt_path, 'w') as f:
f.write(text_table)
print(f"Formatted table saved to {txt_path}")
return specific_dir |