| from pathlib import Path |
| import numpy as np |
| import pandas as pd |
| from tqdm import tqdm |
| import librosa |
| import warnings |
| warnings.filterwarnings("ignore") |
|
|
| DATA_DIR = Path("output/linguawave") |
| SAMPLE_RATE = 16_000 |
| DURATION = 10 |
| CLASSES = ["id", "ms", "vi", "th", "en", "zh", "ar", "fr"] |
|
|
|
|
| def extract_features(fpath, sr=SAMPLE_RATE, n_mfcc=20): |
| """Extract 40-dim MFCC feature vector (mean + std over time).""" |
| y, _ = librosa.load(str(fpath), sr=sr, duration=DURATION) |
| |
| target_len = sr * DURATION |
| if len(y) < target_len: |
| y = np.pad(y, (0, target_len - len(y))) |
| else: |
| y = y[:target_len] |
|
|
| mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=n_mfcc) |
| feats = np.concatenate([mfcc.mean(axis=1), mfcc.std(axis=1)]) |
| return feats |
|
|
|
|
| train_df = pd.read_csv(DATA_DIR / "train.csv") |
| test_df = pd.read_csv(DATA_DIR / "test.csv") |
|
|
| from joblib import Parallel, delayed |
| Path("cache").mkdir(exist_ok=True) |
|
|
| def _ex(row_id): |
| return extract_features(DATA_DIR / row_id) |
|
|
| def cached_extract(df, cache_name): |
| cp = Path("cache") / cache_name |
| if cp.exists(): |
| print(f"[cache] Loading {cache_name}"); return np.load(cp) |
| feats = np.array(Parallel(n_jobs=-1, prefer="threads")( |
| delayed(_ex)(r["id"]) for _, r in tqdm(df.iterrows(), total=len(df)))) |
| np.save(cp, feats); print(f"[cache] Saved {cache_name}"); return feats |
|
|
| print("Extracting train features ...") |
| X_train = cached_extract(train_df, "lw_01_train.npy") |
| y_train = train_df["label"].to_numpy() |
| print("X_train shape:", X_train.shape) |
|
|
| print("Extracting test features ...") |
| X_test = cached_extract(test_df, "lw_01_test.npy") |
| print("X_test shape:", X_test.shape) |
|
|
|
|
| from sklearn.model_selection import train_test_split |
| from sklearn.preprocessing import LabelEncoder, StandardScaler |
|
|
| le = LabelEncoder() |
| le.fit(CLASSES) |
|
|
| y_enc = le.transform(y_train) |
|
|
| X_tr, X_val, y_tr, y_val = train_test_split( |
| X_train, y_enc, test_size=0.15, random_state=42, stratify=y_enc |
| ) |
| print(f"Train: {X_tr.shape[0]} Val: {X_val.shape[0]}") |
|
|
|
|
| scaler = StandardScaler() |
| X_tr_s = scaler.fit_transform(X_tr) |
| X_val_s = scaler.transform(X_val) |
| X_test_s = scaler.transform(X_test) |
|
|
|
|
| from sklearn.svm import SVC |
| from sklearn.metrics import f1_score, classification_report |
|
|
| clf = SVC(kernel="rbf", C=10, probability=True, random_state=42) |
| clf.fit(X_tr_s, y_tr) |
| print("SVM training complete.") |
|
|
|
|
| val_preds = clf.predict(X_val_s) |
| macro_f1 = f1_score(y_val, val_preds, average="macro") |
| print(f"Validation Macro F1: {macro_f1:.4f}") |
|
|
| print() |
| print(classification_report( |
| y_val, val_preds, |
| target_names=le.classes_, |
| )) |
|
|
|
|
| test_preds_enc = clf.predict(X_test_s) |
| test_preds = le.inverse_transform(test_preds_enc) |
|
|
| sub = pd.DataFrame({"id": test_df["id"], "label": test_preds}) |
| Path("submissions").mkdir(exist_ok=True) |
| sub.to_csv("submissions/sub_approach1_mfcc_svm.csv", index=False) |
| print("Saved submissions/sub_approach1_mfcc_svm.csv") |
| sub.head() |
|
|
|
|