| 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 |
|
|
| BATCH = 32 |
| EPOCHS = 20 |
| 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_waveform(path, sr=SR, n_samples=N_SAMPLES): |
| y, _ = librosa.load(path, sr=sr, mono=True) |
| if len(y) < n_samples: |
| y = np.pad(y, (0, n_samples - len(y))) |
| return y[:n_samples].astype(np.float32) |
|
|
|
|
| class WaveDataset(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] |
| wav = load_waveform(self.audio_dir / row["id"]) |
| wav = torch.from_numpy(wav) |
| if self.has_labels: |
| return wav, torch.tensor(row["label"], dtype=torch.float32) |
| return wav, row["id"] |
|
|
|
|
| class ResBlock1D(nn.Module): |
| """Residual block for 1D convolutions.""" |
| def __init__(self, channels, kernel_size=3, stride=2): |
| super().__init__() |
| self.conv = nn.Conv1d(channels, channels, kernel_size, |
| stride=stride, padding=kernel_size // 2) |
| self.bn = nn.BatchNorm1d(channels) |
| self.act = nn.LeakyReLU(0.3) |
| |
| self.shortcut = nn.Sequential( |
| nn.Conv1d(channels, channels, 1, stride=stride), |
| nn.BatchNorm1d(channels), |
| ) |
|
|
| def forward(self, x): |
| return self.act(self.conv(x) + self.shortcut(x)) |
|
|
|
|
| class RawNet(nn.Module): |
| def __init__(self): |
| super().__init__() |
| |
| self.conv1 = nn.Conv1d(1, 128, kernel_size=3, stride=3, padding=1) |
| self.bn1 = nn.BatchNorm1d(128) |
|
|
| |
| self.proj = nn.Sequential( |
| nn.Conv1d(128, 256, 1), nn.BatchNorm1d(256), nn.LeakyReLU(0.3) |
| ) |
| self.blocks = nn.Sequential( |
| ResBlock1D(128, stride=2), |
| ResBlock1D(128, stride=2), |
| ) |
| self.blocks2 = nn.Sequential( |
| ResBlock1D(256, stride=2), |
| ResBlock1D(256, stride=2), |
| ResBlock1D(256, stride=2), |
| ) |
|
|
| self.gru = nn.GRU(256, 128, batch_first=True, bidirectional=True) |
| self.head = nn.Linear(256, 1) |
|
|
| def forward(self, x): |
| x = x.unsqueeze(1) |
| x = torch.relu(self.bn1(self.conv1(x))) |
| x = self.blocks(x) |
| x = self.proj(x) |
| x = self.blocks2(x) |
| x = x.permute(0, 2, 1) |
| x, _ = self.gru(x) |
| x = x.mean(1) |
| return self.head(x).squeeze(-1) |
|
|
|
|
| |
| _m = RawNet() |
| _x = torch.randn(2, N_SAMPLES) |
| print("Output shape:", _m(_x).shape) |
|
|
|
|
| tr_df, val_df = train_test_split(train_df, test_size=0.2, |
| random_state=42, stratify=train_df["label"]) |
|
|
| tr_loader = DataLoader(WaveDataset(tr_df, AUDIO_DIR), batch_size=BATCH, shuffle=True, num_workers=2) |
| val_loader = DataLoader(WaveDataset(val_df, AUDIO_DIR), batch_size=BATCH, shuffle=False, num_workers=2) |
| test_loader = DataLoader(WaveDataset(test_df, AUDIO_DIR, has_labels=False), |
| batch_size=BATCH, shuffle=False, num_workers=2) |
|
|
|
|
| model = RawNet().to(DEVICE) |
| optimizer = torch.optim.Adam(model.parameters(), lr=LR, weight_decay=1e-4) |
| scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS) |
| criterion = nn.BCEWithLogitsLoss() |
|
|
| train_losses, val_aurocs = [], [] |
|
|
| for epoch in range(1, EPOCHS + 1): |
| model.train() |
| total_loss = 0.0 |
| for wav, label in tr_loader: |
| wav, label = wav.to(DEVICE), label.to(DEVICE) |
| optimizer.zero_grad() |
| logits = model(wav) |
| loss = criterion(logits, label) |
| loss.backward() |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) |
| optimizer.step() |
| total_loss += loss.item() * len(label) |
| scheduler.step() |
|
|
| model.eval() |
| all_probs, all_labels = [], [] |
| with torch.no_grad(): |
| for wav, label in val_loader: |
| wav = wav.to(DEVICE) |
| probs = torch.sigmoid(model(wav)).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_rawnet.pt") |
| print("Model saved to model_rawnet.pt") |
|
|
| model.eval() |
| ids_out, probs_out = [], [] |
| with torch.no_grad(): |
| for wav, ids in test_loader: |
| wav = wav.to(DEVICE) |
| probs = torch.sigmoid(model(wav)).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_rawnet.npy", probs_out) |
|
|
| submission = pd.DataFrame({"id": ids_out, "score": probs_out}) |
| submission.to_csv("submission_rawnet.csv", index=False) |
| print(submission.head()) |
| print("Saved submission_rawnet.csv | probs_rawnet.npy") |
|
|
|
|
| try: |
| probs_cnn = np.load("probs_cnn.npy") |
| ensemble_score = 0.5 * probs_out + 0.5 * probs_cnn |
| sub_ensemble = pd.DataFrame({"id": ids_out, "score": ensemble_score}) |
| sub_ensemble.to_csv("submission_ensemble.csv", index=False) |
| print("Ensemble submission saved to submission_ensemble.csv") |
| print(sub_ensemble.head()) |
| except FileNotFoundError: |
| print("probs_cnn.npy not found — run notebook 04 first for ensemble.") |
|
|
|
|