Skip to content

Commit

Permalink
Move construction of error messages to exception classes
Browse files Browse the repository at this point in the history
  • Loading branch information
gbroques committed Feb 25, 2018
1 parent 30e6539 commit de0233d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 13 deletions.
20 changes: 20 additions & 0 deletions exceptions/exceptions.py
Expand Up @@ -4,6 +4,26 @@
class NotFittedError(ValueError):
"""Raise if predict is called before fit."""

def __init__(self, class_name):
message = self.message(class_name)
super(NotFittedError, self).__init__(message)

@staticmethod
def message(class_name):
return ("This instance of " + class_name +
" has not been fitted yet. Please call "
"'fit' before you call 'predict'.")


class ZeroObservationsError(ValueError):
"""Raise in place of ValueError when calculating natural log of zero."""

def __init__(self, value, label):
message = self.message(value, label)
super(ZeroObservationsError, self).__init__(message)

@staticmethod
def message(value, label):
return ("Value " + str(value) +
" never occurs with class " + str(label) +
". Please set use_smoothing to True in the constructor.")
15 changes: 2 additions & 13 deletions naive_bayes/naive_bayes.py
Expand Up @@ -104,23 +104,12 @@ def predict_record(self, test_record):
try:
log_likelihood[label] += log(probability)
except ValueError:
raise ZeroObservationsError(self._get_zero_observations_error_message(feature, label))
raise ZeroObservationsError(feature.value, label)
return max(log_likelihood, key=log_likelihood.get)

@staticmethod
def _get_zero_observations_error_message(feature, label):
return ("Value " + str(feature.value) +
" never occurs with class " + str(label) +
". Please set use_smoothing to True in the constructor.")

def _check_is_fitted(self):
if not self._is_fitted:
raise NotFittedError(self._get_not_fitted_error_message())

def _get_not_fitted_error_message(self):
return ("This instance of " + self.__class__.__name__ +
" has not been fitted yet. Please call "
"'fit' before you call 'predict'.")
raise NotFittedError(self.__class__.__name__)

def _get_probability(self, feature_index, feature, label):
if feature.is_continuous():
Expand Down

0 comments on commit de0233d

Please sign in to comment.