Skip to content

Model elasticnet regressor

ModelElasticNetRegressor

Bases: ModelRegressorMixin, ModelPipeline

Elastic Net model for regression

Source code in template_num/models_training/regressors/models_sklearn/model_elasticnet_regressor.py
class ModelElasticNetRegressor(ModelRegressorMixin, ModelPipeline):
    '''Elastic Net model for regression'''

    _default_name = 'model_elasticnet_regressor'

    def __init__(self, elasticnet_params: Union[dict, None] = None, **kwargs) -> None:
        '''Initialization of the class (see ModelPipeline, ModelClass & ModelRegressorMixin for more arguments)

        Kwargs:
            elasticnet_params (dict) : Parameters for the Elastic Net
        '''
        # Init.
        super().__init__(**kwargs)

        # Get logger (must be done after super init)
        self.logger = logging.getLogger(__name__)

        # Manage model
        if elasticnet_params is None:
            elasticnet_params = {}
        self.elasticnet = ElasticNet(**elasticnet_params)
        # We define a pipeline in order to be compatible with other models
        self.pipeline = Pipeline([('elasticnet', self.elasticnet)])

    def reload_from_standalone(self, **kwargs) -> None:
        '''Reloads a model from its configuration and "standalones" files
        - /!\\ Experimental /!\\ -

        Kwargs:
            configuration_path (str): Path to configuration file
            sklearn_pipeline_path (str): Path to standalone pipeline
            preprocess_pipeline_path (str): Path to preprocess pipeline
        Raises:
            ValueError: If configuration_path is None
            ValueError: If sklearn_pipeline_path is None
            ValueError: If preprocess_pipeline_path is None
            FileNotFoundError: If the object configuration_path is not an existing file
            FileNotFoundError: If the object sklearn_pipeline_path is not an existing file
            FileNotFoundError: If the object preprocess_pipeline_path is not an existing file
        '''
        # Retrieve args
        configuration_path = kwargs.get('configuration_path', None)
        sklearn_pipeline_path = kwargs.get('sklearn_pipeline_path', None)
        preprocess_pipeline_path = kwargs.get('preprocess_pipeline_path', None)

        # Checks
        if configuration_path is None:
            raise ValueError("The argument configuration_path can't be None")
        if sklearn_pipeline_path is None:
            raise ValueError("The argument sklearn_pipeline_path can't be None")
        if preprocess_pipeline_path is None:
            raise ValueError("The argument preprocess_pipeline_path can't be None")
        if not os.path.exists(configuration_path):
            raise FileNotFoundError(f"The file {configuration_path} does not exist")
        if not os.path.exists(sklearn_pipeline_path):
            raise FileNotFoundError(f"The file {sklearn_pipeline_path} does not exist")
        if not os.path.exists(preprocess_pipeline_path):
            raise FileNotFoundError(f"The file {preprocess_pipeline_path} does not exist")

        # Load confs
        with open(configuration_path, 'r', encoding='utf-8') as f:
            configs = json.load(f)

        # Set class vars
        # self.model_name = # Keep the created name
        # self.model_dir = # Keep the created folder
        self.nb_fit = configs.get('nb_fit', 1)  # Consider one unique fit by default
        self.trained = configs.get('trained', True)  # Consider trained by default
        # Try to read the following attributes from configs and, if absent, keep the current one
        for attribute in ['model_type', 'x_col', 'y_col', 'columns_in', 'mandatory_columns',
                          'level_save']:
            setattr(self, attribute, configs.get(attribute, getattr(self, attribute)))

        # Reload pipeline model
        with open(sklearn_pipeline_path, 'rb') as f:
            self.pipeline = pickle.load(f)

        # Reload pipeline elements
        self.elasticnet = self.pipeline['elasticnet']

        # Reload pipeline preprocessing
        with open(preprocess_pipeline_path, 'rb') as f:
            self.preprocess_pipeline = pickle.load(f)

__init__(elasticnet_params=None, **kwargs)

Initialization of the class (see ModelPipeline, ModelClass & ModelRegressorMixin for more arguments)

Kwargs

elasticnet_params (dict) : Parameters for the Elastic Net

Source code in template_num/models_training/regressors/models_sklearn/model_elasticnet_regressor.py
def __init__(self, elasticnet_params: Union[dict, None] = None, **kwargs) -> None:
    '''Initialization of the class (see ModelPipeline, ModelClass & ModelRegressorMixin for more arguments)

    Kwargs:
        elasticnet_params (dict) : Parameters for the Elastic Net
    '''
    # Init.
    super().__init__(**kwargs)

    # Get logger (must be done after super init)
    self.logger = logging.getLogger(__name__)

    # Manage model
    if elasticnet_params is None:
        elasticnet_params = {}
    self.elasticnet = ElasticNet(**elasticnet_params)
    # We define a pipeline in order to be compatible with other models
    self.pipeline = Pipeline([('elasticnet', self.elasticnet)])

reload_from_standalone(**kwargs)

Reloads a model from its configuration and "standalones" files - /! Experimental /! -

Kwargs

configuration_path (str): Path to configuration file sklearn_pipeline_path (str): Path to standalone pipeline preprocess_pipeline_path (str): Path to preprocess pipeline

Raises: ValueError: If configuration_path is None ValueError: If sklearn_pipeline_path is None ValueError: If preprocess_pipeline_path is None FileNotFoundError: If the object configuration_path is not an existing file FileNotFoundError: If the object sklearn_pipeline_path is not an existing file FileNotFoundError: If the object preprocess_pipeline_path is not an existing file

Source code in template_num/models_training/regressors/models_sklearn/model_elasticnet_regressor.py
def reload_from_standalone(self, **kwargs) -> None:
    '''Reloads a model from its configuration and "standalones" files
    - /!\\ Experimental /!\\ -

    Kwargs:
        configuration_path (str): Path to configuration file
        sklearn_pipeline_path (str): Path to standalone pipeline
        preprocess_pipeline_path (str): Path to preprocess pipeline
    Raises:
        ValueError: If configuration_path is None
        ValueError: If sklearn_pipeline_path is None
        ValueError: If preprocess_pipeline_path is None
        FileNotFoundError: If the object configuration_path is not an existing file
        FileNotFoundError: If the object sklearn_pipeline_path is not an existing file
        FileNotFoundError: If the object preprocess_pipeline_path is not an existing file
    '''
    # Retrieve args
    configuration_path = kwargs.get('configuration_path', None)
    sklearn_pipeline_path = kwargs.get('sklearn_pipeline_path', None)
    preprocess_pipeline_path = kwargs.get('preprocess_pipeline_path', None)

    # Checks
    if configuration_path is None:
        raise ValueError("The argument configuration_path can't be None")
    if sklearn_pipeline_path is None:
        raise ValueError("The argument sklearn_pipeline_path can't be None")
    if preprocess_pipeline_path is None:
        raise ValueError("The argument preprocess_pipeline_path can't be None")
    if not os.path.exists(configuration_path):
        raise FileNotFoundError(f"The file {configuration_path} does not exist")
    if not os.path.exists(sklearn_pipeline_path):
        raise FileNotFoundError(f"The file {sklearn_pipeline_path} does not exist")
    if not os.path.exists(preprocess_pipeline_path):
        raise FileNotFoundError(f"The file {preprocess_pipeline_path} does not exist")

    # Load confs
    with open(configuration_path, 'r', encoding='utf-8') as f:
        configs = json.load(f)

    # Set class vars
    # self.model_name = # Keep the created name
    # self.model_dir = # Keep the created folder
    self.nb_fit = configs.get('nb_fit', 1)  # Consider one unique fit by default
    self.trained = configs.get('trained', True)  # Consider trained by default
    # Try to read the following attributes from configs and, if absent, keep the current one
    for attribute in ['model_type', 'x_col', 'y_col', 'columns_in', 'mandatory_columns',
                      'level_save']:
        setattr(self, attribute, configs.get(attribute, getattr(self, attribute)))

    # Reload pipeline model
    with open(sklearn_pipeline_path, 'rb') as f:
        self.pipeline = pickle.load(f)

    # Reload pipeline elements
    self.elasticnet = self.pipeline['elasticnet']

    # Reload pipeline preprocessing
    with open(preprocess_pipeline_path, 'rb') as f:
        self.preprocess_pipeline = pickle.load(f)