X-Git-Url: https://bilbo.iut-bm.univ-fcomte.fr/and/gitweb/predictops.git/blobdiff_plain/d6469a787c80df2c938f21d4ae107b84213e238f..20a117b07643f7b3ef305d1e7a6f62f05e33698e:/predictops/learn/preprocessing.py?ds=sidebyside diff --git a/predictops/learn/preprocessing.py b/predictops/learn/preprocessing.py index 833e483..939a7fa 100644 --- a/predictops/learn/preprocessing.py +++ b/predictops/learn/preprocessing.py @@ -1,6 +1,10 @@ +from configparser import ConfigParser +from csv import DictReader +from datetime import datetime, timedelta from itertools import chain from logging import getLogger from logging.config import fileConfig +from os import listdir from pathlib import Path import numpy as np @@ -18,19 +22,22 @@ class Preprocessing: - Missing datetimes are added first with np.NaN feature values, - The dataframe is then constructed based on the filled feature dictionary, - NaN values are then filled with last known values. - ''' - def __init__(self, dict_features, - start, end, timestep, - features = None): + + def __init__(self, config_file = None, dict_features = None, features = None): ''' Constructor that defines all needed attributes and collects features. ''' - logger.info("Entering NaN values in the feature dataframe") + self._config = ConfigParser() + self._config.read(config_file) + + self._start = datetime.strptime(self._config['DATETIME']['start'], + '%m/%d/%Y %H:%M:%S') + self._end = datetime.strptime(self._config['DATETIME']['end'], + '%m/%d/%Y %H:%M:%S') + self._timestep = timedelta(hours = + self._config['DATETIME'].getfloat('hourStep')) self._dict_features = dict_features - self._start = start - self._end = end - self._timestep = timestep self._full_dict = None self._dataframe = None self._datetimes = [] @@ -41,6 +48,50 @@ class Preprocessing: else: self._features = set(chain.from_iterable([tuple(u.keys()) for u in [*dict_features.values()]])) + feature_files = Path.cwd() / 'config' / 'features' + self._features = {feat : {'numerical': False} for feat in self._features} + for feature_file in listdir(feature_files): + if feature_file.endswith('csv'): + with open(feature_files / feature_file , "r") as f: + reader = DictReader(f, delimiter=',') + typed_names = {row['name']: row['type'] for row in reader} + for feature in self._features: + if feature.split('_')[0] in typed_names: + self._features[feature]['type'] = int(typed_names[feature.split('_')[0]]) + elif feature_file.endswith('cfg'): + config = ConfigParser() + config.read(feature_files / feature_file) + for section in config: + if config.has_option(section, 'numerical'): + self._features[section]['numerical'] = config[section].getboolean('numerical') + + + + @property + def start(self): + return self._start + + @start.setter + def start(self, x): + self._start = x + + + @property + def end(self): + return self._end + + @end.setter + def end(self, x): + self._end = x + + + @property + def timestep(self): + return self._timestep + + @timestep.setter + def timestep(self, x): + self._timestep = x def _fill_dict(self): @@ -93,15 +144,43 @@ class Preprocessing: logger.info("Creating feature dataframe from feature dictionary") self._dataframe = pd.DataFrame.from_dict(self.full_dict, orient='index') - logger.info("Filling NaN values in the feature dataframe") - #TODO: add other filling methods like linear interpolation - self._dataframe = self._dataframe.fillna(method='ffill') - self._dataframe = self._dataframe.fillna(method='bfill') + logger.info("Filling NaN numerical values in the feature dataframe") + # We interpolate (linearly or with splines) only numerical columns + numerical_columns = [k for k in self._features if self._features[k]['type'] == 1 + or (self._features[k]['type'] == 3 and self._features[k]['numerical'])] + # The interpolation + if self._config['PREPROCESSING']['fill_method'] == 'propagate': + self._dataframe[numerical_columns] =\ + self._dataframe[numerical_columns].fillna(method='ffill') + elif self._config['PREPROCESSING']['fill_method'] == 'linear': + self._dataframe[numerical_columns] =\ + self._dataframe[numerical_columns].interpolate() + elif self._config['PREPROCESSING']['fill_method'] == 'spline': + self._dataframe[numerical_columns] =\ + self._dataframe[numerical_columns].interpolate(method='spline', + order=self._config['PREPROCESSING'].getint('order')) + + # For the categorical columns, NaN values are filled by duplicating + # the last known value (forward fill method) + logger.info("Filling NaN categorical values in the feature dataframe") + categorical_columns = [k for k in self._features if self._features[k]['type'] == 2 + or (self._features[k]['type'] == 3 and not self._features[k]['numerical'])] + self._dataframe[categorical_columns] =\ + self._dataframe[categorical_columns].fillna(method='ffill') + + # Uncomment this line to fill NaN values at the beginning of the + # dataframe. This may not be a good idea, especially for features + # that are available only for recent years, e.g., air quality + #self._dataframe = self._dataframe.fillna(method='bfill') + + # Dropping rows that are not related to our datetime window (start/ + # step / end) self._dataframe = self._dataframe.drop([k.to_pydatetime() for k in self._dataframe.T if k not in self._datetimes]) return self._dataframe + @dataframe.setter def dataframe(self, df): self._dataframe = df