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

Function K_fold_cross_validation

pattern/vector/__init__.py:1911–1931  ·  view source on GitHub ↗

For 10-fold cross-validation, performs 10 separate tests of the classifier, each with a different 9/10 training and 1/10 testing documents. The given classifier is a class (Bayes, KNN, SVM) which is initialized with the given optional parameters.

(Classifier, documents=[], folds=10, **kwargs)

Source from the content-addressed store, hash-verified

1909 return s
1910
1911def K_fold_cross_validation(Classifier, documents=[], folds=10, **kwargs):
1912 """ For 10-fold cross-validation, performs 10 separate tests of the classifier,
1913 each with a different 9/10 training and 1/10 testing documents.
1914 The given classifier is a class (Bayes, KNN, SVM)
1915 which is initialized with the given optional parameters.
1916 """
1917 K = kwargs.pop("K", folds)
1918 d = [isinstance(d, Document) and (d, d.type) or d for d in documents]
1919 d = shuffled(d) # Avoid a list sorted by type (because we take successive folds).
1920 m = [0.0, 0.0, 0.0, 0.0] # Macro-average accuracy, precision, recall & F1-score.
1921 for i in range(K):
1922 n = len(d) / float(K) # Test fold size.
1923 x = int(round(i * n)) # Test fold start index.
1924 y = int(round(i * n + n)) # Test fold stop index.
1925 classifier = Classifier(train=d[:x]+d[y:], **kwargs)
1926 A, P, R, F = classifier.test(d[x:y], **kwargs)
1927 m[0] += A
1928 m[1] += P
1929 m[2] += R
1930 m[3] += F
1931 return tuple([v / (K or 1) for v in m])
1932
1933kfoldcv = K_fold_cv = k_fold_cv = k_fold_cross_validation = K_fold_cross_validation
1934

Callers 3

testMethod · 0.85
gridsearchFunction · 0.85

Calls 5

testMethod · 0.95
shuffledFunction · 0.85
lenFunction · 0.85
ClassifierClass · 0.70
popMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…