# /// script # requires-python = ">=3.10" # dependencies = ["numpy>=1.26", "pandas>=2", "scikit-learn>=1.4"] # /// """Simple scikit-learn genre classification baselines on FreeTZAN. For every feature set written by scripts/extract_features.py and every classifier below: features are standardized (fit on train), each hyperparameter setting is trained on train, the setting with the best valid accuracy is kept (the first one listed on ties), and its test accuracy is reported. Nothing is trained on valid or test. Everything is deterministic. Output: resources/baselines.csv (one row per feature set x classifier) and a Markdown table of test accuracies on stdout. Usage: uv run scripts/run_baselines.py [--features-dir ~/.cache/freetzan/features] """ import argparse from pathlib import Path import numpy as np import pandas as pd from sklearn.base import clone from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.model_selection import ParameterGrid from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC REPO = Path(__file__).resolve().parent.parent FEATURES = { 'mfcc': 'MFCC mean/std', 'fma': 'FMA librosa features', 'clap': 'LAION-CLAP (music)', 'mert': 'MERT-v1-95M', } CLASSIFIERS = { # name -> (estimator, hyperparameter grid searched on valid) 'kNN': (KNeighborsClassifier(), {'n_neighbors': [1, 5, 10, 20]}), 'LogReg': (LogisticRegression(max_iter=10000), {'C': [1e-3, 1e-2, 1e-1, 1, 10]}), 'SVM (RBF)': (SVC(), {'C': [0.1, 1, 10, 100]}), 'Random forest': (RandomForestClassifier(n_estimators=500, random_state=0, n_jobs=-1), {}), } def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('--features-dir', default=str(Path.home() / '.cache' / 'freetzan' / 'features')) ap.add_argument('--out', default=str(REPO / 'resources' / 'baselines.csv')) args = ap.parse_args() md = pd.read_csv(REPO / 'metadata.csv') y = md.genre.to_numpy() idx = {s: (md.split == s).to_numpy() for s in ('train', 'valid', 'test')} rows = [] for feat, feat_name in FEATURES.items(): f = Path(args.features_dir) / f'{feat}.npz' if not f.exists(): print(f'{feat}: {f} not found, skipping') continue z = np.load(f) assert (z['track_id'] == md.track_id.to_numpy()).all(), f'{f} rows do not match metadata.csv' X = z['X'] for clf_name, (clf, grid) in CLASSIFIERS.items(): best = None for params in ParameterGrid(grid): model = make_pipeline(StandardScaler(), clone(clf).set_params(**params)) model.fit(X[idx['train']], y[idx['train']]) valid_acc = model.score(X[idx['valid']], y[idx['valid']]) if best is None or valid_acc > best[0]: best = (valid_acc, params, model) valid_acc, params, model = best test_acc = model.score(X[idx['test']], y[idx['test']]) rows.append(dict(features=feat, dim=X.shape[1], classifier=clf_name, params=str(params), train_acc=round(model.score(X[idx['train']], y[idx['train']]), 3), valid_acc=round(valid_acc, 3), test_acc=round(test_acc, 3))) print(f'{feat:5s} {clf_name:14s} {str(params):22s} valid {valid_acc:.2f} test {test_acc:.2f}', flush=True) res = pd.DataFrame(rows) res.to_csv(args.out, index=False) table = res.pivot(index='features', columns='classifier', values='test_acc') table = table.loc[[f for f in FEATURES if f in table.index], list(CLASSIFIERS)] dims = res.groupby('features').dim.first() print(f'\nwrote {args.out}\n') print('| Features | Dim | ' + ' | '.join(table.columns) + ' |') print('|---|---:|' + '---:|' * len(table.columns)) for feat, r in table.iterrows(): print(f'| {FEATURES[feat]} | {dims[feat]} | ' + ' | '.join(f'{100 * v:.0f}%' for v in r) + ' |') if __name__ == '__main__': main()