my_project.preprocessing

Dataset preprocessing utilities.

  1"""Dataset preprocessing utilities."""
  2
  3from pathlib import Path
  4
  5import pandas as pd
  6from sklearn.model_selection import train_test_split
  7
  8from my_project.fileManager import FileManager
  9from my_project.download_data import download_dataset
 10
 11
 12PROJECT_ROOT = Path(__file__).resolve().parent.parent
 13
 14RAW_FILE = PROJECT_ROOT / "data" / "raw" / "automobile_dataset"
 15PROCESSED_TRAIN_FILE = PROJECT_ROOT / "data" / "processed" / "automobile_dataset"
 16PROCESSED_TEST_FILE = PROJECT_ROOT / "data" / "processed" / "automobile_test"
 17
 18
 19def preprocess_dataset(df: pd.DataFrame) -> pd.DataFrame:
 20    """
 21    Cleans and encodes the automobile dataset.
 22        
 23    Parameters
 24    ----------
 25    df : pd.DataFrame
 26        Dataframe with the unprocessed data
 27        
 28    Returns
 29    -------
 30    df : pd.DataFrame
 31        Dataframe with the preprocessed data
 32    """
 33
 34    # Optimize numerical types
 35    for column in df.columns:
 36
 37        if df[column].dtype == "int64":
 38            df[column] = pd.to_numeric(
 39                df[column],
 40                downcast="integer"
 41            )
 42
 43        elif df[column].dtype == "float64":
 44            df[column] = pd.to_numeric(
 45                df[column],
 46                downcast="float"
 47            )
 48
 49        elif df[column].dtype == "object":
 50            df[column] = df[column].astype("category")
 51
 52    # Remove rows containing missing values
 53    df = df.dropna().copy()
 54
 55    # Encode service history
 56    service_mapping = {
 57        "No Service": 0,
 58        "Partial Service": 1,
 59        "Full Service": 2
 60    }
 61
 62    df["Service_History"] = df["Service_History"].map(
 63        service_mapping
 64    )
 65
 66    # One-hot encode categorical columns
 67    categorical_columns = [
 68        "Make",
 69        "Model",
 70        "Fuel_Type",
 71        "Transmission",
 72        "Color",
 73        "Body_Type",
 74        "Drivetrain",
 75        "Location"
 76    ]
 77
 78    df = pd.get_dummies(
 79        df,
 80        columns=categorical_columns,
 81        dtype=int
 82    )
 83
 84    return df
 85
 86
 87def prepare_dataset() -> tuple[pd.DataFrame, pd.DataFrame]:
 88    """
 89    Downloads, preprocesses and saves the dataset.
 90        
 91    Returns
 92    -------
 93    train_df : pd.DataFrame
 94        Dataframe with the preprocessed train data
 95    test_df : pd.DataFrame
 96        Dataframe with the preprocessed test data
 97    """
 98
 99    raw_csv = PROJECT_ROOT / "data" / "raw" / "automobile_dataset.csv"
100
101    if not raw_csv.exists():
102        download_dataset()
103
104    fm = FileManager()
105    fm.set_format("csv")
106
107    df = fm.read(str(RAW_FILE))
108
109    df = preprocess_dataset(df)
110
111    train_df, test_df = train_test_split(
112        df,
113        test_size=0.2,
114        random_state=22
115    )
116
117    PROCESSED_TRAIN_FILE.parent.mkdir(
118        parents=True,
119        exist_ok=True
120    )
121
122    fm.set_format("parquet")
123
124    fm.write(
125        train_df,
126        str(PROCESSED_TRAIN_FILE)
127    )
128
129    fm.write(
130        test_df,
131        str(PROCESSED_TEST_FILE)
132    )
133
134    return train_df, test_df
135
136
137if __name__ == "__main__":
138    prepare_dataset()
PROJECT_ROOT = PosixPath('/home/alumno/Desktop/git_repositories/SDOML-project')
RAW_FILE = PosixPath('/home/alumno/Desktop/git_repositories/SDOML-project/data/raw/automobile_dataset')
PROCESSED_TRAIN_FILE = PosixPath('/home/alumno/Desktop/git_repositories/SDOML-project/data/processed/automobile_dataset')
PROCESSED_TEST_FILE = PosixPath('/home/alumno/Desktop/git_repositories/SDOML-project/data/processed/automobile_test')
def preprocess_dataset(df: pandas.core.frame.DataFrame) -> pandas.core.frame.DataFrame:
20def preprocess_dataset(df: pd.DataFrame) -> pd.DataFrame:
21    """
22    Cleans and encodes the automobile dataset.
23        
24    Parameters
25    ----------
26    df : pd.DataFrame
27        Dataframe with the unprocessed data
28        
29    Returns
30    -------
31    df : pd.DataFrame
32        Dataframe with the preprocessed data
33    """
34
35    # Optimize numerical types
36    for column in df.columns:
37
38        if df[column].dtype == "int64":
39            df[column] = pd.to_numeric(
40                df[column],
41                downcast="integer"
42            )
43
44        elif df[column].dtype == "float64":
45            df[column] = pd.to_numeric(
46                df[column],
47                downcast="float"
48            )
49
50        elif df[column].dtype == "object":
51            df[column] = df[column].astype("category")
52
53    # Remove rows containing missing values
54    df = df.dropna().copy()
55
56    # Encode service history
57    service_mapping = {
58        "No Service": 0,
59        "Partial Service": 1,
60        "Full Service": 2
61    }
62
63    df["Service_History"] = df["Service_History"].map(
64        service_mapping
65    )
66
67    # One-hot encode categorical columns
68    categorical_columns = [
69        "Make",
70        "Model",
71        "Fuel_Type",
72        "Transmission",
73        "Color",
74        "Body_Type",
75        "Drivetrain",
76        "Location"
77    ]
78
79    df = pd.get_dummies(
80        df,
81        columns=categorical_columns,
82        dtype=int
83    )
84
85    return df

Cleans and encodes the automobile dataset.

Parameters
  • df (pd.DataFrame): Dataframe with the unprocessed data
Returns
  • df (pd.DataFrame): Dataframe with the preprocessed data
def prepare_dataset() -> tuple[pandas.core.frame.DataFrame, pandas.core.frame.DataFrame]:
 88def prepare_dataset() -> tuple[pd.DataFrame, pd.DataFrame]:
 89    """
 90    Downloads, preprocesses and saves the dataset.
 91        
 92    Returns
 93    -------
 94    train_df : pd.DataFrame
 95        Dataframe with the preprocessed train data
 96    test_df : pd.DataFrame
 97        Dataframe with the preprocessed test data
 98    """
 99
100    raw_csv = PROJECT_ROOT / "data" / "raw" / "automobile_dataset.csv"
101
102    if not raw_csv.exists():
103        download_dataset()
104
105    fm = FileManager()
106    fm.set_format("csv")
107
108    df = fm.read(str(RAW_FILE))
109
110    df = preprocess_dataset(df)
111
112    train_df, test_df = train_test_split(
113        df,
114        test_size=0.2,
115        random_state=22
116    )
117
118    PROCESSED_TRAIN_FILE.parent.mkdir(
119        parents=True,
120        exist_ok=True
121    )
122
123    fm.set_format("parquet")
124
125    fm.write(
126        train_df,
127        str(PROCESSED_TRAIN_FILE)
128    )
129
130    fm.write(
131        test_df,
132        str(PROCESSED_TEST_FILE)
133    )
134
135    return train_df, test_df

Downloads, preprocesses and saves the dataset.

Returns
  • train_df (pd.DataFrame): Dataframe with the preprocessed train data
  • test_df (pd.DataFrame): Dataframe with the preprocessed test data