| from pathlib import Path |
| import numpy as np |
| import pandas as pd |
| import librosa |
| import torch |
| import torch.nn as nn |
| from torch.utils.data import Dataset, DataLoader |
| from sklearn.model_selection import train_test_split |
| from sklearn.metrics import roc_auc_score, confusion_matrix, ConfusionMatrixDisplay |
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| import warnings |
| warnings.filterwarnings("ignore") |
|
|
| DATA_DIR = Path("output/voiceguard") |
| AUDIO_DIR = DATA_DIR |
| SR = 16_000 |
| DURATION = 4 |
| N_SAMPLES = SR * DURATION |
|
|
| N_MELS = 80 |
| N_FFT = 512 |
| HOP = 128 |
| BATCH = 128 |
| EPOCHS = 50 |
| LR = 1e-3 |
| DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| print("Device:", DEVICE) |
|
|
| train_df = pd.read_csv(DATA_DIR / "train.csv") |
| train_df["label"] = (train_df["label"] == "fake").astype(int) |
| test_df = pd.read_csv(DATA_DIR / "test.csv") |
| print("Train:", train_df.shape, " Test:", test_df.shape) |
|
|
|
|
| def load_mel(path, sr=SR, n_samples=N_SAMPLES, n_mels=N_MELS, |
| n_fft=N_FFT, hop=HOP): |
| y, _ = librosa.load(path, sr=sr, mono=True) |
| if len(y) < n_samples: |
| y = np.pad(y, (0, n_samples - len(y))) |
| y = y[:n_samples] |
| mel = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=n_mels, |
| n_fft=n_fft, hop_length=hop) |
| mel_db = librosa.power_to_db(mel, ref=np.max) |
| |
| mel_db = (mel_db - mel_db.mean()) / (mel_db.std() + 1e-8) |
| return mel_db.astype(np.float32) |
|
|
| |
| _sample = load_mel(AUDIO_DIR / train_df.iloc[0]["id"]) |
| print("Mel shape:", _sample.shape) |
|
|
|
|
| class MelDataset(Dataset): |
| def __init__(self, df, audio_dir, has_labels=True): |
| self.df = df.reset_index(drop=True) |
| self.audio_dir = audio_dir |
| self.has_labels = has_labels |
|
|
| def __len__(self): |
| return len(self.df) |
|
|
| def __getitem__(self, idx): |
| row = self.df.iloc[idx] |
| mel = load_mel(self.audio_dir / row["id"]) |
| mel = torch.from_numpy(mel).unsqueeze(0) |
| if self.has_labels: |
| return mel, torch.tensor(row["label"], dtype=torch.float32) |
| return mel, row["id"] |
|
|
|
|
| class MelCNN(nn.Module): |
| def __init__(self): |
| super().__init__() |
| self.features = nn.Sequential( |
| nn.Conv2d(1, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), |
| nn.MaxPool2d(2), |
| nn.Conv2d(64, 128, kernel_size=3, padding=1), nn.BatchNorm2d(128), nn.ReLU(), |
| nn.MaxPool2d(2), |
| nn.Conv2d(128, 256, kernel_size=3, padding=1), nn.BatchNorm2d(256), nn.ReLU(), |
| nn.AdaptiveAvgPool2d((1, 1)), |
| ) |
| self.head = nn.Linear(256, 1) |
|
|
| def forward(self, x): |
| x = self.features(x) |
| x = x.view(x.size(0), -1) |
| return self.head(x).squeeze(1) |
|
|
|
|
| tr_df, val_df = train_test_split(train_df, test_size=0.2, |
| random_state=42, stratify=train_df["label"]) |
|
|
| tr_loader = DataLoader(MelDataset(tr_df, AUDIO_DIR), batch_size=BATCH, shuffle=True, num_workers=8, pin_memory=True) |
| val_loader = DataLoader(MelDataset(val_df, AUDIO_DIR), batch_size=BATCH, shuffle=False, num_workers=8, pin_memory=True) |
| test_loader = DataLoader(MelDataset(test_df, AUDIO_DIR, has_labels=False), |
| batch_size=BATCH, shuffle=False, num_workers=8, pin_memory=True) |
|
|
| model = MelCNN().to(DEVICE) |
| optimizer = torch.optim.Adam(model.parameters(), lr=LR) |
| scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS) |
| criterion = nn.BCEWithLogitsLoss() |
| scaler = torch.cuda.amp.GradScaler() |
|
|
| train_losses, val_aurocs = [], [] |
|
|
| for epoch in range(1, EPOCHS + 1): |
| model.train() |
| total_loss = 0.0 |
| for mel, label in tr_loader: |
| mel, label = mel.to(DEVICE), label.to(DEVICE) |
| optimizer.zero_grad() |
| with torch.cuda.amp.autocast(): |
| logits = model(mel) |
| loss = criterion(logits, label) |
| scaler.scale(loss).backward() |
| scaler.step(optimizer) |
| scaler.update() |
| total_loss += loss.item() * len(label) |
| scheduler.step() |
|
|
| |
| model.eval() |
| all_probs, all_labels = [], [] |
| with torch.no_grad(): |
| for mel, label in val_loader: |
| mel = mel.to(DEVICE) |
| with torch.cuda.amp.autocast(): |
| logits = model(mel) |
| probs = torch.sigmoid(logits).cpu().numpy() |
| all_probs.extend(probs) |
| all_labels.extend(label.numpy()) |
|
|
| auroc = roc_auc_score(all_labels, all_probs) |
| avg_loss = total_loss / len(tr_df) |
| train_losses.append(avg_loss) |
| val_aurocs.append(auroc) |
| print(f"Epoch {epoch:02d}/{EPOCHS} loss={avg_loss:.4f} val_AUROC={auroc:.4f}") |
|
|
| fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4)) |
| ax1.plot(train_losses, marker="o"); ax1.set_title("Train Loss"); ax1.set_xlabel("Epoch") |
| ax2.plot(val_aurocs, marker="o", color="tomato"); ax2.set_title("Val AUROC"); ax2.set_xlabel("Epoch") |
| plt.tight_layout(); plt.savefig("/dev/null") |
| print(f"Best val AUROC: {max(val_aurocs):.4f} at epoch {np.argmax(val_aurocs)+1}") |
|
|
|
|
| val_preds = (np.array(all_probs) >= 0.5).astype(int) |
| cm = confusion_matrix(all_labels, val_preds) |
| disp = ConfusionMatrixDisplay(cm, display_labels=["real", "fake"]) |
| fig, ax = plt.subplots(figsize=(4, 4)) |
| disp.plot(ax=ax, colorbar=False) |
| ax.set_title(f"Confusion Matrix AUROC={val_aurocs[-1]:.3f}") |
| plt.tight_layout() |
| plt.savefig("/dev/null") |
|
|
|
|
| torch.save(model.state_dict(), "model_cnn_mel.pt") |
| print("Model saved to model_cnn_mel.pt") |
|
|
| model.eval() |
| ids_out, probs_out = [], [] |
| with torch.no_grad(): |
| for mel, ids in test_loader: |
| mel = mel.to(DEVICE) |
| logits = model(mel) |
| probs = torch.sigmoid(logits).cpu().numpy() |
| probs_out.extend(probs) |
| ids_out.extend(ids if isinstance(ids[0], str) else [i.item() for i in ids]) |
|
|
| probs_out = np.array(probs_out) |
| np.save("probs_cnn.npy", probs_out) |
|
|
| submission = pd.DataFrame({"id": ids_out, "score": probs_out}) |
| submission.to_csv("submission_cnn_mel.csv", index=False) |
| print(submission.head()) |
| print("Saved submission_cnn_mel.csv | probs_cnn.npy") |
|
|
|
|