fassabilf's picture
Upload folder using huggingface_hub
e83f0ea verified
Raw
History Blame Contribute Delete
8.57 kB
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
DATA_DIR = Path("output/linguawave")
SAMPLE_RATE = 16_000
DURATION = 10
N_SAMPLES = SAMPLE_RATE * DURATION # 160_000
CLASSES = ["id", "ms", "vi", "th", "en", "zh", "ar", "fr"]
N_CLASSES = len(CLASSES)
# Mel-spectrogram params
N_MELS = 128
N_FFT = 1024
HOP_LENGTH = 256
# expected time frames ≈ N_SAMPLES / HOP_LENGTH = 160000/256 = 625
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Device:", DEVICE)
class MelDataset(Dataset):
def __init__(self, df, data_dir, label_encoder, n_mels=N_MELS,
n_fft=N_FFT, hop_length=HOP_LENGTH, augment=False):
self.df = df.reset_index(drop=True)
self.data_dir = data_dir
self.le = label_encoder
self.n_mels = n_mels
self.n_fft = n_fft
self.hop_length = hop_length
self.augment = augment
self.has_labels = "label" in df.columns
def __len__(self):
return len(self.df)
def _load_mel(self, fpath):
y, _ = librosa.load(str(fpath), sr=SAMPLE_RATE, duration=DURATION)
if len(y) < N_SAMPLES:
y = np.pad(y, (0, N_SAMPLES - len(y)))
else:
y = y[:N_SAMPLES]
if self.augment:
# Time shift augmentation
shift = np.random.randint(-SAMPLE_RATE, SAMPLE_RATE)
y = np.roll(y, shift)
mel = librosa.feature.melspectrogram(
y=y, sr=SAMPLE_RATE,
n_mels=self.n_mels, n_fft=self.n_fft, hop_length=self.hop_length
)
log_mel = librosa.power_to_db(mel, ref=np.max).astype(np.float32)
# Normalise to [-1, 1]
log_mel = (log_mel - log_mel.mean()) / (log_mel.std() + 1e-8)
return log_mel[np.newaxis, :, :] # (1, n_mels, T)
def __getitem__(self, idx):
row = self.df.iloc[idx]
mel = self._load_mel(self.data_dir / row["id"])
if self.has_labels:
label = self.le.transform([row["label"]])[0]
return torch.tensor(mel), label
return torch.tensor(mel)
class ConvBlock(nn.Module):
def __init__(self, in_ch, out_ch):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(in_ch, out_ch, kernel_size=3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
nn.Conv2d(out_ch, out_ch, kernel_size=3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
nn.MaxPool2d(2, 2),
)
def forward(self, x):
return self.net(x)
class MelCNN(nn.Module):
def __init__(self, n_classes=N_CLASSES):
super().__init__()
self.features = nn.Sequential(
ConvBlock(1, 32), # (1, 128, 625) → (32, 64, 312)
ConvBlock(32, 64), # → (64, 32, 156)
ConvBlock(64, 128), # → (128, 16, 78)
ConvBlock(128, 256), # → (256, 8, 39)
nn.AdaptiveAvgPool2d(1), # → (256, 1, 1)
)
self.head = nn.Sequential(
nn.Flatten(),
nn.Linear(256, 128),
nn.ReLU(inplace=True),
nn.Dropout(0.5),
nn.Linear(128, n_classes),
)
def forward(self, x):
x = self.features(x)
return self.head(x)
model = MelCNN().to(DEVICE)
print(model)
total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"Trainable params: {total_params:,}")
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"]
)
BATCH = 64
train_ds = MelDataset(tr_df, DATA_DIR, le, augment=True)
val_ds = MelDataset(val_df, DATA_DIR, le, augment=False)
test_ds = MelDataset(test_df, DATA_DIR, le, augment=False)
train_loader = DataLoader(train_ds, batch_size=BATCH, shuffle=True, num_workers=4, pin_memory=True)
val_loader = DataLoader(val_ds, batch_size=BATCH, shuffle=False, num_workers=4, pin_memory=True)
test_loader = DataLoader(test_ds, batch_size=BATCH, shuffle=False, num_workers=4, pin_memory=True)
print(f"Train batches: {len(train_loader)} Val batches: {len(val_loader)}")
EPOCHS = 5
criterion = nn.CrossEntropyLoss()
optimizer = optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4)
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS)
scaler = torch.cuda.amp.GradScaler()
history = {"train_loss": [], "val_f1": []}
best_f1 = 0.0
best_weights = None
for epoch in range(1, EPOCHS + 1):
# ── train ──────────────────────────────────────────────────
model.train()
running_loss = 0.0
for X_batch, y_batch in tqdm(train_loader, desc=f"Epoch {epoch:02d} train", leave=False):
X_batch = X_batch.to(DEVICE)
y_batch = y_batch.to(DEVICE)
optimizer.zero_grad()
with torch.cuda.amp.autocast():
logits = model(X_batch)
loss = criterion(logits, y_batch)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
running_loss += loss.item() * len(y_batch)
train_loss = running_loss / len(train_ds)
# ── validate ────────────────────────────────────────────────
model.eval()
all_preds, all_labels = [], []
with torch.no_grad():
for X_batch, y_batch in val_loader:
X_batch = X_batch.to(DEVICE)
with torch.cuda.amp.autocast():
preds = model(X_batch).argmax(dim=1).cpu().numpy()
all_preds.extend(preds)
all_labels.extend(y_batch.numpy())
val_f1 = f1_score(all_labels, all_preds, average="macro")
history["train_loss"].append(train_loss)
history["val_f1"].append(val_f1)
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} loss={train_loss:.4f} 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
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
ax1.plot(history["train_loss"])
ax1.set_title("Training Loss")
ax1.set_xlabel("Epoch")
ax2.plot(history["val_f1"])
ax2.set_title("Validation Macro F1")
ax2.set_xlabel("Epoch")
plt.tight_layout()
plt.savefig("/dev/null")
model.load_state_dict(best_weights)
model.eval()
all_preds, all_labels = [], []
with torch.no_grad():
for X_batch, y_batch in val_loader:
X_batch = X_batch.to(DEVICE)
preds = model(X_batch).argmax(dim=1).cpu().numpy()
all_preds.extend(preds)
all_labels.extend(y_batch.numpy())
print(f"Final validation Macro F1: {f1_score(all_labels, all_preds, average='macro'):.4f}")
print()
print(classification_report(all_labels, all_preds, target_names=le.classes_))
Path("submissions").mkdir(exist_ok=True)
# Save model
torch.save(best_weights, "submissions/model_approach4_cnn_mel.pt")
print("Model saved.")
# Generate test probabilities
model.eval()
all_probs = []
with torch.no_grad():
for X_batch in tqdm(DataLoader(test_ds, batch_size=64, num_workers=4, pin_memory=True), desc="Test inference"):
if isinstance(X_batch, (list, tuple)):
X_batch = X_batch[0]
X_batch = X_batch.to(DEVICE)
with torch.cuda.amp.autocast():
probs = torch.softmax(model(X_batch), dim=1).cpu().numpy()
all_probs.append(probs)
test_probs = np.vstack(all_probs)
np.save("submissions/probs_approach4_cnn_mel.npy", test_probs)
print("Test probabilities saved. Shape:", test_probs.shape)
# Submission CSV
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_approach4_cnn_mel.csv", index=False)
print("Saved submissions/sub_approach4_cnn_mel.csv")
sub.head()