Source code for traveltimes_prediction.models.combined_model

from sklearn import base
import collections
import numpy as np

from .base_model import BaseModel
from ..support_files.helpers import convert_params, check_params

import logging
logger = logging.getLogger('traveltimes')


[docs]class CombinedModel(base.BaseEstimator, BaseModel): """ Class - estimator. combination of multiple models. """ name = 'CombinedModel' def __init__(self, models=None, models_params=None, stacking_function=lambda x: np.mean(x)): """ Constructor. :param dict models: dictionary with keys - models` names and values - classes of models to be used. :param dict models_params: dictionary with parameters to be used for creation of individual models. {model.name: params} :param function stacking_function: function to be used for combining of the results of predictions of individual models. """ super(CombinedModel, self).__init__() self.models = models self.models_params = models_params self.stacking_function = stacking_function self.fitted_models = dict()
[docs] def fit(self, X, Y): """ Method for fitting the model. :param np.ndarray X: matrix of features - SxF :param np.ndarray Y: matrix of outputs - S :return: """ for k, v in self.models.items(): m = v(**self.models_params[k]) m.fit(X=X, Y=Y) self.fitted_models[k] = m return self
@check_params def predict(self, X): """ Method for prediction. :param np.ndarray X: array of samples (matrix of feature) for which the value is predicted. :return: list - predicted values """ results = [] for k, v in self.fitted_models.items(): res = v.predict(X=X) results.append(res) results = self._stack_results(np.array(results)) return np.array(results) if isinstance(results, collections.Iterable) else results
[docs] def dump(self): """ Method for dumping of the model. :return: dict - keys are names of attributes, values are their values """ d = dict() d['model'] = dict() d['model']['fitted_models'] = {r: self.fitted_models[r].dump() for r in self.fitted_models.keys()} d['model_type'] = self.name return d
@staticmethod
[docs] def load(model): """ Method for loading of the dumped model :param dict model: :return: obj """ inst = CombinedModel() from .create_model import create_model # Converted to int, because n JSON it has to be represented as string inst.fitted_models = {k: create_model(v) for k, v in model['fitted_models'].items()} return inst
def _stack_results(self, results): """ Method for combining the predictions` results of individual models -> producing one value. :param np.array results: array results - one array per sample :return: float or array - depends on some shape of the input """ if results.shape[0] == results.size: return self.stacking_function(results) else: return list(map(self.stacking_function, results.T))