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 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
| import os import json import math import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader, Dataset, Subset from torchvision import models, transforms from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.metrics import mean_absolute_error, r2_score, mean_squared_error import matplotlib.pyplot as plt import seaborn as sns from PIL import Image from tqdm import tqdm
sns.set_theme(style="whitegrid", font_scale=0.9) plt.rcParams['font.sans-serif'] = ['DejaVu Sans'] plt.rcParams['axes.unicode_minus'] = False
def get_best_device(): """Select the best available device: CUDA > MPS (Apple Silicon) > CPU.""" try: if torch.cuda.is_available(): return 'cuda' except Exception: pass try: if hasattr(torch.backends, 'mps') and torch.backends.mps.is_available(): return 'mps' except Exception: pass return 'cpu'
class HyperspectralDataset(Dataset): def __init__(self, root_folder, metadata_file='new_metadata.csv', transform=None, target_size=(256, 256), scaler=None, feature_scaler=None, target_channels=None): self.root_folder = os.path.normpath(root_folder) self.transform = transform self.target_size = target_size self.target_channels = target_channels self.file_list = [] self.labels = [] self.raw_values = []
metadata_path = os.path.join(self.root_folder, metadata_file) if not os.path.exists(metadata_path): raise FileNotFoundError(f"Metadata file {metadata_path} not found")
metadata = pd.read_csv( metadata_path, dtype={'toxin_value': float, 'Value_Raw': float}, encoding='utf-8-sig' ) valid_metadata = metadata[metadata['toxin_value'] <= 20] print(f"Found {len(valid_metadata)} valid samples (toxin_value ≤ 20)")
invalid_count = len(metadata) - len(valid_metadata) if invalid_count > 0: print(f"⚠️ Warning: Filtered {invalid_count} abnormal samples (toxin_value > 20)") has_npy_col = 'npy_filename' in valid_metadata.columns for idx, row in valid_metadata.iterrows(): try: if has_npy_col and isinstance(row['npy_filename'], str) and len(row['npy_filename'].strip()) > 0: rel_path = row['npy_filename'].strip() else: rel_path = str(row['filename']).strip() if os.path.isabs(rel_path): file_path = os.path.normpath(rel_path) else: file_path = os.path.normpath(os.path.join(self.root_folder, rel_path)) if not os.path.isfile(file_path): print(f"Warning: File {file_path} not found, skipping") continue toxin_value = float(row['toxin_value']) raw_value = float(row['Value_Raw']) self.file_list.append(file_path) self.labels.append(toxin_value) self.raw_values.append(raw_value) except Exception as e: print(f"Error processing file {file_path}: {e}") continue
if not self.file_list: raise RuntimeError("No valid data found")
print(f"Successfully loaded {len(self.file_list)} samples") self.labels = np.array(self.labels).reshape(-1, 1) self.raw_values = np.array(self.raw_values).reshape(-1, 1) if scaler: self.labels = scaler.transform(self.labels) self.labels = self.labels.flatten() if feature_scaler: self.raw_values = feature_scaler.transform(self.raw_values) self.raw_values = self.raw_values.flatten()
if self.file_list: sample_data = np.load(self.file_list[0]) if sample_data.shape[:2] != self.target_size: print(f"⚠️ Warning: Input size {sample_data.shape[:2]} does not match target size {self.target_size}, resizing automatically")
def __len__(self): return len(self.file_list)
def __getitem__(self, idx): file_path = self.file_list[idx] data = None try: try: data = np.load(file_path) except ValueError as ve: if "mmap length is greater than file size" in str(ve) or "cannot reshape" in str(ve): print(f"Warning: {file_path} has shape mismatch, attempting manual load") with open(file_path, 'rb') as f: version = np.lib.format.read_magic(f) shape, fortran_order, dtype = np.lib.format.read_array_header_1_0(f) remaining_data = f.read() expected_bytes = np.prod(shape) * np.dtype(dtype).itemsize actual_bytes = len(remaining_data) print(f"Header shape: {shape}, expected {expected_bytes} bytes, got {actual_bytes} bytes") if actual_bytes > 0: elements = actual_bytes // np.dtype(dtype).itemsize flat_data = np.frombuffer(remaining_data[:elements * np.dtype(dtype).itemsize], dtype=dtype) if len(shape) == 3: h_expected, w_expected, c_expected = shape actual_h = elements // (w_expected * c_expected) if actual_h * w_expected * c_expected == elements: print(f"Reshaping to ({actual_h}, {w_expected}, {c_expected}) instead of {shape}") data = flat_data.reshape(actual_h, w_expected, c_expected) else: for c in [300, 600, 900]: for w in [960, 957, 950]: h = elements // (w * c) if h * w * c == elements and h > 0: print(f"Reshaping to ({h}, {w}, {c})") data = flat_data.reshape(h, w, c) break if data is not None: break if data is None and elements >= 256 * 256: sqrt_elem = int(np.sqrt(elements)) while sqrt_elem > 0 and elements % sqrt_elem != 0: sqrt_elem -= 1 if sqrt_elem > 0: height = sqrt_elem width = elements // sqrt_elem data = flat_data[:height*width].reshape(height, width, 1) else: side = int(np.sqrt(elements)) data = flat_data[:side*side].reshape(side, side, 1) elif data is None: data = np.zeros((64, 64, 1), dtype=np.float32) else: raise ValueError("No data to load") else: raise ve if data.ndim == 1: total_size = data.size for channels in [300, 600, 900, 1200]: spatial_size = total_size // channels spatial_dim = int(np.sqrt(spatial_size)) if spatial_dim * spatial_dim * channels == total_size: data = data.reshape(spatial_dim, spatial_dim, channels) break else: spatial_dim = int(np.sqrt(total_size)) if spatial_dim * spatial_dim == total_size: data = data.reshape(spatial_dim, spatial_dim, 1) else: target_size = min(256, spatial_dim) data = data[:target_size*target_size].reshape(target_size, target_size, 1) elif data.ndim == 2: data = data[:, :, np.newaxis] data = self.resize_data(data) data = torch.tensor(data, dtype=torch.float32).permute(2, 0, 1).contiguous() if self.target_channels is not None: c, h, w = data.shape if c > self.target_channels: data = data[:self.target_channels, :, :].contiguous() elif c < self.target_channels: pad = torch.zeros(self.target_channels - c, h, w, dtype=data.dtype) data = torch.cat([data, pad], dim=0).contiguous() if self.transform: data = self.transform(data) label = torch.tensor(self.labels[idx], dtype=torch.float32) raw_value = torch.tensor(self.raw_values[idx], dtype=torch.float32) return data, label, raw_value except Exception as e: print(f"Error loading {file_path}: {e}") if data is not None: print(f"Array shape: {data.shape}, size: {data.size}") else: print("Failed to load array") dummy_data = torch.zeros(self.target_channels or 300, *self.target_size, dtype=torch.float32) dummy_label = torch.tensor(0.0, dtype=torch.float32) dummy_raw = torch.tensor(0.0, dtype=torch.float32) return dummy_data, dummy_label, dummy_raw
def resize_data(self, data): """Resize images using PyTorch's efficient interpolation""" if data.ndim == 2: data = data[:, :, np.newaxis] data_tensor = torch.tensor(data, dtype=torch.float32).permute(2, 0, 1) resized = F.interpolate( data_tensor.unsqueeze(0), size=self.target_size, mode='bilinear', align_corners=False ) return resized.squeeze(0).permute(1, 2, 0).contiguous().cpu().numpy().copy()
def compute_or_load_stats(dataset, cache_path='stats.json', label_scaler=None): """Compute or load statistics including normalization parameters for targets""" if os.path.exists(cache_path): with open(cache_path, 'r') as f: stats = json.load(f) print(f"Loaded statistics from {cache_path}") has_toxin_params = 'toxin_min' in stats and 'toxin_max' in stats if has_toxin_params: print("Cache contains toxin normalization parameters") return ( stats['mean'], stats['std'], stats['toxin_min'], stats['toxin_max'] ) else: print("⚠️ Warning: Cache does not contain toxin normalization parameters, will recompute statistics") print("Computing dataset statistics (mean and std)... This may take some time") loader = DataLoader(dataset, batch_size=16, shuffle=False, num_workers=0, pin_memory=False) try: channels = dataset[0][0].shape[0] except IndexError: raise RuntimeError("Dataset is empty, cannot compute statistics")
total = torch.zeros(channels) total_sq = torch.zeros(channels) num_pixels = 0
for data, _, _ in tqdm(loader, desc="Computing statistics"): data = data.view(data.size(0), channels, -1) total += data.sum(dim=[0, 2]) total_sq += (data ** 2).sum(dim=[0, 2]) num_pixels += data.shape[0] * data.shape[2]
mean = (total / num_pixels).tolist() std = ((total_sq / num_pixels - torch.tensor(mean) ** 2) ** 0.5).tolist()
toxin_min = float(label_scaler.data_min_[0]) if label_scaler else 0.0 toxin_max = float(label_scaler.data_max_[0]) if label_scaler else 1.0
stats = { 'mean': mean, 'std': std, 'toxin_min': toxin_min, 'toxin_max': toxin_max }
try: with open(cache_path, 'w') as f: json.dump(stats, f) print(f"Statistics computed and saved to {cache_path}") except OSError as e: if e.errno == 28: print(f"Warning: No space left on device, skipping stats cache. Stats computed successfully.") else: print(f"Warning: Failed to save stats cache: {e}") return mean, std, toxin_min, toxin_max
def _infer_common_channels(npy_paths, sample_limit=32): """Infer a common channel count across a subset of files (min channels).""" chans = [] for p in npy_paths[:sample_limit]: try: arr = np.load(p, mmap_mode='r') if arr.ndim == 1: total_size = arr.size for channels in [300, 600, 900, 1200]: spatial_size = total_size // channels spatial_dim = int(np.sqrt(spatial_size)) if spatial_dim * spatial_dim * channels == total_size: chans.append(channels) break else: spatial_dim = int(np.sqrt(total_size)) if spatial_dim * spatial_dim == total_size: chans.append(1) elif arr.ndim == 2: chans.append(1) else: chans.append(arr.shape[2]) except Exception as e: print(f"Warning: Failed to process {p}: {e}") continue if not chans: return None common_channels = min(chans) print(f"Detected channels: {chans[:10]}... (first 10), using min: {common_channels}") return int(common_channels)
def preprocess_data(data_folder, batch_size=16, target_size=(256, 256)): metadata_path = os.path.join(data_folder, 'new_metadata.csv') if not os.path.exists(metadata_path): raise FileNotFoundError(f"Metadata file {metadata_path} not found") metadata = pd.read_csv(metadata_path, encoding='utf-8-sig') required_base = ['toxin_value', 'Value_Raw'] for col in required_base: if col not in metadata.columns: raise ValueError(f"Required column '{col}' not found in metadata.csv") if ('npy_filename' not in metadata.columns) and ('filename' not in metadata.columns): raise ValueError("metadata.csv must contain 'npy_filename' or 'filename'")
toxin_values = metadata['toxin_value'].values.reshape(-1, 1) label_scaler = MinMaxScaler(feature_range=(0, 1)) label_scaler.fit(toxin_values) print(f"Toxin value normalization parameters: min={label_scaler.data_min_[0]}, max={label_scaler.data_max_[0]}")
raw_values = metadata['Value_Raw'].values.reshape(-1, 1) feature_scaler = StandardScaler().fit(raw_values) print(f"Value_Raw normalization: mean={feature_scaler.mean_[0]}, std={feature_scaler.scale_[0]}")
meta = pd.read_csv(metadata_path, encoding='utf-8-sig') npy_col = 'npy_filename' if 'npy_filename' in meta.columns else 'filename' npy_paths = [] for _, r in meta.iterrows(): p = str(r[npy_col]).strip() if not os.path.isabs(p): p = os.path.join(data_folder, p) if os.path.isfile(p): npy_paths.append(os.path.normpath(p)) target_channels = _infer_common_channels(npy_paths) if target_channels is None: raise RuntimeError("Failed to infer common channel count from npy files") print(f"Using common spectral channels: {target_channels}")
full_dataset_for_stats = HyperspectralDataset( data_folder, target_size=target_size, scaler=None, feature_scaler=None, target_channels=target_channels ) mean, std, toxin_min, toxin_max = compute_or_load_stats( full_dataset_for_stats, os.path.join(data_folder, 'stats.json'), label_scaler=label_scaler ) print(f"Toxin value normalization parameters saved: min={toxin_min}, max={toxin_max}")
train_transform = transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.RandomVerticalFlip(), transforms.RandomRotation(degrees=15), transforms.RandomAffine(degrees=0, translate=(0.05, 0.05)), transforms.Normalize(mean, std) ]) test_transform = transforms.Compose([ transforms.Normalize(mean, std) ])
full_dataset_train = HyperspectralDataset( data_folder, target_size=target_size, transform=train_transform, scaler=label_scaler, feature_scaler=feature_scaler, target_channels=target_channels ) full_dataset_test = HyperspectralDataset( data_folder, target_size=target_size, transform=test_transform, scaler=label_scaler, feature_scaler=feature_scaler, target_channels=target_channels )
train_idx, test_idx = train_test_split( np.arange(len(full_dataset_train)), test_size=0.2, random_state=24 ) train_set = Subset(full_dataset_train, train_idx) test_set = Subset(full_dataset_test, test_idx)
nw = min(4, (os.cpu_count() or 1)) train_loader = DataLoader( train_set, batch_size=batch_size, shuffle=True, num_workers=nw, pin_memory=True, persistent_workers=(nw > 0) ) test_loader = DataLoader( test_set, batch_size=batch_size, shuffle=False, num_workers=nw, pin_memory=True, persistent_workers=(nw > 0) )
return train_loader, test_loader, label_scaler, feature_scaler
class ChannelAttention(nn.Module): """Channel Attention Module""" def __init__(self, in_channels, reduction_ratio=16): super(ChannelAttention, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.max_pool = nn.AdaptiveMaxPool2d(1) self.fc = nn.Sequential( nn.Linear(in_channels, in_channels // reduction_ratio), nn.ReLU(inplace=True), nn.Linear(in_channels // reduction_ratio, in_channels), nn.Sigmoid() )
def forward(self, x): avg_out = self.fc(self.avg_pool(x).view(x.size(0), -1)) max_out = self.fc(self.max_pool(x).view(x.size(0), -1)) out = avg_out + max_out return out.view(x.size(0), x.size(1), 1, 1)
class SpatialAttention(nn.Module): """Spatial Attention Module""" def __init__(self, kernel_size=7): super(SpatialAttention, self).__init__() assert kernel_size in (3, 7), "kernel size must be 3 or 7" padding = 3 if kernel_size == 7 else 1 self.conv = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False) self.sigmoid = nn.Sigmoid()
def forward(self, x): avg_out = torch.mean(x, dim=1, keepdim=True) max_out, _ = torch.max(x, dim=1, keepdim=True) x = torch.cat([avg_out, max_out], dim=1) x = self.conv(x) return self.sigmoid(x)
class CBAM(nn.Module): """CBAM Module: Channel Attention + Spatial Attention""" def __init__(self, in_channels, reduction_ratio=16, kernel_size=7): super(CBAM, self).__init__() self.channel_att = ChannelAttention(in_channels, reduction_ratio) self.spatial_att = SpatialAttention(kernel_size)
def forward(self, x): x = x * self.channel_att(x) x = x * self.spatial_att(x) return x
class PositionalEncoding(nn.Module): """Positional Encoding for enhanced spectral information""" def __init__(self, d_model, max_len=500): super().__init__() pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0) self.register_buffer('pe', pe) def forward(self, x): seq_len = x.size(1) pos_emb = self.pe[:, :seq_len, :] return x + pos_emb
class GatedLinear(nn.Module): """Gated Linear Layer""" def __init__(self, in_features, out_features): super().__init__() self.linear = nn.Linear(in_features, out_features) self.gate = nn.Linear(in_features, out_features) nn.init.xavier_uniform_(self.linear.weight) nn.init.xavier_uniform_(self.gate.weight) nn.init.zeros_(self.linear.bias) nn.init.zeros_(self.gate.bias) def forward(self, x): return self.linear(x) * torch.sigmoid(self.gate(x))
class HyperspectralModel(nn.Module): def __init__(self, input_channels): super(HyperspectralModel, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d(input_channels, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) ) self.cbam1 = CBAM(64) self.down1 = nn.Sequential( nn.Conv2d(64, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2), CBAM(64) ) self.down2 = nn.Sequential( nn.Conv2d(64, 128, kernel_size=3, padding=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.Conv2d(128, 128, kernel_size=3, padding=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.MaxPool2d(2), CBAM(128) ) self.final_conv = nn.Sequential( nn.Conv2d(128, 256, kernel_size=3, padding=1), nn.BatchNorm2d(256), nn.ReLU(inplace=True), CBAM(256), nn.AdaptiveAvgPool2d(1) ) self.fc = nn.Sequential( nn.Linear(256 + 1, 512), nn.ReLU(inplace=True), nn.Dropout(0.4), nn.Linear(512, 256), nn.ReLU(inplace=True), nn.Dropout(0.3), nn.Linear(256, 128), nn.ReLU(inplace=True), nn.Dropout(0.2), nn.Linear(128, 1) ) def forward(self, x, feature): x = self.conv1(x) x = self.cbam1(x) x = self.down1(x) x = self.down2(x) img_features = self.final_conv(x).squeeze(-1).squeeze(-1) combined = torch.cat([img_features, feature.unsqueeze(1)], dim=1) return self.fc(combined).flatten() def visualize_attention(self, input_tensor): """Visualize CBAM attention effects (for debugging)""" with torch.no_grad(): activations = {} x1 = self.conv1(input_tensor) x1_att = self.cbam1(x1) activations['conv1'] = x1 activations['cbam1'] = x1_att x2 = self.down1[:-1](x1_att) x2_att = self.down1[-1](x2) activations['down1'] = x2 activations['cbam2'] = x2_att x3 = self.down2[:-1](x2_att) x3_att = self.down2[-1](x3) activations['down2'] = x3 activations['cbam3'] = x3_att x4 = self.final_conv[:-2](x3_att) x4_att = self.final_conv[-2](x4) activations['final_conv'] = x4 activations['cbam4'] = x4_att return activations
def adjust_learning_rate(optimizer, epoch, warmup_epochs, initial_lr, num_epochs): """Custom learning rate scheduler""" if epoch < warmup_epochs: lr = initial_lr * (epoch + 1) / warmup_epochs else: progress = (epoch - warmup_epochs) / (num_epochs - warmup_epochs) lr = 0.5 * initial_lr * (1 + math.cos(math.pi * progress)) for param_group in optimizer.param_groups: param_group['lr'] = lr return lr
def evaluate_regression(model, loader, device='cuda', scaler=None): """Evaluate regression model performance""" model.eval() all_labels, all_preds = [], [] with torch.no_grad(): for inputs, labels, features in loader: inputs = inputs.to(device) features = features.to(device) outputs = model(inputs, features).flatten() all_labels.extend(labels.cpu().numpy()) all_preds.extend(outputs.cpu().numpy()) all_labels = np.array(all_labels) all_preds = np.array(all_preds)
if scaler: all_labels_orig = scaler.inverse_transform(all_labels.reshape(-1, 1)).flatten() all_preds_orig = scaler.inverse_transform(all_preds.reshape(-1, 1)).flatten() else: all_labels_orig = all_labels all_preds_orig = all_preds
mae = mean_absolute_error(all_labels_orig, all_preds_orig) r2 = r2_score(all_labels_orig, all_preds_orig) mse_normalized = np.mean((all_labels - all_preds)**2)
return all_labels_orig, all_preds_orig, mae, r2, mse_normalized
def train_regression_model(model, train_loader, val_loader, scaler, num_epochs=100, device='cpu'): """Train regression model (evaluate every epoch)""" model.to(device) criterion = nn.MSELoss() optimizer = optim.AdamW(model.parameters(), lr=1e-4, weight_decay=1e-5) warmup_epochs = 10 best_val_loss = float('inf') best_val_r2 = -float('inf') patience = 15 trigger_times = 0
train_losses = [] val_losses = [] val_r2s = [] best_predictions = None
print(f"Starting training for {num_epochs} epochs with evaluation every epoch...") for epoch in range(num_epochs): model.train() running_loss = 0.0 current_lr = adjust_learning_rate(optimizer, epoch, warmup_epochs, 1e-4, num_epochs) for inputs, labels, features in tqdm(train_loader, desc=f'Epoch {epoch + 1}/{num_epochs}'): inputs = inputs.to(device) labels = labels.to(device) features = features.to(device) optimizer.zero_grad() outputs = model(inputs, features) loss = criterion(outputs, labels) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=2.0) optimizer.step() running_loss += loss.item() avg_train_loss = running_loss / len(train_loader) train_losses.append(avg_train_loss) model.eval() with torch.no_grad(): val_labels, val_preds = [], [] for val_inputs, val_labels_batch, val_features in val_loader: val_inputs = val_inputs.to(device) val_features = val_features.to(device) val_outputs = model(val_inputs, val_features).flatten() val_labels.extend(val_labels_batch.cpu().numpy()) val_preds.extend(val_outputs.cpu().numpy()) val_labels = np.array(val_labels) val_preds = np.array(val_preds) if scaler: val_labels_orig = scaler.inverse_transform(val_labels.reshape(-1, 1)).flatten() val_preds_orig = scaler.inverse_transform(val_preds.reshape(-1, 1)).flatten() else: val_labels_orig = val_labels val_preds_orig = val_preds
val_mae = mean_absolute_error(val_labels_orig, val_preds_orig) val_r2 = r2_score(val_labels_orig, val_preds_orig) val_loss_normalized = np.mean((val_labels - val_preds)**2) val_losses.append(val_loss_normalized) val_r2s.append(val_r2) r2_improved = (val_r2 - best_val_r2) > 0.001 loss_improved = (best_val_loss - val_loss_normalized) > 0.01 improvement = r2_improved or loss_improved if improvement: best_val_r2 = val_r2 best_val_loss = val_loss_normalized trigger_times = 0 best_predictions = (val_labels_orig, val_preds_orig) save_dict = { 'epoch': epoch, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'loss': best_val_loss, 'r2': best_val_r2, } if hasattr(scaler, 'data_min_') and hasattr(scaler, 'data_max_'): save_dict['toxin_min'] = scaler.data_min_[0] save_dict['toxin_max'] = scaler.data_max_[0] try: torch.save(save_dict, 'best_model.pth') print(f"✔ Validation metrics improved, saving model. R²: {best_val_r2:.4f}, Loss: {val_loss_normalized:.4f} (Epoch {epoch+1})") except OSError as e: if e.errno == 28: print(f"✔ Validation metrics improved but cannot save model (no space). R²: {best_val_r2:.4f}, Loss: {val_loss_normalized:.4f} (Epoch {epoch+1})") else: print(f"✔ Validation metrics improved but failed to save model: {e}. R²: {best_val_r2:.4f}, Loss: {val_loss_normalized:.4f} (Epoch {epoch+1})") else: trigger_times += 1 if trigger_times >= patience: print(f"Early stopping triggered! No improvement for {patience} consecutive epochs.") break print(f"Epoch {epoch + 1}/{num_epochs} | LR: {current_lr:.2e} | " f"Train Loss: {avg_train_loss:.4f} | " f"Val Loss: {val_loss_normalized:.4f} | " f"Val R²: {val_r2:.4f} | " f"Trigger: {trigger_times}/{patience}") if os.path.exists('best_model.pth'): checkpoint = torch.load('best_model.pth') model.load_state_dict(checkpoint['model_state_dict']) print(f"\nTraining complete. Best model at epoch {checkpoint['epoch'] + 1}: " f"R²: {checkpoint['r2']:.4f}, Loss: {checkpoint['loss']:.4f}") if 'toxin_min' in checkpoint and 'toxin_max' in checkpoint: print(f"Toxin min={checkpoint['toxin_min']}, Toxin max={checkpoint['toxin_max']}") else: print("\nTraining complete, but no model saved.") visualize_training(train_losses, val_losses, val_r2s, min(num_epochs, len(val_losses))) return best_predictions
def visualize_training(train_losses, val_losses, val_r2s, num_epochs): """Visualize training progress""" plt.figure(figsize=(12, 8)) epochs = np.arange(1, len(train_losses) + 1) plt.subplot(2, 1, 1) plt.plot(epochs, train_losses, 'b-', label='Train Loss') if val_losses: eval_points = np.linspace(0, num_epochs, len(val_losses), endpoint=False).astype(int) + 1 plt.plot(eval_points, val_losses, 'r-', label='Val Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.title('Training and Validation Loss') plt.legend() plt.grid(True) plt.subplot(2, 1, 2) if val_r2s: plt.plot(eval_points, val_r2s, 'g-', label='Val R²') plt.axhline(y=0, color='k', linestyle='--', alpha=0.5) plt.xlabel('Epoch') plt.ylabel('R² Score') plt.title('Validation R² Score') plt.ylim(-0.5, 1.0) plt.grid(True) plt.tight_layout() plt.savefig('training_metrics.png', dpi=300) plt.show()
def enhanced_visualization(true_values, pred_values): """Enhanced regression result visualization""" plt.figure(figsize=(18, 12)) residuals = pred_values - true_values abs_errors = np.abs(residuals) plt.subplot(2, 2, 1) sns.regplot(x=true_values, y=pred_values, scatter_kws={'alpha':0.4, 'color':'#4B8BBE'}, line_kws={'color':'#FF0000', 'lw':2}, ci=95) mae = mean_absolute_error(true_values, pred_values) r2 = r2_score(true_values, pred_values) rmse = np.sqrt(mean_squared_error(true_values, pred_values)) textstr = '\n'.join(( f'MAE = {mae:.2f}', f'RMSE = {rmse:.2f}', f'R² = {r2:.2f}')) plt.gca().text(0.05, 0.95, textstr, transform=plt.gca().transAxes, fontsize=12, verticalalignment='top', bbox=dict(facecolor='white', alpha=0.8)) plt.plot([min(true_values), max(true_values)], [min(true_values), max(true_values)], 'k--', lw=1, label='Perfect Prediction') plt.xlabel('True Values') plt.ylabel('Predictions') plt.title('True vs Predicted Values') plt.legend() plt.subplot(2, 2, 2) sns.residplot(x=true_values, y=residuals, lowess=True, scatter_kws={'alpha':0.4, 'color':'#4B8BBE'}, line_kws={'color':'#FF0000', 'lw':2}) plt.axhline(y=0, color='k', linestyle='--', lw=1) plt.xlabel('True Values') plt.ylabel('Residuals') plt.title('Residual Analysis') plt.subplot(2, 2, 3) sns.histplot(abs_errors, kde=True, bins=30, color='#4B8BBE', edgecolor='white', linewidth=0.5) plt.axvline(x=mae, color='r', linestyle='--', lw=2, label=f'MAE = {mae:.2f}') plt.xlabel('Absolute Error') plt.ylabel('Count') plt.title('Absolute Error Distribution') plt.legend() plt.subplot(2, 2, 4) plt.scatter(true_values, residuals, alpha=0.5, color='#4B8BBE') plt.axhline(y=0, color='r', linestyle='--', lw=1) plt.xlabel('True Values') plt.ylabel('Prediction Error') plt.title('Prediction Error Distribution') plt.grid(True) plt.tight_layout() plt.savefig('enhanced_regression_analysis.png', dpi=300) plt.show()
def main(): data_folder = "/Volumes/Extreme Pro/001-实验数据-是这个/001-是这个/test/processed_npy" batch_size = 16 num_epochs = 100
print("--- Data Preprocessing ---") train_loader, test_loader, label_scaler, feature_scaler = preprocess_data(data_folder, batch_size) device = get_best_device() print(f"Using device: {device}") try: sample_data, _, _ = next(iter(train_loader)) input_channels = sample_data.shape[1] print(f"Detected input channels: {input_channels}") except StopIteration: print("Train loader is empty. Check data folder and metadata file.") return
print("--- Model Creation ---") model = HyperspectralModel(input_channels) total_params = sum(p.numel() for p in model.parameters()) trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) print(f"Total parameters: {total_params:,} | Trainable parameters: {trainable_params:,}")
print("--- Model Training ---") best_predictions = train_regression_model( model, train_loader, test_loader, label_scaler, num_epochs=num_epochs, device=device )
print("\n--- Final Model Evaluation ---") if os.path.exists('best_model.pth'): checkpoint = torch.load('best_model.pth') model.load_state_dict(checkpoint['model_state_dict']) final_labels_orig, final_preds_orig, final_mae, final_r2, _ = evaluate_regression( model, test_loader, device=device, scaler=label_scaler )
print(f"Final performance on test set:") print(f"MAE (original scale): {final_mae:.4f}") print(f"R² Score (original scale): {final_r2:.4f}") print(f"Best model achieved R²: {checkpoint['r2']:.4f} at epoch {checkpoint['epoch'] + 1}")
enhanced_visualization(final_labels_orig, final_preds_orig) if best_predictions: print("\nVisualizing best predictions...") best_labels, best_preds = best_predictions enhanced_visualization(best_labels, best_preds) else: print("No saved model found, using current model for evaluation") final_labels_orig, final_preds_orig, final_mae, final_r2, _ = evaluate_regression( model, test_loader, device=device, scaler=label_scaler ) print(f"Final performance on test set:") print(f"MAE (original scale): {final_mae:.4f}") print(f"R² Score (original scale): {final_r2:.4f}") enhanced_visualization(final_labels_orig, final_preds_orig)
if __name__ == '__main__': main()
|