File size: 1,484 Bytes
0ddcb86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Feature preprocessing pipeline.

Numerical features pass through StandardScaler; categorical features
(road_type, vehicle_type) one-hot encoded. The whole ColumnTransformer is
saved with joblib so inference uses identical encoding to training.
"""
from __future__ import annotations
from typing import List, Tuple
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder


NUMERIC_FEATURES: List[str] = [
    "distance_km",
    "nominal_speed_kmh",
    "turns",
    "turns_per_km",
    "traffic_level",
    "road_quality",
    "hour_of_day",
    "day_of_week",
    "weather_severity",
    "detour_ratio",
]
CATEGORICAL_FEATURES: List[str] = ["road_type", "vehicle_type"]
ALL_FEATURES: List[str] = NUMERIC_FEATURES + CATEGORICAL_FEATURES


def build_preprocessor() -> ColumnTransformer:
    return ColumnTransformer(
        transformers=[
            ("num", StandardScaler(), NUMERIC_FEATURES),
            ("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), CATEGORICAL_FEATURES),
        ],
        remainder="drop",
    )


def features_to_dataframe(rows: List[dict]) -> pd.DataFrame:
    df = pd.DataFrame(rows)
    for col in NUMERIC_FEATURES:
        if col not in df.columns:
            df[col] = 0.0
    for col in CATEGORICAL_FEATURES:
        if col not in df.columns:
            df[col] = "mixed" if col == "road_type" else "car"
    return df[ALL_FEATURES]