voiceguard-competition / scripts /01_spectral_lr.py
fassabilf's picture
Upload folder using huggingface_hub
fe8ffdd verified
Raw
History Blame Contribute Delete
4.46 kB
from pathlib import Path
import numpy as np
import pandas as pd
import librosa
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
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
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_audio(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]
def hnr_autocorr(y, sr=SR, fmin=75, fmax=400):
frame_len = int(sr * 0.04)
hop = int(sr * 0.01)
hnrs = []
for start in range(0, len(y) - frame_len, hop):
frame = y[start: start + frame_len] * np.hanning(frame_len)
r = np.correlate(frame, frame, mode="full")
r = r[len(r) // 2:]
r0 = r[0] + 1e-8
min_lag, max_lag = int(sr / fmax), int(sr / fmin)
if max_lag >= len(r):
continue
r_max = r[min_lag:max_lag].max()
hnrs.append(10 * np.log10(r_max / (r0 - r_max + 1e-8)))
return float(np.mean(hnrs)) if hnrs else 0.0
def high_freq_energy_ratio(y, sr=SR, cutoff=4000, n_fft=512):
S = np.abs(librosa.stft(y, n_fft=n_fft)) ** 2
freqs = librosa.fft_frequencies(sr=sr, n_fft=n_fft)
total = S.sum() + 1e-8
high = S[freqs >= cutoff].sum()
return float(high / total)
def extract_features(path):
y = load_audio(path)
# spectral flatness
sf = librosa.feature.spectral_flatness(y=y)[0]
# mfcc
mfcc = librosa.feature.mfcc(y=y, sr=SR, n_mfcc=20)
# zcr
zcr = librosa.feature.zero_crossing_rate(y)[0]
# rms
rms = librosa.feature.rms(y=y)[0]
feat = np.concatenate([
[np.mean(sf), np.std(sf)],
[high_freq_energy_ratio(y)],
np.mean(mfcc, axis=1),
np.std(mfcc, axis=1),
[np.mean(zcr), np.std(zcr)],
[np.mean(rms), np.std(rms)],
[hnr_autocorr(y)],
])
return feat
from joblib import Parallel, delayed
from tqdm import tqdm
Path("cache").mkdir(exist_ok=True)
def _ex(row_id):
return extract_features(AUDIO_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_raw = np.nan_to_num(cached_extract(train_df, "vg_01_train.npy"), nan=0.0, posinf=0.0, neginf=0.0)
y_train = train_df["label"].to_numpy()
print("Done. Shape:", X_train_raw.shape)
print("Extracting test features …")
X_test_raw = np.nan_to_num(cached_extract(test_df, "vg_01_test.npy"), nan=0.0, posinf=0.0, neginf=0.0)
print("Done. Shape:", X_test_raw.shape)
X_tr, X_val, y_tr, y_val = train_test_split(
X_train_raw, y_train, test_size=0.2, random_state=42, stratify=y_train
)
scaler = StandardScaler()
X_tr_s = scaler.fit_transform(X_tr)
X_val_s = scaler.transform(X_val)
X_test_s = scaler.transform(X_test_raw)
clf = LogisticRegression(C=1.0, max_iter=500, random_state=42)
clf.fit(X_tr_s, y_tr)
val_probs = clf.predict_proba(X_val_s)[:, 1]
val_preds = (val_probs >= 0.5).astype(int)
auroc = roc_auc_score(y_val, val_probs)
print(f"Validation AUROC: {auroc:.4f}")
cm = confusion_matrix(y_val, 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 (threshold=0.5) AUROC={auroc:.3f}")
plt.tight_layout()
plt.savefig("/dev/null")
test_probs = clf.predict_proba(X_test_s)[:, 1]
np.save("probs_lr.npy", test_probs)
submission = pd.DataFrame({"id": test_df["id"], "score": test_probs})
submission.to_csv("submission_lr.csv", index=False)
print(submission.head())
print("Saved submission_lr.csv | probs_lr.npy")