summaryrefslogtreecommitdiffstats
path: root/src/model/Model.java
blob: 15b2b358294314ba5ca68f6b38594a35b243abb0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/**
Copyright 2016 Huawei Technologies Co. Ltd.

Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/

package model;

import java.io.*;
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.apache.log4j.*;

import org.apache.commons.math3.stat.descriptive.moment.*;
import org.apache.commons.math3.distribution.NormalDistribution;

import weka.core.*;
import weka.classifiers.evaluation.*;
import weka.core.converters.*;

import input.ARFFReader;
import predictor.*;


public class Model implements ModelInterface {
	protected Logger logger = Logger.getLogger(Model.class);
	
	protected String datapath;
	protected Instances trainingInstances;
	protected Instances preprocessedInstances;
	protected ArrayList<PredictorInterface> predictors;

	protected static DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
	protected static Date date = new Date();
	protected static String resultFilename = dateFormat.format(date);

	public Model(){
		this.datapath = "";
		this.trainingInstances = null;
		this.preprocessedInstances = null;
		this.predictors = new ArrayList<PredictorInterface>();
	}

	public Model (ModelInterface model) {
		this.datapath = model.getDatapath();
		this.trainingInstances = new Instances(model.getTrainingInstances());
		this.preprocessedInstances = new Instances(model.getPreprocessedInstances());
		this.predictors = new ArrayList<PredictorInterface>(model.getPredictors());
	}

	@Override
	public Instances getPreprocessedInstances() {
		return this.preprocessedInstances;
	}

	@Override
	public Instances getTrainingInstances() {
		return this.trainingInstances;
	}


	@Override
	public String getDatapath() {
		return this.datapath;
	}


	@Override
	public ArrayList<PredictorInterface> getPredictors() {
		return this.predictors;
	}


	@Override
	public void loadTrainingData(String path) {
		logger.debug("Reading training data from " + path);
		this.datapath = path;
		try {
			trainingInstances = ARFFReader.read(path);
			preprocessedInstances = trainingInstances;
			logger.debug("Training data is read");
			logger.trace(trainingInstances);
		} catch (Exception e) {
			logger.warn(e.toString());
		}
	}

	@Override
	public void loadRawLog(String path) {
		logger.debug("Reading logfile from " + path);
		try {
			BufferedReader in = new BufferedReader(new FileReader(path));
			String line = in.readLine();
			System.out.println(line);
		} catch (Exception e) {
			logger.warn(e.toString());
		}
	}



	@Override
	public void setPreprocessedInstances(Instances instances){
		this.preprocessedInstances=new Instances(instances);
	}

	@Override
	public void savePreprocessedInstances(String path) {
		ArffSaver saver = new ArffSaver();
		saver.setInstances(this.preprocessedInstances);
		try {
			saver.setFile(new File(path));
			saver.writeBatch();
		} catch (Exception e) {
			logger.error("Cannot save preprocessed instances to file " + path);
		}
	}

	@Override
	public void addPredictor(String shortName) {
		for (PredictorFactory.PredictionTechnique pTechnique : PredictorFactory.PredictionTechnique.values()) {
			if (pTechnique.getShortName().equals(shortName)) {
				predictors.add(PredictorFactory.createPredictor(pTechnique));
				logger.info("Added predictor: " + pTechnique.getName());
				return;
			}
		}
		logger.warn("Added predictor: None");
		logger.warn(shortName + " is not in the list.");
	}

	@Override
	public void selectTrainingMethod() {

	}

	@Override
	public void trainPredictors() throws Exception{
		if (preprocessedInstances == null) {
			throw new Exception("No training data");
		}
		if (predictors.size() == 0) {
			throw new Exception("No predictors selected");
		}
		for (PredictorInterface p : predictors) {
			try {
				logger.info("Training " + p.getName());
				p.train(preprocessedInstances);
				logger.debug(p.toString());
			} catch (Exception e) {
				logger.error(e.toString());
			}
		}
	}

	@Override
	public void crossValidatePredictors(int numFold) {
		long seed = 1;
		this.crossValidatePredictors(numFold, seed);
	}

	@Override
	public void crossValidatePredictors(int numFold, long seed) {
		for (PredictorInterface p : predictors) {
			try {
				logger.debug(numFold + "-fold cross-validating: " + p.getName());
				Random rand = new Random(seed);
				p.crossValidate(preprocessedInstances, numFold, rand);

				///* 
				ThresholdCurve tc = new ThresholdCurve();
				int classIndex = 1;
				Instances result = tc.getCurve(p.getEvaluationPredictions(), classIndex);


				// Save ROC

				BufferedWriter br = new BufferedWriter(new FileWriter(resultFilename + "_" + p.getName().replace(" ", "_") + "_ROC.arff"));
				br.write(result.toString());
				br.close();
			} catch (Exception e) {
				logger.error(e.toString());
			}
		}
	}

	@Override
	public void benchmark(int rounds, String filename) throws Exception {
		ArrayList<ArrayList<Double>> trainingTime = new ArrayList<ArrayList<Double>>(this.predictors.size());
		ArrayList<ArrayList<Double>> predictionTime = new ArrayList<ArrayList<Double>>(this.predictors.size());

		Runtime runtime = Runtime.getRuntime();

		for (int i=0; i<this.predictors.size(); i++) {
			trainingTime.add(new ArrayList<Double>(rounds));
			predictionTime.add(new ArrayList<Double>(rounds));
		}

		// Benchmark - using preprocessed instances
		long startTime;
		long endTime;
		double elapsedTime;
		for (int pIndex=0; pIndex<this.predictors.size(); pIndex++) {
			for (int rIndex=0; rIndex<rounds; rIndex++) {
				logger.debug("Benchmarking " + this.predictors.get(pIndex).getName() + " round " + rIndex);

				// Training time
				startTime = System.currentTimeMillis();
				this.predictors.get(pIndex).train(this.preprocessedInstances);
				endTime = System.currentTimeMillis();
				elapsedTime = ((double)(endTime - startTime))/1000;
				trainingTime.get(pIndex).add(elapsedTime);
				logger.debug("Training time = " + elapsedTime + " seconds");

				// Prediction time
				startTime = System.currentTimeMillis();
				this.predictors.get(pIndex).predict(this.preprocessedInstances);
				endTime = System.currentTimeMillis();
				elapsedTime = ((double)(endTime - startTime))/1000;
				predictionTime.get(pIndex).add(elapsedTime);
				logger.debug("Prediction time = " + elapsedTime + " seconds");
			}
		}

		// Save time results to file
		BufferedWriter br = new BufferedWriter(new FileWriter(filename+"_benchmark"));
		// Write header
		String header = "";
		for (int pIndex=0; pIndex<this.predictors.size(); pIndex++) {
			header += "\"" + this.predictors.get(pIndex).getName() + " Training\" ";
			header += "\"" + this.predictors.get(pIndex).getName() + " Prediction\" ";
		}
		header += "\n";
		br.write(header);

		for (int rIndex=0; rIndex<rounds; rIndex++) {
			String line = "";
			for (int pIndex=0; pIndex<this.predictors.size(); pIndex++) {
				line += trainingTime.get(pIndex).get(rIndex).toString() + " " + predictionTime.get(pIndex).get(rIndex).toString() + " ";
			}
			line += "\n";
			br.write(line);
		}
		br.close();

		// TODO: move to another function
		// refactor
		// Calculate and save summary results
		BufferedWriter brSummary = new BufferedWriter(new FileWriter(filename+"_benchmark_time_summary"));
		//header = "Algorithms tMean tError pMean pError\n";
		//brSummary.write(header);
		for (int pIndex=0; pIndex<this.predictors.size(); pIndex++) {
			String line = "\"" + this.predictors.get(pIndex).getName() + "\" ";
			// Calculate mean
			double [] training = new double[rounds];
			// Convert ArrayList to array for Mean.evaluate
			for (int rIndex=0; rIndex<rounds; rIndex++) {
				//System.out.println("pIndex = " + pIndex + " rIndex = " + rIndex);
				//System.out.println("array size = " + training.length);
				training[rIndex] = trainingTime.get(pIndex).get(rIndex);
			}
			double meanTraining = new Mean().evaluate(training);
			double varTraining = new Variance().evaluate(training);
			double stdTraining = Math.sqrt(varTraining);
			double errorTraining = new NormalDistribution().inverseCumulativeProbability(0.975)*(stdTraining/Math.sqrt(rounds));
			double lowerCITraining = meanTraining - errorTraining;
			double upperCITraining = meanTraining + errorTraining;
			line += meanTraining + " " + errorTraining + " ";
			//brSummary.write(line);

			//line = "\"" + this.predictors.get(pIndex).getName() + " Prediction\" ";
			// Calculate mean
			double [] prediction = new double[rounds];
			// Convert ArrayList to array for Mean.evaluate
			for (int rIndex=0; rIndex<rounds; rIndex++) {
				prediction[rIndex] = predictionTime.get(pIndex).get(rIndex);
			}
			double meanPrediction = new Mean().evaluate(prediction);
			double varPrediction = new Variance().evaluate(prediction);
			double stdPrediction = Math.sqrt(varPrediction);
			double errorPrediction = new NormalDistribution().inverseCumulativeProbability(0.975)*(stdPrediction/Math.sqrt(rounds));
			double lowerCIPrediction = meanPrediction - errorPrediction;
			double upperCIPrediction = meanPrediction + errorPrediction;
			line += meanPrediction + " " + errorPrediction + "\n";
			brSummary.write(line);
		}
		brSummary.close();
	}


	@Override
	public String getPredictorNames() {
		String str = "";
		for (PredictorInterface p : this.predictors) {
			str += p.getName() + "\n";
		}
		return str;
	}

	@Override
	public String toString() {
		String str = "";
		str += "Training data:\n" + this.datapath + "\n";
		str += "Training data summary:\n" + this.getTrainingInstances().toSummaryString() + "\n";
		str += "Preprocessed data summary:\n" + this.getPreprocessedInstances().toSummaryString() + "\n";
		str += "Predictors:\n" + this.getPredictorNames() + "\n";
		return str;
	}

	@Override
	public void saveSettings(String filename) throws Exception {
		BufferedWriter br = new BufferedWriter(new FileWriter(filename,true));
		br.write(this.toString());
		br.close();
	}

	@Override
	public void saveResults(String filename) throws Exception {
		BufferedWriter br = new BufferedWriter(new FileWriter(filename,true));

		for (PredictorInterface p : this.predictors) {
			logger.info(p.getEvaluationResults());
			br.write(p.getEvaluationResults());
		}

		br.close();
	}
}