| 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"] |
|
|
| N_CLUSTERS = 64 |
| FRAME_SUBSAMPLE = 5 |
| N_MFCC = 20 |
|
|
|
|
| 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 _get_frames(row_id): |
| y, _ = librosa.load(str(DATA_DIR / row_id), sr=SAMPLE_RATE, duration=DURATION) |
| target_len = SAMPLE_RATE * 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=SAMPLE_RATE, n_mfcc=N_MFCC) |
| return mfcc.T[::FRAME_SUBSAMPLE] |
|
|
| print("Collecting MFCC frames from training files ...") |
| frame_cp = Path("cache") / "lw_03_frames.npy" |
| if frame_cp.exists(): |
| print("[cache] Loading lw_03_frames.npy"); all_frames = np.load(frame_cp) |
| else: |
| results = Parallel(n_jobs=-1, prefer="threads")( |
| delayed(_get_frames)(r["id"]) for _, r in tqdm(train_df.iterrows(), total=len(train_df))) |
| all_frames = np.vstack(results) |
| np.save(frame_cp, all_frames); print("[cache] Saved lw_03_frames.npy") |
|
|
| print(f"Total subsampled frames: {all_frames.shape}") |
|
|
|
|
| from sklearn.cluster import MiniBatchKMeans |
|
|
| print(f"Fitting KMeans with k={N_CLUSTERS} ...") |
| kmeans = MiniBatchKMeans(n_clusters=N_CLUSTERS, random_state=42, batch_size=4096, n_init=5) |
| kmeans.fit(all_frames) |
| print("KMeans fitting complete.") |
|
|
|
|
| def file_to_histogram(fpath, kmeans=kmeans): |
| """Assign each MFCC frame to a cluster and return normalised frequency histogram.""" |
| y, _ = librosa.load(str(fpath), sr=SAMPLE_RATE, duration=DURATION) |
| target_len = SAMPLE_RATE * 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=SAMPLE_RATE, n_mfcc=N_MFCC).T |
| labels = kmeans.predict(mfcc) |
| hist, _ = np.histogram(labels, bins=N_CLUSTERS, range=(0, N_CLUSTERS)) |
| return hist.astype(np.float32) / (hist.sum() + 1e-8) |
|
|
| print("Building train histograms ...") |
| train_hist_cp = Path("cache") / "lw_03_train_hist.npy" |
| test_hist_cp = Path("cache") / "lw_03_test_hist.npy" |
| if train_hist_cp.exists(): |
| print("[cache] Loading histograms") |
| X_train_hist = np.load(train_hist_cp) |
| X_test_hist = np.load(test_hist_cp) |
| else: |
| X_train_hist = np.array(Parallel(n_jobs=-1, prefer="threads")( |
| delayed(file_to_histogram)(DATA_DIR / r["id"]) |
| for _, r in tqdm(train_df.iterrows(), total=len(train_df)))) |
| print("Building test histograms ...") |
| X_test_hist = np.array(Parallel(n_jobs=-1, prefer="threads")( |
| delayed(file_to_histogram)(DATA_DIR / r["id"]) |
| for _, r in tqdm(test_df.iterrows(), total=len(test_df)))) |
| np.save(train_hist_cp, X_train_hist); np.save(test_hist_cp, X_test_hist) |
| print("[cache] Saved histograms") |
| y_train = train_df["label"].to_numpy() |
| print("X_train_hist shape:", X_train_hist.shape) |
| print("X_test_hist shape:", X_test_hist.shape) |
|
|
|
|
| from sklearn.model_selection import train_test_split |
| from sklearn.preprocessing import LabelEncoder |
|
|
| le = LabelEncoder() |
| le.fit(CLASSES) |
| y_enc = le.transform(y_train) |
|
|
| X_tr, X_val, y_tr, y_val = train_test_split( |
| X_train_hist, y_enc, test_size=0.15, random_state=42, stratify=y_enc |
| ) |
| print(f"Train: {X_tr.shape[0]} Val: {X_val.shape[0]}") |
|
|
|
|
| from sklearn.linear_model import LogisticRegression |
| from sklearn.metrics import f1_score, classification_report |
|
|
| lr = LogisticRegression(max_iter=1000, C=1.0, |
| solver="lbfgs", random_state=42, n_jobs=-1) |
| lr.fit(X_tr, y_tr) |
| print("Logistic Regression training complete.") |
|
|
|
|
| val_preds = lr.predict(X_val) |
| 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_)) |
|
|
|
|
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
|
|
| fig, axes = plt.subplots(2, 4, figsize=(16, 6), sharey=False) |
| axes = axes.flatten() |
|
|
| for idx, lang in enumerate(CLASSES): |
| mask = y_train == lang |
| avg_hist = X_train_hist[mask].mean(axis=0) |
| axes[idx].bar(range(N_CLUSTERS), avg_hist) |
| axes[idx].set_title(lang) |
| axes[idx].set_xlabel("Codeword") |
| axes[idx].set_ylabel("Freq") |
|
|
| plt.suptitle("Average codeword histogram per language") |
| plt.tight_layout() |
| plt.savefig("/dev/null") |
|
|
|
|
| test_preds_enc = lr.predict(X_test_hist) |
| 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_approach3_bag_of_codewords.csv", index=False) |
| print("Saved submissions/sub_approach3_bag_of_codewords.csv") |
| sub.head() |
|
|
|
|