やり方は色々あると思いますが、個人的には交差検証で細かく制御したい場合、StratifiedKFold
などのクラスを使って交差検証の処理そのものは自分で書くことにしています。簡単です。
python
1import numpy as np
2from sklearn.datasets import load_digits
3from sklearn.tree import DecisionTreeClassifier as DTC
4from sklearn.model_selection import StratifiedKFold as SKF
5from sklearn.metrics import classification_report as clf_report
6
7def main():
8 digits = load_digits()
9 X = digits.data
10 y = digits.target
11
12 clf = DTC()
13
14 skf = SKF(n_splits=3, shuffle=True, random_state=0)
15 trues = []
16 preds = []
17 for train_index, test_index in skf.split(X, y):
18 clf.fit(X[train_index], y[train_index])
19 trues.append(y[test_index])
20 preds.append(clf.predict(X[test_index]))
21
22 print(clf_report(np.hstack(trues), np.hstack(preds)))
23
24if __name__ == "__main__":
25 main()
26
27""" =>
28 precision recall f1-score support
29
30 0 0.95 0.95 0.95 178
31 1 0.77 0.84 0.80 182
32 2 0.81 0.86 0.84 177
33 3 0.84 0.79 0.81 183
34 4 0.86 0.84 0.85 181
35 5 0.87 0.87 0.87 182
36 6 0.91 0.91 0.91 181
37 7 0.87 0.88 0.87 179
38 8 0.74 0.75 0.74 174
39 9 0.81 0.76 0.78 180
40
41 micro avg 0.84 0.84 0.84 1797
42 macro avg 0.84 0.84 0.84 1797
43weighted avg 0.84 0.84 0.84 1797
44
45"""
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/21 03:52