| 1860 | #--- CLASSIFIER EVALUATION ------------------------------------------------------------------------- |
| 1861 | |
| 1862 | class ConfusionMatrix(defaultdict): |
| 1863 | |
| 1864 | def __init__(self, classify=lambda document: True, documents=[]): |
| 1865 | """ Returns the matrix of classes x predicted classes as a dictionary. |
| 1866 | """ |
| 1867 | defaultdict.__init__(self, lambda: defaultdict(int)) |
| 1868 | for document, type1 in documents: |
| 1869 | type2 = classify(document) |
| 1870 | self[type1][type2] += 1 |
| 1871 | |
| 1872 | def split(self): |
| 1873 | """ Returns an iterator over one-vs-all (type, TP, TN, FP, FN)-tuples. |
| 1874 | """ |
| 1875 | return iter((type,) + self(type) for type in self) |
| 1876 | |
| 1877 | def __call__(self, type): |
| 1878 | """ Returns a (TP, TN, FP, FN)-tuple for the given class (one-vs-all). |
| 1879 | """ |
| 1880 | TP = 0 # True positives. |
| 1881 | TN = 0 # True negatives. |
| 1882 | FP = 0 # False positives (type I error). |
| 1883 | FN = 0 # False negatives (type II error). |
| 1884 | for t1 in self: |
| 1885 | for t2, n in self[t1].iteritems(): |
| 1886 | if type == t1 == t2: |
| 1887 | TP += n |
| 1888 | if type != t1 == t2: |
| 1889 | TN += n |
| 1890 | if type == t1 != t2: |
| 1891 | FN += n |
| 1892 | if type == t2 != t1: |
| 1893 | FP += n |
| 1894 | return (TP, TN, FP, FN) |
| 1895 | |
| 1896 | @property |
| 1897 | def table(self, padding=1): |
| 1898 | k = sorted(self) |
| 1899 | n = max(map(lambda x: len(decode_utf8(x)), k)) |
| 1900 | n = max(n, *(len(str(self[k1][k2])) for k1 in k for k2 in k)) + padding |
| 1901 | s = "".ljust(n) |
| 1902 | for t1 in k: |
| 1903 | s += decode_utf8(t1).ljust(n) |
| 1904 | for t1 in k: |
| 1905 | s += "\n" |
| 1906 | s += decode_utf8(t1).ljust(n) |
| 1907 | for t2 in k: |
| 1908 | s += str(self[t1][t2]).ljust(n) |
| 1909 | return s |
| 1910 | |
| 1911 | def K_fold_cross_validation(Classifier, documents=[], folds=10, **kwargs): |
| 1912 | """ For 10-fold cross-validation, performs 10 separate tests of the classifier, |
no outgoing calls
no test coverage detected
searching dependent graphs…