zeechimp commited on
Commit
968c754
·
verified ·
1 Parent(s): c7d2042

Create liar_detector/feature_extractor.py

Browse files
Files changed (1) hide show
  1. liar_detector/feature_extractor.py +198 -0
liar_detector/feature_extractor.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """44-dim hand-crafted features + standardization. Pure numpy."""
2
+ from __future__ import annotations
3
+ import json
4
+ import math
5
+ import os
6
+ from typing import List, Optional, Sequence
7
+
8
+ import numpy as np
9
+
10
+ FEATURE_DIM = 44
11
+
12
+
13
+ def feature_names() -> List[str]:
14
+ return [
15
+ "mean_A", "mean_B",
16
+ "log_std_A", "log_std_B",
17
+ "skew_A", "skew_B",
18
+ "kurt_A", "kurt_B",
19
+ "abs_mean_A_minus_abs_mean_B",
20
+ "log_std_ratio_canonical",
21
+ "mean_diff", "log_std_ratio",
22
+ "skew_diff", "kurt_diff",
23
+ "skew_resid", "kurt_resid", "log_std_resid",
24
+ "ac_r_1", "ac_r_2", "ac_r_3",
25
+ "xcorr_-2", "xcorr_-1", "xcorr_0", "xcorr_1", "xcorr_2",
26
+ "resid_slope_on_A", "resid_explained_by_A",
27
+ "corr_abs_r_A", "corr_abs_r_B",
28
+ "quant_sig_A", "quant_sig_B",
29
+ "stair_A", "stair_B",
30
+ "inversion_A", "inversion_B",
31
+ "smooth_A", "smooth_B",
32
+ "zero_runs_A", "zero_runs_B",
33
+ "log_quant_ratio", "log_smooth_ratio",
34
+ "log_zero_runs_ratio",
35
+ "unique_frac_A", "unique_frac_B",
36
+ ]
37
+
38
+
39
+ def _safe_stats(x):
40
+ m = float(np.mean(x))
41
+ s = float(np.std(x)) + 1e-12
42
+ sk = float(np.mean((x - m) ** 3) / s ** 3)
43
+ ku = float(np.mean((x - m) ** 4) / s ** 4)
44
+ return m, s, sk, ku
45
+
46
+
47
+ def _autocorr(x, lag):
48
+ xc = x - x.mean()
49
+ if lag == 0:
50
+ return 1.0
51
+ v0 = float(np.mean(xc * xc)) + 1e-12
52
+ return float(np.mean(xc[lag:] * xc[:-lag])) / v0
53
+
54
+
55
+ def _crosscorr(x, y, lag):
56
+ xc, yc = x - x.mean(), y - y.mean()
57
+ if lag >= 0:
58
+ a = xc[lag:]; b = yc[:len(yc) - lag] if lag > 0 else yc
59
+ else:
60
+ a = xc[:len(xc) + lag]; b = yc[-lag:]
61
+ if len(a) < 2:
62
+ return 0.0
63
+ denom = float(np.std(a) * np.std(b)) + 1e-12
64
+ return float(np.mean(a * b)) / denom
65
+
66
+
67
+ def _corr_abs(r, x):
68
+ if len(r) < 3:
69
+ return 0.0
70
+ a, b = np.abs(r), np.abs(x)
71
+ if float(np.std(a)) < 1e-12 or float(np.std(b)) < 1e-12:
72
+ return 0.0
73
+ c = float(np.corrcoef(a, b)[0, 1])
74
+ return c if math.isfinite(c) else 0.0
75
+
76
+
77
+ def _quant_sig(x):
78
+ d = np.abs(np.diff(x))
79
+ s = float(np.std(x)) + 1e-12
80
+ return float(np.mean(d < 1e-4 * s))
81
+
82
+
83
+ def _stair(x):
84
+ d = np.diff(x)
85
+ return float(np.mean(np.abs(np.diff(np.sign(d))) > 0))
86
+
87
+
88
+ def _inversion_sig(x):
89
+ s = float(np.std(x)) + 1e-12
90
+ small = x[np.abs(x) < 0.3 * s]
91
+ if len(small) < 10:
92
+ return 0.0
93
+ return float(np.mean(small) / s)
94
+
95
+
96
+ def _smooth(x):
97
+ if len(x) < 7:
98
+ return 0.0
99
+ d2 = x[2:] - 2 * x[1:-1] + x[:-2]
100
+ s = float(np.std(x)) + 1e-12
101
+ return float(np.mean(np.abs(d2)) / s)
102
+
103
+
104
+ def _zero_runs(x):
105
+ if len(x) < 3:
106
+ return 0.0
107
+ same = (np.abs(np.diff(x)) < 1e-9).astype(int)
108
+ runs = 0
109
+ for i in range(len(same) - 1):
110
+ if same[i] and same[i + 1]:
111
+ runs += 1
112
+ return float(runs) / len(x)
113
+
114
+
115
+ def extract_features(A: np.ndarray, B: np.ndarray) -> np.ndarray:
116
+ r = A - B
117
+ mA, sA, skA, kuA = _safe_stats(A)
118
+ mB, sB, skB, kuB = _safe_stats(B)
119
+ _, sR, skR, kuR = _safe_stats(r)
120
+
121
+ Am = A - mA
122
+ rm = r - float(np.mean(r))
123
+ alpha = float(np.sum(Am * rm) / (float(np.sum(Am * Am)) + 1e-9))
124
+ resid_after_fit = rm - alpha * Am
125
+ var_r = float(np.var(r)) + 1e-12
126
+ resid_explained = 1.0 - float(np.var(resid_after_fit)) / var_r
127
+
128
+ q_A, q_B = _quant_sig(A), _quant_sig(B)
129
+ st_A, st_B = _stair(A), _stair(B)
130
+ inv_A, inv_B = _inversion_sig(A), _inversion_sig(B)
131
+ sm_A, sm_B = _smooth(A), _smooth(B)
132
+ zr_A, zr_B = _zero_runs(A), _zero_runs(B)
133
+
134
+ return np.array([
135
+ mA, mB, math.log(sA + 1e-9), math.log(sB + 1e-9),
136
+ skA, skB, kuA, kuB,
137
+ abs(mA) - abs(mB),
138
+ math.log(sA + 1e-9) - math.log(sB + 1e-9),
139
+ mB - mA,
140
+ math.log(sB + 1e-9) - math.log(sA + 1e-9),
141
+ skB - skA, kuB - kuA,
142
+ skR, kuR, math.log(sR + 1e-9),
143
+ _autocorr(r, 1), _autocorr(r, 2), _autocorr(r, 3),
144
+ _crosscorr(A, B, -2), _crosscorr(A, B, -1), _crosscorr(A, B, 0),
145
+ _crosscorr(A, B, 1), _crosscorr(A, B, 2),
146
+ alpha, resid_explained,
147
+ _corr_abs(r, A), _corr_abs(r, B),
148
+ q_A, q_B, st_A, st_B, inv_A, inv_B,
149
+ sm_A, sm_B, zr_A, zr_B,
150
+ math.log(q_B + 1e-9) - math.log(q_A + 1e-9),
151
+ math.log(sm_B + 1e-9) - math.log(sm_A + 1e-9),
152
+ math.log(zr_B + 1e-9) - math.log(zr_A + 1e-9),
153
+ float(len(np.unique(np.round(A, 3))) / len(A)),
154
+ float(len(np.unique(np.round(B, 3))) / len(B)),
155
+ ], dtype=np.float32)
156
+
157
+
158
+ class LiarDetectorFeatureExtractor:
159
+ """Holds normalization stats. Save/load next to the model."""
160
+
161
+ def __init__(self,
162
+ mean: Optional[Sequence[float]] = None,
163
+ std: Optional[Sequence[float]] = None):
164
+ self.mean = (np.zeros(FEATURE_DIM, dtype=np.float32)
165
+ if mean is None else np.asarray(mean, dtype=np.float32))
166
+ self.std = (np.ones(FEATURE_DIM, dtype=np.float32)
167
+ if std is None else np.asarray(std, dtype=np.float32))
168
+ self.std = np.where(self.std < 1e-9, 1.0, self.std)
169
+
170
+ def fit(self, features: np.ndarray) -> "LiarDetectorFeatureExtractor":
171
+ self.mean = features.mean(axis=0).astype(np.float32)
172
+ std = features.std(axis=0).astype(np.float32)
173
+ self.std = np.where(std < 1e-9, 1.0, std)
174
+ return self
175
+
176
+ def transform(self, features: np.ndarray) -> np.ndarray:
177
+ return ((features - self.mean) / self.std).astype(np.float32)
178
+
179
+ def __call__(self, A: np.ndarray, B: np.ndarray) -> np.ndarray:
180
+ return self.transform(extract_features(A, B))
181
+
182
+ def save_pretrained(self, save_directory: str) -> str:
183
+ os.makedirs(save_directory, exist_ok=True)
184
+ path = os.path.join(save_directory, "feature_extractor.json")
185
+ with open(path, "w") as f:
186
+ json.dump({
187
+ "mean": self.mean.tolist(),
188
+ "std": self.std.tolist(),
189
+ "feature_names": feature_names(),
190
+ }, f, indent=2)
191
+ return save_directory
192
+
193
+ @classmethod
194
+ def from_pretrained(cls, load_directory: str) -> "LiarDetectorFeatureExtractor":
195
+ path = os.path.join(load_directory, "feature_extractor.json")
196
+ with open(path) as f:
197
+ d = json.load(f)
198
+ return cls(mean=d["mean"], std=d["std"])