Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import weka.core.Instance;
- import weka.core.Instances;
- import weka.core.converters.ArffSaver;
- import weka.core.converters.ConverterUtils;
- import weka.core.converters.Saver;
- import java.io.File;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- import java.util.Random;
- public class Split {
- private File testFile;
- private File trainFile;
- private Split(String fileName, long seed, double split, int iterations) throws Exception {
- ConverterUtils.DataSource dataSource = new ConverterUtils.DataSource("split input/" + fileName);
- Instances instances = dataSource.getDataSet();
- List<Instance> instanceList = new ArrayList<>(instances);
- int length = Math.round((float) split * instances.size());
- Random random = new Random(seed);
- for (int i = 1; i < iterations + 1; i++) {
- prepareFiles(fileName, i);
- Collections.shuffle(instanceList, random);
- ArffSaver trainSaver = new ArffSaver();
- trainSaver.setStructure(instances);
- trainSaver.setRetrieval(Saver.INCREMENTAL);
- trainSaver.setFile(trainFile);
- for (int index = 0; index < length; index++) {
- trainSaver.writeIncremental(instanceList.get(index));
- }
- trainSaver.getWriter().flush();
- trainSaver.getWriter().close();
- ArffSaver testSaver = new ArffSaver();
- testSaver.setStructure(instances);
- testSaver.setRetrieval(Saver.INCREMENTAL);
- testSaver.setFile(testFile);
- for (int _index = 0; _index < instances.size() - length; _index++) {
- int index = length + _index;
- testSaver.writeIncremental(instanceList.get(index));
- }
- testSaver.getWriter().flush();
- testSaver.getWriter().close();
- }
- }
- public static void main(String[] args) throws Exception {
- new Split("Glass.arff", 5, 0.66, 5);
- }
- private void prepareFiles(String fileName, int iteration) throws IOException {
- String outputName = fileName.substring(0, fileName.lastIndexOf("."));
- File dir = new File(String.format("split/%s", outputName));
- testFile = new File(String.format("%s/%s_test_%d.arff", dir.getPath(), outputName, iteration));
- trainFile = new File(String.format("%s/%s_train_%d.arff", dir.getPath(), outputName, iteration));
- if (dir.mkdirs()) {
- testFile.createNewFile();
- trainFile.createNewFile();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement