| from pathlib import Path |
| import numpy as np |
| import pandas as pd |
| from tqdm import tqdm |
| import librosa |
| import warnings |
| warnings.filterwarnings("ignore") |
|
|
| import torch |
| import torch.nn as nn |
| import torch.optim as optim |
| from torch.utils.data import Dataset, DataLoader |
| from sklearn.model_selection import train_test_split |
| from sklearn.preprocessing import LabelEncoder |
| from sklearn.metrics import f1_score, classification_report, confusion_matrix |
| from joblib import Parallel, delayed |
|
|
| DATA_DIR = Path("output/linguawave") |
| SAMPLE_RATE = 16_000 |
| DURATION = 10 |
| N_SAMPLES = SAMPLE_RATE * DURATION |
| CLASSES = ["id", "ms", "vi", "th", "en", "zh", "ar", "fr"] |
| N_CLASSES = len(CLASSES) |
|
|
| HARD_NEG_LANGS = {"id", "ms"} |
| OVERSAMPLE_FACTOR = 2 |
|
|
| DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| print("Device:", DEVICE) |
|
|
| BRANCH_CONFIGS = [ |
| {"n_fft": 512, "hop_length": 256, "n_mels": 128}, |
| {"n_fft": 1024, "hop_length": 256, "n_mels": 128}, |
| {"n_fft": 2048, "hop_length": 256, "n_mels": 128}, |
| ] |
| TARGET_T = N_SAMPLES // 256 + 1 |
|
|
|
|
| def _compute_mels_one(row_id): |
| """Compute 3-branch mels for one audio file. Returns (3, 128, TARGET_T) float32.""" |
| y, _ = librosa.load(str(DATA_DIR / row_id), sr=SAMPLE_RATE, duration=DURATION) |
| if len(y) < N_SAMPLES: |
| y = np.pad(y, (0, N_SAMPLES - len(y))) |
| else: |
| y = y[:N_SAMPLES] |
| out = [] |
| for cfg in BRANCH_CONFIGS: |
| mel = librosa.feature.melspectrogram( |
| y=y, sr=SAMPLE_RATE, |
| n_mels=cfg["n_mels"], n_fft=cfg["n_fft"], hop_length=cfg["hop_length"] |
| ) |
| log_mel = librosa.power_to_db(mel, ref=np.max).astype(np.float32) |
| log_mel = (log_mel - log_mel.mean()) / (log_mel.std() + 1e-8) |
| if log_mel.shape[1] < TARGET_T: |
| log_mel = np.pad(log_mel, ((0, 0), (0, TARGET_T - log_mel.shape[1]))) |
| else: |
| log_mel = log_mel[:, :TARGET_T] |
| out.append(log_mel) |
| return np.stack(out, axis=0) |
|
|
|
|
| def precompute_mels(df, cache_path): |
| """Compute mels for all rows in df (parallel), save to cache_path as (N,3,128,T).""" |
| cp = Path(cache_path) |
| if cp.exists(): |
| print(f"[cache] Loading {cp.name}") |
| return np.load(cp, mmap_mode='r') |
| print(f"Precomputing mels → {cp.name} ({len(df)} samples, parallel) ...") |
| results = Parallel(n_jobs=-1, prefer="threads")( |
| delayed(_compute_mels_one)(r["id"]) |
| for _, r in tqdm(df.iterrows(), total=len(df)) |
| ) |
| arr = np.stack(results, axis=0) |
| np.save(cp, arr) |
| print(f"[cache] Saved {cp.name} shape={arr.shape}") |
| return np.load(cp, mmap_mode='r') |
|
|
|
|
| class CachedMultiScaleDataset(Dataset): |
| """Loads precomputed (3, 128, T) mel arrays; augmentation via time-roll on mel.""" |
| def __init__(self, df, mels_cache, label_encoder, augment=False): |
| self.df = df.reset_index(drop=True) |
| self.mels = mels_cache |
| self.le = label_encoder |
| self.augment = augment |
| self.has_labels = "label" in df.columns |
|
|
| def __len__(self): |
| return len(self.df) |
|
|
| def __getitem__(self, idx): |
| row = self.df.iloc[idx] |
| |
| mels = self.mels[idx].copy() |
| if self.augment: |
| shift = np.random.randint(-SAMPLE_RATE // 2 // 256, SAMPLE_RATE // 2 // 256) |
| mels = np.roll(mels, shift, axis=-1) |
| mels_tensors = [torch.tensor(mels[b][np.newaxis, :, :]) for b in range(3)] |
| if self.has_labels: |
| label = self.le.transform([row["label"]])[0] |
| return mels_tensors, label |
| return mels_tensors |
|
|
|
|
| class SingleBranchCNN(nn.Module): |
| def __init__(self, out_dim=256): |
| super().__init__() |
| def block(ic, oc): |
| return nn.Sequential( |
| nn.Conv2d(ic, oc, 3, padding=1), nn.BatchNorm2d(oc), nn.ReLU(True), |
| nn.Conv2d(oc, oc, 3, padding=1), nn.BatchNorm2d(oc), nn.ReLU(True), |
| nn.MaxPool2d(2, 2), |
| ) |
| self.net = nn.Sequential( |
| block(1, 32), block(32, 64), block(64, 128), block(128, out_dim), |
| nn.AdaptiveAvgPool2d(1), |
| nn.Flatten(), |
| ) |
|
|
| def forward(self, x): |
| return self.net(x) |
|
|
|
|
| class MultiScaleCNN(nn.Module): |
| def __init__(self, n_classes=N_CLASSES, branch_dim=256): |
| super().__init__() |
| self.branch1 = SingleBranchCNN(branch_dim) |
| self.branch2 = SingleBranchCNN(branch_dim) |
| self.branch3 = SingleBranchCNN(branch_dim) |
| self.head = nn.Sequential( |
| nn.Linear(branch_dim * 3, 256), |
| nn.ReLU(True), |
| nn.Dropout(0.4), |
| nn.Linear(256, n_classes), |
| ) |
|
|
| def forward(self, mels): |
| m1, m2, m3 = mels |
| return self.head(torch.cat([self.branch1(m1), self.branch2(m2), self.branch3(m3)], dim=1)) |
|
|
|
|
| |
| train_df = pd.read_csv(DATA_DIR / "train.csv") |
| test_df = pd.read_csv(DATA_DIR / "test.csv") |
|
|
| le = LabelEncoder() |
| le.fit(CLASSES) |
|
|
| tr_df, val_df = train_test_split( |
| train_df, test_size=0.15, random_state=42, stratify=train_df["label"] |
| ) |
|
|
| hard_rows = tr_df[tr_df["label"].isin(HARD_NEG_LANGS)] |
| tr_df_aug = pd.concat( |
| [tr_df] + [hard_rows] * (OVERSAMPLE_FACTOR - 1), |
| ignore_index=True |
| ).sample(frac=1, random_state=42).reset_index(drop=True) |
|
|
| print(f"Train (augmented): {len(tr_df_aug)} Val: {len(val_df)} Test: {len(test_df)}") |
|
|
| |
| Path("cache").mkdir(exist_ok=True) |
| full_train_mels = precompute_mels(train_df.reset_index(drop=True), "cache/lw_05_train_mels.npy") |
| test_mels = precompute_mels(test_df.reset_index(drop=True), "cache/lw_05_test_mels.npy") |
|
|
| |
| train_id_to_idx = {row["id"]: i for i, row in train_df.reset_index(drop=True).iterrows()} |
|
|
| tr_aug_mels = np.stack([full_train_mels[train_id_to_idx[r["id"]]] for _, r in tr_df_aug.iterrows()]) |
| val_mels = np.stack([full_train_mels[train_id_to_idx[r["id"]]] for _, r in val_df.iterrows()]) |
|
|
| print("Building augmented train mel array ...") |
| print(f" tr_aug shape: {tr_aug_mels.shape}") |
|
|
| |
| tr_df_aug_reset = tr_df_aug.reset_index(drop=True) |
| val_df_reset = val_df.reset_index(drop=True) |
|
|
|
|
| def collate_fn(batch): |
| mels_list = [item[0] for item in batch] |
| labels = torch.tensor([item[1] for item in batch]) |
| stacked = [torch.stack([m[b] for m in mels_list]) for b in range(3)] |
| return stacked, labels |
|
|
| def collate_fn_test(batch): |
| stacked = [torch.stack([item[b] for item in batch]) for b in range(3)] |
| return stacked |
|
|
| BATCH = 64 |
| train_ds = CachedMultiScaleDataset(tr_df_aug_reset, tr_aug_mels, le, augment=True) |
| val_ds = CachedMultiScaleDataset(val_df_reset, val_mels, le, augment=False) |
| test_ds = CachedMultiScaleDataset(test_df.reset_index(drop=True), test_mels, le, augment=False) |
|
|
| train_loader = DataLoader(train_ds, batch_size=BATCH, shuffle=True, |
| num_workers=4, pin_memory=True, collate_fn=collate_fn) |
| val_loader = DataLoader(val_ds, batch_size=BATCH, shuffle=False, |
| num_workers=4, pin_memory=True, collate_fn=collate_fn) |
| test_loader = DataLoader(test_ds, batch_size=BATCH, shuffle=False, |
| num_workers=4, pin_memory=True, collate_fn=collate_fn_test) |
|
|
| print(f"Train batches: {len(train_loader)} Val batches: {len(val_loader)}") |
|
|
| |
| model = MultiScaleCNN().to(DEVICE) |
| print(f"Trainable params: {sum(p.numel() for p in model.parameters() if p.requires_grad):,}") |
|
|
| from sklearn.utils.class_weight import compute_class_weight |
| class_weights = compute_class_weight("balanced", classes=le.classes_, y=tr_df["label"].to_numpy()) |
| for lang in HARD_NEG_LANGS: |
| class_weights[le.transform([lang])[0]] /= OVERSAMPLE_FACTOR |
| class_weights_tensor = torch.tensor(class_weights, dtype=torch.float).to(DEVICE) |
|
|
| criterion = nn.CrossEntropyLoss(weight=class_weights_tensor) |
| EPOCHS = 5 |
| optimizer = optim.AdamW(model.parameters(), lr=5e-4, weight_decay=1e-4) |
| scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS) |
|
|
| best_f1 = 0.0 |
| best_weights = None |
|
|
| for epoch in range(1, EPOCHS + 1): |
| model.train() |
| running_loss = 0.0 |
| for mels, y_batch in tqdm(train_loader, desc=f"Epoch {epoch:02d} train", leave=False): |
| mels = [m.to(DEVICE) for m in mels] |
| y_batch = y_batch.to(DEVICE) |
| optimizer.zero_grad() |
| loss = criterion(model(mels), y_batch) |
| loss.backward() |
| nn.utils.clip_grad_norm_(model.parameters(), 1.0) |
| optimizer.step() |
| running_loss += loss.item() * y_batch.size(0) |
|
|
| model.eval() |
| all_preds, all_labels = [], [] |
| with torch.no_grad(): |
| for mels, y_batch in val_loader: |
| mels = [m.to(DEVICE) for m in mels] |
| all_preds.extend(model(mels).argmax(dim=1).cpu().numpy()) |
| all_labels.extend(y_batch.numpy()) |
|
|
| val_f1 = f1_score(all_labels, all_preds, average="macro") |
| scheduler.step() |
| if val_f1 > best_f1: |
| best_f1 = val_f1 |
| best_weights = {k: v.clone() for k, v in model.state_dict().items()} |
| print(f"Epoch {epoch:02d}/{EPOCHS} val_F1={val_f1:.4f} best={best_f1:.4f}") |
|
|
| print(f"\nBest validation Macro F1: {best_f1:.4f}") |
|
|
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| import seaborn as sns |
|
|
| model.load_state_dict(best_weights) |
| model.eval() |
| all_preds, all_labels = [], [] |
| with torch.no_grad(): |
| for mels, y_batch in val_loader: |
| mels = [m.to(DEVICE) for m in mels] |
| all_preds.extend(model(mels).argmax(dim=1).cpu().numpy()) |
| all_labels.extend(y_batch.numpy()) |
|
|
| print(classification_report(all_labels, all_preds, target_names=le.classes_)) |
|
|
| cm = confusion_matrix(all_labels, all_preds) |
| id_idx = le.transform(["id"])[0]; ms_idx = le.transform(["ms"])[0] |
| print(f"id→ms confusions: {cm[id_idx, ms_idx]} | ms→id confusions: {cm[ms_idx, id_idx]}") |
|
|
| Path("submissions").mkdir(exist_ok=True) |
| torch.save(best_weights, "submissions/model_approach5_multiscale.pt") |
|
|
| all_probs = [] |
| with torch.no_grad(): |
| for mels in tqdm(test_loader, desc="Test inference"): |
| mels = [m.to(DEVICE) for m in mels] |
| all_probs.append(torch.softmax(model(mels), dim=1).cpu().numpy()) |
|
|
| test_probs = np.vstack(all_probs) |
| np.save("submissions/probs_approach5_multiscale.npy", test_probs) |
| test_preds = le.inverse_transform(test_probs.argmax(axis=1)) |
| sub = pd.DataFrame({"id": test_df["id"], "label": test_preds}) |
| sub.to_csv("submissions/sub_approach5_multiscale.csv", index=False) |
| print("Saved submissions/sub_approach5_multiscale.csv") |
|
|
| probs4_path = Path("submissions/probs_approach4_cnn_mel.npy") |
| probs5_path = Path("submissions/probs_approach5_multiscale.npy") |
| if probs4_path.exists() and probs5_path.exists(): |
| ensemble_probs = (np.load(probs4_path) + np.load(probs5_path)) / 2 |
| ensemble_preds = le.inverse_transform(ensemble_probs.argmax(axis=1)) |
| pd.DataFrame({"id": test_df["id"], "label": ensemble_preds}).to_csv( |
| "submissions/sub_ensemble_4_5.csv", index=False) |
| print("Ensemble submission saved: submissions/sub_ensemble_4_5.csv") |
| else: |
| print("Run notebook 04 first to generate probs_approach4_cnn_mel.npy") |
|
|