| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202 |
- #!/usr/bin/env python3
- """Rebuild model.js for the «Голос винта» interactive.
- Usage: python train_model.py train.npz
- Dependencies: numpy, scipy, scikit-learn.
- Implements Solution #2 from ML1. Голос винта.
- """
- from __future__ import annotations
- import base64
- import json
- import sys
- from pathlib import Path
- import numpy as np
- from scipy.fftpack import dct
- from sklearn.linear_model import LogisticRegression
- from sklearn.metrics import accuracy_score, roc_auc_score
- from sklearn.model_selection import train_test_split
- EPS = 1e-10
- def safe_corr(a: np.ndarray, b: np.ndarray) -> float:
- if len(a) < 2:
- return 0.0
- a = a - np.mean(a)
- b = b - np.mean(b)
- denom = np.std(a) * np.std(b)
- if denom < EPS:
- return 0.0
- return float(np.mean(a * b) / denom)
- def extract_raw(X: np.ndarray) -> np.ndarray:
- """Return the 46 features used by Solution #2."""
- n = X.shape[0]
- feats = np.zeros((n, 46), dtype=np.float64)
- for i in range(n):
- S = X[i].astype(np.float64) # dB, 64 x 44
- # MFCC-like coefficients: DCT-II along frequency.
- S_centered = S - np.mean(S, axis=0, keepdims=True)
- mfcc = dct(S_centered, type=2, axis=0, norm="ortho")
- mfcc = mfcc[1:14, :]
- mfcc_mean = np.mean(mfcc, axis=1)
- mfcc_std = np.std(mfcc, axis=1)
- # Linear power and per-frame normalized distributions.
- P = 10.0 ** (S / 10.0)
- frame_sum = np.sum(P, axis=0, keepdims=True) + EPS
- Pn = P / frame_sum
- freqs = np.arange(64).reshape(64, 1)
- centroid = np.sum(freqs * Pn, axis=0)
- bandwidth = np.sqrt(np.sum(((freqs - centroid) ** 2) * Pn, axis=0))
- logP = np.log(Pn + EPS)
- gm = np.exp(np.mean(logP, axis=0))
- am = np.mean(Pn, axis=0)
- flatness = gm / (am + EPS)
- entropy = -np.sum(Pn * logP, axis=0) / np.log(64)
- cumsum = np.cumsum(Pn, axis=0)
- rolloff = np.zeros(44)
- for t in range(44):
- rolloff[t] = np.searchsorted(cumsum[:, t], 0.85) / 63.0
- total_energy = np.sum(P, axis=0)
- total_energy_norm = total_energy / (np.mean(total_energy) + EPS)
- ac1 = safe_corr(total_energy_norm[:-1], total_energy_norm[1:])
- ac2 = safe_corr(total_energy_norm[:-2], total_energy_norm[2:])
- env = total_energy_norm - np.mean(total_energy_norm)
- zcr = np.mean(np.abs(np.diff(np.sign(env)))) / 2.0 if len(env) > 1 else 0.0
- low_energy = np.sum(P[:16, :])
- high_energy = np.sum(P[32:, :])
- total = np.sum(P) + EPS
- low_ratio = low_energy / total
- high_ratio = high_energy / total
- S_norm = S - np.median(S, axis=1, keepdims=True)
- m = np.mean(S_norm)
- s = np.std(S_norm) + EPS
- kurt = np.mean((S_norm - m) ** 4) / (s ** 4 + EPS) - 3.0
- skew = np.mean((S_norm - m) ** 3) / (s ** 3 + EPS)
- freq_var = np.var(S_norm, axis=1)
- freq_range = np.max(S_norm, axis=1) - np.min(S_norm, axis=1)
- feats[i] = np.concatenate([
- mfcc_mean, mfcc_std,
- [np.mean(centroid), np.std(centroid)],
- [np.mean(bandwidth), np.std(bandwidth)],
- [np.mean(rolloff)],
- [np.mean(flatness), np.std(flatness)],
- [np.mean(entropy), np.std(entropy)],
- [ac1, ac2, zcr],
- [low_ratio, high_ratio],
- [kurt, skew],
- [np.mean(freq_var), np.std(freq_var)],
- [np.mean(freq_range), np.std(freq_range)],
- ])
- return feats
- def fit_pipeline(F: np.ndarray, y: np.ndarray):
- mean = np.mean(F, axis=0)
- std = np.std(F, axis=0)
- std[std < 1e-8] = 1.0
- normalized = (F - mean) / std
- _, _, vt = np.linalg.svd(normalized, full_matrices=False)
- components = vt[:16]
- projected = normalized @ components.T
- projected_mean = np.mean(projected, axis=0)
- projected_std = np.std(projected, axis=0)
- projected_std[projected_std < 1e-8] = 1.0
- projected = (projected - projected_mean) / projected_std
- classifier = LogisticRegression()
- classifier.fit(projected, y)
- return mean, std, components, projected_mean, projected_std, classifier
- def main() -> None:
- source = Path(sys.argv[1] if len(sys.argv) > 1 else "train.npz")
- data = np.load(source)
- X = data["X"]
- y = data["y"].astype(int)
- if X.shape[1:] != (64, 44):
- raise ValueError(f"Expected X shape (N, 64, 44), got {X.shape}")
- X_db = X.astype(np.float64) * 0.3 - 45.0
- F = extract_raw(X_db)
- # Reproducible local holdout check.
- ids_train, ids_valid = train_test_split(
- np.arange(len(y)), test_size=0.2, random_state=42, stratify=y
- )
- vmean, vstd, vcomp, vpm, vps, vclf = fit_pipeline(F[ids_train], y[ids_train])
- vproj = ((F[ids_valid] - vmean) / vstd) @ vcomp.T
- vproj = (vproj - vpm) / vps
- vprob = vclf.predict_proba(vproj)[:, 1]
- val_auc = float(roc_auc_score(y[ids_valid], vprob))
- val_acc = float(accuracy_score(y[ids_valid], (vprob >= 0.5).astype(int)))
- # Final classifier trained on all 4000 labelled spectrograms.
- mean, std, components, pmean, pstd, clf = fit_pipeline(F, y)
- p_all = clf.predict_proba(((F - mean) / std @ components.T - pmean) / pstd)[:, 1]
- samples = []
- used = set()
- targets = {0: [0.08, 0.18, 0.28, 0.38], 1: [0.62, 0.75, 0.87, 0.96]}
- for label, target_values in targets.items():
- ids = np.where(y == label)[0]
- for j, target in enumerate(target_values):
- order = sorted(ids, key=lambda ix: abs(float(p_all[ix]) - target))
- index = next(int(ix) for ix in order if int(ix) not in used)
- used.add(index)
- encoded = base64.b64encode(X[index].astype(np.uint8).tobytes()).decode("ascii")
- samples.append({
- "id": f"{'bg' if label == 0 else 'uav'}{j + 1}",
- "name": f"{'Фоновая запись' if label == 0 else 'Запись с БПЛА'} {j + 1}",
- "label": int(label),
- "sourceIndex": index,
- "base64": encoded,
- "trainModelScore": float(p_all[index]),
- })
- payload = {
- "description": "46 raw features -> standardization -> PCA(16) -> standardization -> LogisticRegression",
- "source": "ML1 Голос винта, Решение №2",
- "rawMean": mean.tolist(),
- "rawStd": std.tolist(),
- "components": components.tolist(),
- "projectionMean": pmean.tolist(),
- "projectionStd": pstd.tolist(),
- "coef": clf.coef_[0].tolist(),
- "intercept": float(clf.intercept_[0]),
- "classes": [0, 1],
- "validation": {
- "split": "stratified 80/20, random_state=42",
- "rocAuc": val_auc,
- "accuracy": val_acc,
- "trainCount": int(len(ids_train)),
- "validationCount": int(len(ids_valid)),
- },
- }
- out = Path(__file__).resolve().parent / "model.js"
- with out.open("w", encoding="utf-8") as f:
- f.write("window.GOLOS_MODEL = ")
- json.dump(payload, f, separators=(",", ":"), ensure_ascii=False)
- f.write(";\nwindow.GOLOS_SAMPLES = ")
- json.dump(samples, f, separators=(",", ":"), ensure_ascii=False)
- f.write(";\n")
- print(f"Saved {out}")
- print(f"Local holdout ROC-AUC={val_auc:.4f}; accuracy@0.5={val_acc:.4f}")
- if __name__ == "__main__":
- main()
|