"""Base class for all objectives."""fromabcimportABC,abstractmethodimportnumpyasnpimportpandasaspdfromevalml.problem_typesimporthandle_problem_typesfromevalml.utilsimportclassproperty
[docs]classObjectiveBase(ABC):"""Base class for all objectives."""problem_types=None@property@classmethod@abstractmethoddefname(cls):"""Returns a name describing the objective."""@property@classmethod@abstractmethoddefgreater_is_better(cls):"""Returns a boolean determining if a greater score indicates better model performance."""@property@classmethod@abstractmethoddefscore_needs_proba(cls):"""Returns a boolean determining if the score() method needs probability estimates. This should be true for objectives which work with predicted probabilities, like log loss or AUC, and false for objectives which compare predicted class labels to the actual labels, like F1 or correlation. """@property@classmethod@abstractmethoddefperfect_score(cls):"""Returns the score obtained by evaluating this objective on a perfect model."""@property@classmethod@abstractmethoddefis_bounded_like_percentage(cls):"""Returns whether this objective is bounded between 0 and 1, inclusive."""@property@classmethod@abstractmethoddefexpected_range(cls):"""Returns the expected range of the objective, which is not necessarily the possible ranges. For example, our expected R2 range is from [-1, 1], although the actual range is (-inf, 1]. """
[docs]@classmethod@abstractmethoddefobjective_function(cls,y_true,y_predicted,y_train=None,X=None,sample_weight=None,):"""Computes the relative value of the provided predictions compared to the actual labels, according a specified metric. Args: y_predicted (pd.Series): Predicted values of length [n_samples] y_true (pd.Series): Actual class labels of length [n_samples] y_train (pd.Series): Observed training values of length [n_samples] X (pd.DataFrame or np.ndarray): Extra data of shape [n_samples, n_features] necessary to calculate score sample_weight (pd.DataFrame or np.ndarray): Sample weights used in computing objective value result Returns: Numerical value used to calculate score """
@classpropertydefpositive_only(cls):"""If True, this objective is only valid for positive data. Defaults to False."""returnFalse
[docs]defscore(self,y_true,y_predicted,y_train=None,X=None,sample_weight=None):"""Returns a numerical score indicating performance based on the differences between the predicted and actual values. Args: y_predicted (pd.Series): Predicted values of length [n_samples] y_true (pd.Series): Actual class labels of length [n_samples] y_train (pd.Series): Observed training values of length [n_samples] X (pd.DataFrame or np.ndarray): Extra data of shape [n_samples, n_features] necessary to calculate score sample_weight (pd.DataFrame or np.ndarray): Sample weights used in computing objective value result Returns: score """ifXisnotNone:X=self._standardize_input_type(X)ify_trainisnotNone:y_train=self._standardize_input_type(y_train)y_true=self._standardize_input_type(y_true)y_predicted=self._standardize_input_type(y_predicted)self.validate_inputs(y_true,y_predicted)returnself.objective_function(y_true,y_predicted,y_train=y_train,X=X,sample_weight=sample_weight,)
@staticmethoddef_standardize_input_type(input_data):"""Standardize input to pandas for scoring. Args: input_data (list, pd.DataFrame, pd.Series, or np.ndarray): A matrix of predictions or predicted probabilities Returns: pd.DataFrame or pd.Series: a pd.Series, or pd.DataFrame object if predicted probabilities were provided. """ifisinstance(input_data,(pd.Series,pd.DataFrame)):returninput_dataifisinstance(input_data,list):ifisinstance(input_data[0],list):returnpd.DataFrame(input_data)returnpd.Series(input_data)ifisinstance(input_data,np.ndarray):iflen(input_data.shape)==1:returnpd.Series(input_data)returnpd.DataFrame(input_data)
[docs]defvalidate_inputs(self,y_true,y_predicted):"""Validates the input based on a few simple checks. Args: y_predicted (pd.Series, or pd.DataFrame): Predicted values of length [n_samples]. y_true (pd.Series): Actual class labels of length [n_samples]. Raises: ValueError: If the inputs are malformed. """ify_predicted.shape[0]!=y_true.shape[0]:raiseValueError("Inputs have mismatched dimensions: y_predicted has shape {}, y_true has shape {}".format(len(y_predicted),len(y_true),),)iflen(y_true)==0:raiseValueError("Length of inputs is 0")ifisinstance(y_true,pd.DataFrame):y_true=y_true.to_numpy().flatten()ifnp.isnan(y_true).any()ornp.isinf(y_true).any():raiseValueError("y_true contains NaN or infinity")ifisinstance(y_predicted,pd.DataFrame):y_predicted=y_predicted.to_numpy().flatten()ifnp.isnan(y_predicted).any()ornp.isinf(y_predicted).any():raiseValueError("y_predicted contains NaN or infinity")ifself.score_needs_probaandnp.any([(y_predicted<0)|(y_predicted>1)]):raiseValueError("y_predicted contains probability estimates not within [0, 1]",)
[docs]@classmethoddefcalculate_percent_difference(cls,score,baseline_score):"""Calculate the percent difference between scores. Args: score (float): A score. Output of the score method of this objective. baseline_score (float): A score. Output of the score method of this objective. In practice, this is the score achieved on this objective with a baseline estimator. Returns: float: The percent difference between the scores. Note that for objectives that can be interpreted as percentages, this will be the difference between the reference score and score. For all other objectives, the difference will be normalized by the reference score. """ifpd.isna(score)orpd.isna(baseline_score):returnnp.nanifnp.isclose(baseline_score-score,0,atol=1e-10):return0# Return inf when dividing by 0if(np.isclose(baseline_score,0,atol=1e-10)andnotcls.is_bounded_like_percentage):returnnp.infdecrease=Falseif(baseline_score>scoreandcls.greater_is_better)or(baseline_score<scoreandnotcls.greater_is_better):decrease=Truedifference=baseline_score-scorechange=(differenceifcls.is_bounded_like_percentageelsedifference/baseline_score)return100*(-1)**(decrease)*np.abs(change)
[docs]@classmethoddefis_defined_for_problem_type(cls,problem_type):"""Returns whether or not an objective is defined for a problem type."""returnhandle_problem_types(problem_type)incls.problem_types