import argparse
import json
import os
import sys
from pathlib import Path
import numpy as np
import pandas as pd
def resolve_path(path: str, base_dir: str) -> str:
if os.path.isabs(path):
return path
return os.path.join(base_dir, path)
def convert_to_numeric(df: pd.DataFrame, dataset_name: str) -> pd.DataFrame:
non_numeric_cols = df.select_dtypes(exclude=[np.number]).columns.tolist()
if non_numeric_cols:
print(f"INFO: Dataset '{dataset_name}' contains non-numeric columns: "
f"{', '.join(non_numeric_cols)}")
print("Converting categorical variables to numeric representations...")
for col in non_numeric_cols:
df[col] = pd.to_numeric(df[col], errors='coerce')
if df[col].isna().any():
df[col] = df[col].astype('category').cat.codes
return df
def loess_lowess(x, y, span):
from statsmodels.nonparametric.smoothers_lowess import lowess
return lowess(y, x, frac=span, return_sorted=False)
def main():
parser = argparse.ArgumentParser(description='Generate LOESS reference values')
parser.add_argument('csv_path', nargs='?',
default='../../../datasets/csv/faithful.csv',
help='Path to CSV file')
parser.add_argument('output_dir', nargs='?',
default='../../../results/python',
help='Output directory')
args = parser.parse_args()
csv_path = args.csv_path
output_dir = args.output_dir
if not os.path.exists(csv_path):
print(f"ERROR: CSV file not found: {csv_path}")
sys.exit(1)
dataset_name = Path(csv_path).stem
print(f"Running LOESS regression on dataset: {dataset_name}")
df = pd.read_csv(csv_path)
df = convert_to_numeric(df, dataset_name)
y = df.iloc[:, 0].values
x_all = df.iloc[:, 1:].values
n_predictors = x_all.shape[1]
if n_predictors > 1:
print(f"Note: Using first predictor only (LOESS single-predictor focus)")
x = x_all[:, 0]
n = len(y)
test_configs = [
(0.25, 1),
(0.50, 1),
(0.75, 1),
]
os.makedirs(output_dir, exist_ok=True)
for span, degree in test_configs:
print(f" Testing span={span:.2f} degree={degree} (LOWESS)...")
fitted = loess_lowess(x, y, span)
method = "statsmodels_lowess"
result = {
'test': 'loess',
'method': method,
'dataset': dataset_name,
'n': int(n),
'n_predictors': 1,
'span': span,
'degree': degree,
'surface': 'direct', 'fitted': fitted.tolist(),
'y': y.tolist(),
'x': x.tolist()
}
output_file = os.path.join(output_dir, f"{dataset_name}_loess_{span:.2f}_d{degree}.json")
with open(output_file, 'w') as f:
json.dump(result, f, indent=2)
print(f" Wrote: {os.path.basename(output_file)}")
print(f"Done: {dataset_name} (3 outputs - LOWESS degree 1 only)")
if __name__ == '__main__':
main()