adjusted the profiling pipelines: multipliers & (potential) founders, explorative analyses
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
"""Multivariate outlier detection for the RQ1 feature set.
|
||||
|
||||
Two stages: a sanity ceiling (>5,000 lifetime publications or patents) to drop
|
||||
flagrant name-collision aggregates, then an Isolation Forest in log-space over
|
||||
the full numeric feature set. Why not a single threshold:
|
||||
docs/DESIGN_NOTES.md, "outliers.py".
|
||||
"""
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.ensemble import IsolationForest
|
||||
|
||||
from . import config
|
||||
|
||||
SANITY_CEILING = 5000 # any one individual having more than this is implausible
|
||||
OUTLIER_CONTAMINATION = 0.01 # drop the ~1% most anomalous *remaining* rows
|
||||
|
||||
_OUTLIER_COLUMNS = [c for c in config.RQ1_NUMERIC_COLUMNS if "_year" not in c]
|
||||
|
||||
|
||||
def flag_outliers(df, contamination=OUTLIER_CONTAMINATION, random_state=config.RANDOM_STATE):
|
||||
"""Return a boolean Series (True = flagged as an outlier), combining the
|
||||
sanity-ceiling and Isolation Forest stages described in the module docstring."""
|
||||
sanity_flagged = (
|
||||
pd.to_numeric(df["publications"], errors="coerce").fillna(0) > SANITY_CEILING
|
||||
) | (pd.to_numeric(df["patents"], errors="coerce").fillna(0) > SANITY_CEILING)
|
||||
|
||||
remaining = df.loc[~sanity_flagged]
|
||||
X = remaining[_OUTLIER_COLUMNS].apply(pd.to_numeric, errors="coerce").fillna(0)
|
||||
X = np.log1p(X.clip(lower=0))
|
||||
model = IsolationForest(
|
||||
n_estimators=300, contamination=contamination, random_state=random_state
|
||||
)
|
||||
labels = model.fit_predict(X) # -1 = outlier, 1 = inlier
|
||||
iforest_flagged = pd.Series(labels == -1, index=remaining.index)
|
||||
|
||||
flagged = sanity_flagged.copy()
|
||||
flagged.loc[iforest_flagged.index] = flagged.loc[iforest_flagged.index] | iforest_flagged
|
||||
return flagged
|
||||
Reference in New Issue
Block a user