dna_noc / src /data /05_enhanced_feature_engineering.py
manhngvu's picture
๐ŸŽ‰ Update: Optimized models with F1=0.7135 + Complete research report + Analysis (2026-05-08)
4636192 verified
Raw
History Blame Contribute Delete
8.88 kB
"""Enhanced Feature Engineering: Add domain-specific DNA features."""
import pandas as pd
import numpy as np
from pathlib import Path
import json
import warnings
warnings.filterwarnings('ignore')
ROOT = Path(__file__).parent.parent.parent
RECONSTRUCTED_DIR = ROOT / "data/reconstructed"
RAW_DATA_DIR = ROOT / "data/PROVEDIt_1-5-Person CSVs UnFiltered"
OUTPUT_DIR = ROOT / "data/reconstructed/production"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
def load_all_sample_data():
"""Load all sample labels from both phases."""
print("๐Ÿ“– Loading all sample labels...")
labels_df = pd.read_csv(RECONSTRUCTED_DIR / "sample_labels.csv")
print(f"โœ… Loaded {len(labels_df)} total samples")
# Split by study
rd14_samples = labels_df[labels_df['study_id'] == 'RD14-0003'].copy()
rd12_samples = labels_df[labels_df['study_id'] == 'RD12-0002'].copy()
print(f" RD14: {len(rd14_samples)} samples")
print(f" RD12: {len(rd12_samples)} samples")
return labels_df, rd14_samples, rd12_samples
def extract_peak_features_enhanced(sample_file, raw_data_dir):
"""Extract enhanced peak features from raw CSV."""
features = {}
try:
# Find the CSV file
found_files = list(raw_data_dir.rglob(f"{sample_file}"))
if not found_files:
return features
csv_path = found_files[0]
df = pd.read_csv(csv_path)
# Extract statistics per marker
for _, row in df.iterrows():
marker = row['Marker']
# Extract all heights and sizes
heights = []
sizes = []
alleles = []
for i in range(1, 101):
height_col = f'Height {i}'
size_col = f'Size {i}'
allele_col = f'Allele {i}'
if height_col in df.columns:
height = row[height_col]
if pd.notna(height) and height != '' and str(height).upper() != 'NAN':
try:
h = float(height)
if h > 0:
heights.append(h)
except:
pass
if size_col in df.columns and len(heights) > 0:
size = row[size_col]
if pd.notna(size) and size != '':
try:
sizes.append(float(size))
except:
pass
if allele_col in df.columns:
allele = str(row[allele_col]).strip()
if allele and allele.upper() != 'OL' and allele != 'nan':
alleles.append(allele)
if heights:
# Basic features
features[f"{marker}_peak_count"] = len(heights)
features[f"{marker}_max_height"] = max(heights)
features[f"{marker}_sum_height"] = sum(heights)
features[f"{marker}_mean_height"] = np.mean(heights)
features[f"{marker}_std_height"] = np.std(heights) if len(heights) > 1 else 0
# Domain-specific: Peak height ratio (peak 1 / peak 2)
if len(heights) >= 2:
sorted_heights = sorted(heights, reverse=True)
features[f"{marker}_peak_ratio"] = sorted_heights[0] / sorted_heights[1] if sorted_heights[1] > 0 else 0
# Allele balance: ratio of two highest peaks
features[f"{marker}_allele_balance"] = min(sorted_heights[0], sorted_heights[1]) / max(sorted_heights[0], sorted_heights[1]) if sorted_heights[0] > 0 else 0
# Domain-specific: Homozygosity indicator
if len(alleles) == 2:
features[f"{marker}_is_homozygous"] = 1 if alleles[0] == alleles[1] else 0
else:
features[f"{marker}_is_homozygous"] = 0
# Domain-specific: Peak distribution (coefficient of variation)
if len(heights) > 1:
features[f"{marker}_cv_heights"] = np.std(heights) / np.mean(heights) if np.mean(heights) > 0 else 0
except Exception as e:
pass
return features
def build_enhanced_feature_matrix(labels_df):
"""Build feature matrix with domain-specific features."""
print("\n๐Ÿ› ๏ธ Building enhanced feature matrix with domain features...")
features_list = []
for idx, row in labels_df.iterrows():
if idx % 100 == 0:
print(f" Processing {idx}/{len(labels_df)}...", end='\r')
sample_file = row['sample_file']
# Basic info
feature_dict = {
'sample_file': sample_file,
'study_id': row['study_id'],
'kit': row['kit'],
'num_contributors': row['num_contributors'],
'num_known': row['num_known'],
'num_unknown': row['num_unknown'],
'unknown_present': row['unknown_present'],
}
# Extract enhanced peak features
peak_features = extract_peak_features_enhanced(sample_file, RAW_DATA_DIR)
feature_dict.update(peak_features)
features_list.append(feature_dict)
feature_df = pd.DataFrame(features_list)
# Fill NaN with 0
feature_df = feature_df.fillna(0)
# Filter: Keep only samples with minimum markers
marker_threshold = 15
marker_cols = [c for c in feature_df.columns if '_peak_count' in c]
feature_df['num_markers_detected'] = (feature_df[marker_cols] > 0).sum(axis=1)
print(f"\n Total features before filtering: {len(feature_df)}")
print(f" Min marker threshold: {marker_threshold}")
filtered_df = feature_df[feature_df['num_markers_detected'] >= marker_threshold].copy()
print(f" Total features after filtering: {len(filtered_df)}")
print(f" Feature columns: {len(filtered_df.columns)}")
return filtered_df
def split_by_study(feature_df):
"""Split dataset by study."""
print("\n๐Ÿ“Š Splitting by study...")
rd14_df = feature_df[feature_df['study_id'] == 'RD14-0003'].copy()
rd12_df = feature_df[feature_df['study_id'] == 'RD12-0002'].copy()
print(f" RD14: {len(rd14_df)} samples")
print(f" RD12: {len(rd12_df)} samples")
print(f" Combined: {len(feature_df)} samples")
return rd14_df, rd12_df, feature_df
def save_enhanced_features(rd14_df, rd12_df, combined_df):
"""Save enhanced feature matrices."""
print("\n๐Ÿ’พ Saving enhanced feature matrices...")
# Save by study
rd14_df.to_csv(OUTPUT_DIR / "rd14_enhanced_features.csv", index=False)
rd12_df.to_csv(OUTPUT_DIR / "rd12_enhanced_features.csv", index=False)
# Save combined
combined_df.to_csv(OUTPUT_DIR / "combined_enhanced_features.csv", index=False)
# Save summary (convert numpy types to python native types)
summary = {
"rd14": {
"total_samples": int(len(rd14_df)),
"num_features": int(len(rd14_df.columns)),
"unknown_present_0": int((rd14_df['unknown_present'] == 0).sum()),
"unknown_present_1": int((rd14_df['unknown_present'] == 1).sum()),
},
"rd12": {
"total_samples": int(len(rd12_df)),
"num_features": int(len(rd12_df.columns)),
"unknown_present_0": int((rd12_df['unknown_present'] == 0).sum()),
"unknown_present_1": int((rd12_df['unknown_present'] == 1).sum()),
},
"combined": {
"total_samples": int(len(combined_df)),
"num_features": int(len(combined_df.columns)),
"unknown_present_0": int((combined_df['unknown_present'] == 0).sum()),
"unknown_present_1": int((combined_df['unknown_present'] == 1).sum()),
}
}
with open(OUTPUT_DIR / "enhanced_features_summary.json", "w") as f:
json.dump(summary, f, indent=2)
print(f" โœ… RD14: {OUTPUT_DIR}/rd14_enhanced_features.csv")
print(f" โœ… RD12: {OUTPUT_DIR}/rd12_enhanced_features.csv")
print(f" โœ… Combined: {OUTPUT_DIR}/combined_enhanced_features.csv")
return summary
def main():
print("=" * 80)
print("๐Ÿ”ง STEP 5: Enhanced Feature Engineering")
print("=" * 80)
# Load data
labels_df, rd14_samples, rd12_samples = load_all_sample_data()
# Build enhanced features
feature_df = build_enhanced_feature_matrix(labels_df)
# Split by study
rd14_df, rd12_df, combined_df = split_by_study(feature_df)
# Save
summary = save_enhanced_features(rd14_df, rd12_df, combined_df)
print("\n" + "=" * 80)
print("โœ… STEP 5 COMPLETE!")
print("=" * 80)
print("\n๐Ÿ“Š Feature Engineering Summary:")
print(json.dumps(summary, indent=2))
print(f"\nNext step: Light hyperparameter tuning with 5-fold CV")
if __name__ == "__main__":
main()