train_model.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #!/usr/bin/env python3
  2. """Rebuild model.js for the «Голос винта» interactive.
  3. Usage: python train_model.py train.npz
  4. Dependencies: numpy, scipy, scikit-learn.
  5. Implements Solution #2 from ML1. Голос винта.
  6. """
  7. from __future__ import annotations
  8. import base64
  9. import json
  10. import sys
  11. from pathlib import Path
  12. import numpy as np
  13. from scipy.fftpack import dct
  14. from sklearn.linear_model import LogisticRegression
  15. from sklearn.metrics import accuracy_score, roc_auc_score
  16. from sklearn.model_selection import train_test_split
  17. EPS = 1e-10
  18. def safe_corr(a: np.ndarray, b: np.ndarray) -> float:
  19. if len(a) < 2:
  20. return 0.0
  21. a = a - np.mean(a)
  22. b = b - np.mean(b)
  23. denom = np.std(a) * np.std(b)
  24. if denom < EPS:
  25. return 0.0
  26. return float(np.mean(a * b) / denom)
  27. def extract_raw(X: np.ndarray) -> np.ndarray:
  28. """Return the 46 features used by Solution #2."""
  29. n = X.shape[0]
  30. feats = np.zeros((n, 46), dtype=np.float64)
  31. for i in range(n):
  32. S = X[i].astype(np.float64) # dB, 64 x 44
  33. # MFCC-like coefficients: DCT-II along frequency.
  34. S_centered = S - np.mean(S, axis=0, keepdims=True)
  35. mfcc = dct(S_centered, type=2, axis=0, norm="ortho")
  36. mfcc = mfcc[1:14, :]
  37. mfcc_mean = np.mean(mfcc, axis=1)
  38. mfcc_std = np.std(mfcc, axis=1)
  39. # Linear power and per-frame normalized distributions.
  40. P = 10.0 ** (S / 10.0)
  41. frame_sum = np.sum(P, axis=0, keepdims=True) + EPS
  42. Pn = P / frame_sum
  43. freqs = np.arange(64).reshape(64, 1)
  44. centroid = np.sum(freqs * Pn, axis=0)
  45. bandwidth = np.sqrt(np.sum(((freqs - centroid) ** 2) * Pn, axis=0))
  46. logP = np.log(Pn + EPS)
  47. gm = np.exp(np.mean(logP, axis=0))
  48. am = np.mean(Pn, axis=0)
  49. flatness = gm / (am + EPS)
  50. entropy = -np.sum(Pn * logP, axis=0) / np.log(64)
  51. cumsum = np.cumsum(Pn, axis=0)
  52. rolloff = np.zeros(44)
  53. for t in range(44):
  54. rolloff[t] = np.searchsorted(cumsum[:, t], 0.85) / 63.0
  55. total_energy = np.sum(P, axis=0)
  56. total_energy_norm = total_energy / (np.mean(total_energy) + EPS)
  57. ac1 = safe_corr(total_energy_norm[:-1], total_energy_norm[1:])
  58. ac2 = safe_corr(total_energy_norm[:-2], total_energy_norm[2:])
  59. env = total_energy_norm - np.mean(total_energy_norm)
  60. zcr = np.mean(np.abs(np.diff(np.sign(env)))) / 2.0 if len(env) > 1 else 0.0
  61. low_energy = np.sum(P[:16, :])
  62. high_energy = np.sum(P[32:, :])
  63. total = np.sum(P) + EPS
  64. low_ratio = low_energy / total
  65. high_ratio = high_energy / total
  66. S_norm = S - np.median(S, axis=1, keepdims=True)
  67. m = np.mean(S_norm)
  68. s = np.std(S_norm) + EPS
  69. kurt = np.mean((S_norm - m) ** 4) / (s ** 4 + EPS) - 3.0
  70. skew = np.mean((S_norm - m) ** 3) / (s ** 3 + EPS)
  71. freq_var = np.var(S_norm, axis=1)
  72. freq_range = np.max(S_norm, axis=1) - np.min(S_norm, axis=1)
  73. feats[i] = np.concatenate([
  74. mfcc_mean, mfcc_std,
  75. [np.mean(centroid), np.std(centroid)],
  76. [np.mean(bandwidth), np.std(bandwidth)],
  77. [np.mean(rolloff)],
  78. [np.mean(flatness), np.std(flatness)],
  79. [np.mean(entropy), np.std(entropy)],
  80. [ac1, ac2, zcr],
  81. [low_ratio, high_ratio],
  82. [kurt, skew],
  83. [np.mean(freq_var), np.std(freq_var)],
  84. [np.mean(freq_range), np.std(freq_range)],
  85. ])
  86. return feats
  87. def fit_pipeline(F: np.ndarray, y: np.ndarray):
  88. mean = np.mean(F, axis=0)
  89. std = np.std(F, axis=0)
  90. std[std < 1e-8] = 1.0
  91. normalized = (F - mean) / std
  92. _, _, vt = np.linalg.svd(normalized, full_matrices=False)
  93. components = vt[:16]
  94. projected = normalized @ components.T
  95. projected_mean = np.mean(projected, axis=0)
  96. projected_std = np.std(projected, axis=0)
  97. projected_std[projected_std < 1e-8] = 1.0
  98. projected = (projected - projected_mean) / projected_std
  99. classifier = LogisticRegression()
  100. classifier.fit(projected, y)
  101. return mean, std, components, projected_mean, projected_std, classifier
  102. def main() -> None:
  103. source = Path(sys.argv[1] if len(sys.argv) > 1 else "train.npz")
  104. data = np.load(source)
  105. X = data["X"]
  106. y = data["y"].astype(int)
  107. if X.shape[1:] != (64, 44):
  108. raise ValueError(f"Expected X shape (N, 64, 44), got {X.shape}")
  109. X_db = X.astype(np.float64) * 0.3 - 45.0
  110. F = extract_raw(X_db)
  111. # Reproducible local holdout check.
  112. ids_train, ids_valid = train_test_split(
  113. np.arange(len(y)), test_size=0.2, random_state=42, stratify=y
  114. )
  115. vmean, vstd, vcomp, vpm, vps, vclf = fit_pipeline(F[ids_train], y[ids_train])
  116. vproj = ((F[ids_valid] - vmean) / vstd) @ vcomp.T
  117. vproj = (vproj - vpm) / vps
  118. vprob = vclf.predict_proba(vproj)[:, 1]
  119. val_auc = float(roc_auc_score(y[ids_valid], vprob))
  120. val_acc = float(accuracy_score(y[ids_valid], (vprob >= 0.5).astype(int)))
  121. # Final classifier trained on all 4000 labelled spectrograms.
  122. mean, std, components, pmean, pstd, clf = fit_pipeline(F, y)
  123. p_all = clf.predict_proba(((F - mean) / std @ components.T - pmean) / pstd)[:, 1]
  124. samples = []
  125. used = set()
  126. targets = {0: [0.08, 0.18, 0.28, 0.38], 1: [0.62, 0.75, 0.87, 0.96]}
  127. for label, target_values in targets.items():
  128. ids = np.where(y == label)[0]
  129. for j, target in enumerate(target_values):
  130. order = sorted(ids, key=lambda ix: abs(float(p_all[ix]) - target))
  131. index = next(int(ix) for ix in order if int(ix) not in used)
  132. used.add(index)
  133. encoded = base64.b64encode(X[index].astype(np.uint8).tobytes()).decode("ascii")
  134. samples.append({
  135. "id": f"{'bg' if label == 0 else 'uav'}{j + 1}",
  136. "name": f"{'Фоновая запись' if label == 0 else 'Запись с БПЛА'} {j + 1}",
  137. "label": int(label),
  138. "sourceIndex": index,
  139. "base64": encoded,
  140. "trainModelScore": float(p_all[index]),
  141. })
  142. payload = {
  143. "description": "46 raw features -> standardization -> PCA(16) -> standardization -> LogisticRegression",
  144. "source": "ML1 Голос винта, Решение №2",
  145. "rawMean": mean.tolist(),
  146. "rawStd": std.tolist(),
  147. "components": components.tolist(),
  148. "projectionMean": pmean.tolist(),
  149. "projectionStd": pstd.tolist(),
  150. "coef": clf.coef_[0].tolist(),
  151. "intercept": float(clf.intercept_[0]),
  152. "classes": [0, 1],
  153. "validation": {
  154. "split": "stratified 80/20, random_state=42",
  155. "rocAuc": val_auc,
  156. "accuracy": val_acc,
  157. "trainCount": int(len(ids_train)),
  158. "validationCount": int(len(ids_valid)),
  159. },
  160. }
  161. out = Path(__file__).resolve().parent / "model.js"
  162. with out.open("w", encoding="utf-8") as f:
  163. f.write("window.GOLOS_MODEL = ")
  164. json.dump(payload, f, separators=(",", ":"), ensure_ascii=False)
  165. f.write(";\nwindow.GOLOS_SAMPLES = ")
  166. json.dump(samples, f, separators=(",", ":"), ensure_ascii=False)
  167. f.write(";\n")
  168. print(f"Saved {out}")
  169. print(f"Local holdout ROC-AUC={val_auc:.4f}; accuracy@0.5={val_acc:.4f}")
  170. if __name__ == "__main__":
  171. main()