I have written a draft version of a data cleaner: [code] The intent is to replace…
- User
I have written a draft version of a data cleaner:
code""" Used for any data prep steps that we want to be applied to the data before training the model. Any steps added here will not be performed on new data when the model is used for prediction. """ from dataclasses import dataclass, field from typing import ClassVar import pandas as pd from ml_app.modelling.entities.data_container import DataContainer @dataclass class FeatureOutlierStats: """ Value level outlier stats for a feature. This is used to exclude values with extreme outliers on a given feature (keeping the rest of the sample unlike outlier detection done at sample level). """ min: float max: float median: float q1: float q3: float iqr: float n_values: float n_outliers: float threshold: float # values above this for this feature will be considered outliers (probably errors) @dataclass class DataCleaner(): data: DataContainer _feature_to_outlier_stats: dict[str, FeatureOutlierStats] = field(default_factory=dict) # only contains features with value outliers _cleaned_df: pd.DataFrame = field(init=False) IQR_THRESHOLD: ClassVar[float] = 20 # set high to just exclude extreme outliers that are very likely errors def __post_init__(self): self._calculate_outlier_stats() def _calculate_outlier_stats(self): for col in self.data.columns.numeric_features: if not (col.is_included_feature or col.is_result_col): continue stats = self.data.df[col.name].describe() q1 = stats['25%'] q3 = stats['75%'] med = stats['50%'] iqr = q3 - q1 threshold = med + self.IQR_THRESHOLD * iqr n_outliers = self.data.df[col.name] > threshold self._feature_to_outlier_stats[col.name] = FeatureOutlierStats( min=stats['min'], max=stats['max'], median=med, q1=q1, q3=q3, iqr=iqr, n_values=stats['count'], n_outliers=n_outliers, threshold=threshold) def get_cleaned_df(self) -> pd.DataFrame: """Replace values above threshold with NaN.""" if self._cleaned_df is not None: return self._cleaned_df cleaned_df = self.data.df.copy() for col, stats in self._feature_to_outlier_stats.items(): cleaned_df.loc[cleaned_df[col] > stats.threshold, col] = None self._cleaned_df = cleaned_df return cleaned_df Assistant
From a quick review, the code looks well-structured and efficient for its purpose. However, there are a few areas of improvement and potential issues to be aware of:
- The threshold calculation is based on IQR and median, which is a common technique for detecting outliers. However, setting a fixed IQR threshold (
IQR_THRESHOLD = 20) for all features might not be the best approach, as it assumes that the distribution and scale of all features are similar. Consider using a dynamic threshold based on the feature's distribution or implementing a method to calculate an appropriate threshold for each feature.
- The threshold calculation is based on IQR and median, which is a common technique for detecting outliers. However, setting a fixed IQR threshold (
- User
The intent is for
n_outliers = self.data.df[col.name] > thresholdto count the number above the threshold, would this work or would it return a bool array that would need converting? Assistant
Apologies for the confusion in my previous response. You are correct that the current implementation of
n_outlierswill return a boolean Series, not the count of outliers. To get the count of outliers, you can modify the line:pythonn_outliers = self.data.df[col.name] > thresholdto:
pythonn_outliers = (self.data.df[col.name] > threshold).sum()This will return the count of outliers for each feature. In the
FeatureOutlierStatsdataclass, you can then change the type ofn_outlierstoint.python@dataclass class FeatureOutlierStats: # ... n_outliers: int # ...With this change,
n_outlierswill store the actual count of outliers for each feature, which should be more useful for your purposes.- User
Is it better to replace the outliers (in numeric columns) with
Noneornp.nan? Assistant
It is better to replace the outliers in numeric columns with
np.naninstead ofNone. The main reason is thatnp.nanis a special floating-point value that represents missing data in numerical contexts, whileNoneis a general-purpose Python object that represents the absence of a value.When working with numerical data in libraries like NumPy and pandas, using
np.nanhas the following benefits:- Preserves data type: Replacing outliers with
np.nanwill preserve the data type of the column as float, which is essential for numerical operations and computations. On the other hand, usingNonecan change the data type of the column toobject, making it difficult to work with numerically. - Compatibility with libraries: Libraries like NumPy, pandas, and scikit-learn are designed to work with
np.nanfor missing values. They provide various functions and methods to handlenp.nanvalues, such as imputation techniques, interpolation, and more.
- Preserves data type: Replacing outliers with