| 1662 | FREQUENCY = "frequency" |
| 1663 | |
| 1664 | class Classifier(object): |
| 1665 | |
| 1666 | def __init__(self, train=[], baseline=FREQUENCY, **kwargs): |
| 1667 | """ A base class for Naive Bayes, k-NN and SVM. |
| 1668 | Trains a classifier on the given list of Documents or (document, type)-tuples, |
| 1669 | where document can be a Document, Vector, dict or string |
| 1670 | (dicts and strings are implicitly converted to vectors). |
| 1671 | """ |
| 1672 | self._vectors = [] # List of trained (type, vector)-tuples. |
| 1673 | self._classes = {} # Dict of (class, frequency)-items. |
| 1674 | self._baseline = baseline # Default predicted class. |
| 1675 | # Train on the list of Document objects or (document, type)-tuples: |
| 1676 | for d in (isinstance(d, Document) and (d, d.type) or d for d in train): |
| 1677 | self.train(*d) |
| 1678 | # In Pattern 2.5-, Classifier.test() is a classmethod. |
| 1679 | # In Pattern 2.6+, it is replaced with Classifier._test() once instantiated: |
| 1680 | self.test = self._test |
| 1681 | |
| 1682 | @property |
| 1683 | def features(self): |
| 1684 | """ Yields a list of trained features. |
| 1685 | """ |
| 1686 | return list(features(v for type, v in self._vectors)) |
| 1687 | |
| 1688 | @property |
| 1689 | def classes(self): |
| 1690 | """ Yields a list of trained classes. |
| 1691 | """ |
| 1692 | return self._classes.keys() |
| 1693 | |
| 1694 | terms, types = features, classes |
| 1695 | |
| 1696 | @property |
| 1697 | def binary(self): |
| 1698 | """ Yields True if the classifier predicts either True (0) or False (1). |
| 1699 | """ |
| 1700 | return sorted(self.classes) in ([False, True], [0, 1]) |
| 1701 | |
| 1702 | @property |
| 1703 | def distribution(self): |
| 1704 | """ Yields a dictionary of trained (class, frequency)-items. |
| 1705 | """ |
| 1706 | return self._classes.copy() |
| 1707 | |
| 1708 | @property |
| 1709 | def majority(self): |
| 1710 | """ Yields the majority class (= most frequent class). |
| 1711 | """ |
| 1712 | d = sorted((v, k) for k, v in self._classes.iteritems()) |
| 1713 | return d and d[-1][1] or None |
| 1714 | |
| 1715 | @property |
| 1716 | def minority(self): |
| 1717 | """ Yields the minority class (= least frequent class). |
| 1718 | """ |
| 1719 | d = sorted((v, k) for k, v in self._classes.iteritems()) |
| 1720 | return d and d[0][1] or None |
| 1721 |
no outgoing calls
no test coverage detected
searching dependent graphs…