Spaces:
Sleeping
Sleeping
File size: 4,463 Bytes
bc308f6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | import numpy as np
import pandas as pd
from sklearn.preprocessing import QuantileTransformer
class DomainNormalizer:
"""Performs domain-conditioned feature distribution normalization.
Fits domain-specific QuantileTransformers to map feature distributions to standard normal,
reducing cross-domain feature separability.
"""
def __init__(self, n_quantiles=50):
self.n_quantiles = n_quantiles
self.transformers = {} # domain -> feature -> transformer
self.global_transformers = {} # feature -> transformer (fallback)
self.features = []
def fit(self, df, features):
"""Fits transformers on the training dataframe by domain."""
self.features = list(features)
# 1. Fit Global fallback transformers for all features
for feat in self.features:
col_data = df[feat].dropna().values
if len(col_data) > 0:
qt = QuantileTransformer(
n_quantiles=min(self.n_quantiles, len(col_data)),
output_distribution='normal',
random_state=42
)
qt.fit(col_data.reshape(-1, 1))
self.global_transformers[feat] = qt
else:
self.global_transformers[feat] = None
# 2. Fit Domain-specific transformers
domains = df["dataset_source"].unique()
for dom in domains:
self.transformers[dom] = {}
df_dom = df[df["dataset_source"] == dom]
for feat in self.features:
col_data = df_dom[feat].dropna().values
if len(col_data) > 5: # Need enough data points to fit quantile transformer
qt = QuantileTransformer(
n_quantiles=min(self.n_quantiles, len(col_data)),
output_distribution='normal',
random_state=42
)
qt.fit(col_data.reshape(-1, 1))
self.transformers[dom][feat] = qt
else:
self.transformers[dom][feat] = None
def transform(self, df):
"""Applies normalization on features in the dataframe relative to their domain."""
df_norm = df.copy()
# Cast feature columns to float to prevent Pandas type errors when writing float values to int columns
for feat in self.features:
if feat in df_norm.columns:
df_norm[feat] = df_norm[feat].astype(float)
# Apply transformation row-by-row or by grouping domains
# Grouping is much faster in pandas
for dom, group in df_norm.groupby("dataset_source", group_keys=False):
dom_idx = group.index
for feat in self.features:
# Get transformer
qt = self.transformers.get(dom, {}).get(feat)
if qt is None:
qt = self.global_transformers.get(feat)
if qt is not None:
# Retrieve non-null values
non_null_mask = df_norm.loc[dom_idx, feat].notna()
if non_null_mask.any():
vals = df_norm.loc[dom_idx[non_null_mask], feat].values.reshape(-1, 1)
transformed = qt.transform(vals).flatten()
df_norm.loc[dom_idx[non_null_mask], feat] = transformed
# Fill any remaining NaNs (for safety/downstream models)
# We don't impute here, we let the classifier or downstream models handle it, but we can fillna with 0.0 (since mean of normal is 0.0)
# Let's keep NaNs as NaNs to let XGBoost handle them natively, but for MLP we will impute with 0.0.
return df_norm
def transform_single(self, feature_dict, domain):
"""Transforms a single feature dictionary for online inference."""
res = feature_dict.copy()
for feat in self.features:
if feat in res and res[feat] is not None and not pd.isna(res[feat]):
qt = self.transformers.get(domain, {}).get(feat)
if qt is None:
qt = self.global_transformers.get(feat)
if qt is not None:
val = np.array([[float(res[feat])]])
res[feat] = float(qt.transform(val)[0, 0])
return res
|