1 | // Copyright 2015 Georg-August-Universität Göttingen, Germany
|
---|
2 | //
|
---|
3 | // Licensed under the Apache License, Version 2.0 (the "License");
|
---|
4 | // you may not use this file except in compliance with the License.
|
---|
5 | // You may obtain a copy of the License at
|
---|
6 | //
|
---|
7 | // http://www.apache.org/licenses/LICENSE-2.0
|
---|
8 | //
|
---|
9 | // Unless required by applicable law or agreed to in writing, software
|
---|
10 | // distributed under the License is distributed on an "AS IS" BASIS,
|
---|
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
---|
12 | // See the License for the specific language governing permissions and
|
---|
13 | // limitations under the License.
|
---|
14 |
|
---|
15 | package de.ugoe.cs.cpdp.training;
|
---|
16 |
|
---|
17 | import java.io.PrintStream;
|
---|
18 | import java.util.logging.Level;
|
---|
19 |
|
---|
20 | import org.apache.commons.io.output.NullOutputStream;
|
---|
21 |
|
---|
22 | import de.ugoe.cs.cpdp.wekaclassifier.ITestAwareClassifier;
|
---|
23 | import de.ugoe.cs.util.console.Console;
|
---|
24 | import weka.classifiers.rules.ZeroR;
|
---|
25 | import weka.core.Instances;
|
---|
26 |
|
---|
27 | // TODO comment
|
---|
28 | public class WekaTestAwareTraining extends WekaBaseTraining implements ITestAwareTrainingStrategy {
|
---|
29 |
|
---|
30 | @Override
|
---|
31 | public void apply(Instances testdata, Instances traindata) {
|
---|
32 | classifier = setupClassifier();
|
---|
33 | if( !(classifier instanceof ITestAwareClassifier) ) {
|
---|
34 | throw new RuntimeException("classifier must implement the ITestAwareClassifier interface in order to be used as TestAwareTrainingStrategy");
|
---|
35 | }
|
---|
36 | ((ITestAwareClassifier) classifier).setTestdata(testdata);
|
---|
37 | PrintStream errStr = System.err;
|
---|
38 | System.setErr(new PrintStream(new NullOutputStream()));
|
---|
39 | try {
|
---|
40 | if (classifier == null) {
|
---|
41 | Console.traceln(Level.WARNING, String.format("classifier null!"));
|
---|
42 | }
|
---|
43 | classifier.buildClassifier(traindata);
|
---|
44 | }
|
---|
45 | catch (Exception e) {
|
---|
46 | if (e.getMessage().contains("Not enough training instances with class labels")) {
|
---|
47 | Console.traceln(Level.SEVERE,
|
---|
48 | "failure due to lack of instances: " + e.getMessage());
|
---|
49 | Console.traceln(Level.SEVERE, "training ZeroR classifier instead");
|
---|
50 | classifier = new ZeroR();
|
---|
51 | try {
|
---|
52 | classifier.buildClassifier(traindata);
|
---|
53 | }
|
---|
54 | catch (Exception e2) {
|
---|
55 | throw new RuntimeException(e2);
|
---|
56 | }
|
---|
57 | }
|
---|
58 | else {
|
---|
59 | throw new RuntimeException(e);
|
---|
60 | }
|
---|
61 | }
|
---|
62 | finally {
|
---|
63 | System.setErr(errStr);
|
---|
64 | }
|
---|
65 | }
|
---|
66 | }
|
---|