MCPcopy Index your code
hub / github.com/clips/pattern / classify

Method classify

pattern/vector/__init__.py:2007–2044  ·  view source on GitHub ↗

Returns the type with the highest probability for the given document. If the classifier has been trained on LSA concept vectors you need to supply LSA.transform(document).

(self, document, discrete=True)

Source from the content-addressed store, hash-verified

2005 self._likelihood[type][f] = self._likelihood[type].get(f, 0) + w
2006
2007 def classify(self, document, discrete=True):
2008 """ Returns the type with the highest probability for the given document.
2009 If the classifier has been trained on LSA concept vectors
2010 you need to supply LSA.transform(document).
2011 """
2012 # Given red & round, what is the likelihood that it is an apple?
2013 # p = p(red|apple) * p(round|apple) * p(apple) / (p(red) * p(round))
2014 # The multiplication can cause underflow so we use log() instead.
2015 # For unknown features, we smoothen with an alpha value.
2016 v = self._vector(document)[1]
2017 n = float(sum(self._classes.itervalues()))
2018 p = defaultdict(float)
2019 for type in self._classes:
2020 if self._method == MULTINOMIAL:
2021 d = float(sum(self._likelihood[type].itervalues()))
2022 if self._method == BERNOUILLI:
2023 d = float(self._classes[type])
2024 g = 0
2025 for f in v:
2026 # Conditional probabilities:
2027 g += log(self._likelihood[type].get(f, self._alpha) / d)
2028 g = exp(g) * self._classes[type] / n # prior
2029 p[type] = g
2030 # Normalize probability estimates.
2031 s = sum(p.itervalues()) or 1
2032 for type in p:
2033 p[type] /= s
2034 if not discrete:
2035 return p
2036 try:
2037 # Ties are broken in favor of the majority class
2038 # (random winner for majority ties).
2039 m = max(p.itervalues())
2040 p = sorted((self._classes[type], type) for type, g in p.iteritems() if g == m > 0)
2041 p = [type for frequency, type in p if frequency == p[0][0]]
2042 return choice(p)
2043 except:
2044 return self.baseline
2045
2046Bayes = NB = NaiveBayes
2047

Callers

nothing calls this directly

Calls 5

sumFunction · 0.85
_vectorMethod · 0.80
itervaluesMethod · 0.80
iteritemsMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected