KFold implements CrossValidator<ListDataset<INSTANCE>> { @Override public CrossValidationIterable<ListDataset<INSTANCE>> createIterable(ListDataset<INSTANCE> data) { return new KFoldIterable(data, k); } KFold(int k); @Override CrossValidationIterable<ListDataset<INSTANCE>> createIterable(ListDataset<INSTANCE> data); @Override String toString();  }
@Test public void test10Fold() { KFold<Integer> cv = new KFold<Integer>(10); CrossValidationIterable<ListDataset<Integer>> iterable = cv.createIterable(dataset); for (ValidationData<ListDataset<Integer>> cvData : iterable) { ListDataset<Integer> training = cvData.getTrainingDataset(); ListDataset<Integer> validation = cvData.getValidationDataset(); assertEquals(1, validation.size()); assertEquals(dataset.size() - 1, training.size()); assertEquals(dataset.size(), validation.size() + training.size()); TIntHashSet trainingSet = new TIntHashSet(); for (int j=0; j<training.size(); j++) { trainingSet.add( training.getInstance(j) ); } assertEquals(training.size(), trainingSet.size()); TIntHashSet validationSet = new TIntHashSet(); for (int j=0; j<validation.size(); j++) { validationSet.add( validation.getInstance(j) ); } assertEquals(validation.size(), validationSet.size()); for (int i : trainingSet.toArray()) { assertFalse(validationSet.contains(i)); } for (int i : validationSet.toArray()) { assertFalse(trainingSet.contains(i)); } } }
@Test(expected = IllegalArgumentException.class) public void test100Fold() { KFold<Integer> cv = new KFold<Integer>(100); cv.createIterable(dataset); }
@Test public void test5Fold() { KFold<Integer> cv= new KFold<Integer>(5); CrossValidationIterable<ListDataset<Integer>> iterable = cv.createIterable(dataset); for (ValidationData<ListDataset<Integer>> cvData : iterable) { ListDataset<Integer> training = cvData.getTrainingDataset(); ListDataset<Integer> validation = cvData.getValidationDataset(); assertEquals(2, validation.size()); assertEquals(dataset.size() - 2, training.size()); assertEquals(dataset.size(), validation.size() + training.size()); TIntHashSet trainingSet = new TIntHashSet(); for (int j=0; j<training.size(); j++) { trainingSet.add( training.getInstance(j) ); } assertEquals(training.size(), trainingSet.size()); TIntHashSet validationSet = new TIntHashSet(); for (int j=0; j<validation.size(); j++) { validationSet.add( validation.getInstance(j) ); } assertEquals(validation.size(), validationSet.size()); for (int i : trainingSet.toArray()) { assertFalse(validationSet.contains(i)); } for (int i : validationSet.toArray()) { assertFalse(trainingSet.contains(i)); } } }