~ubuntu-branches/ubuntu/trusty/weka/trusty-proposed

« back to all changes in this revision

Viewing changes to weka/classifiers/misc/SerializedClassifier.java

  • Committer: Bazaar Package Importer
  • Author(s): Soeren Sonnenburg
  • Date: 2008-02-24 09:18:45 UTC
  • Revision ID: james.westby@ubuntu.com-20080224091845-1l8zy6fm6xipbzsr
Tags: upstream-3.5.7+tut1
ImportĀ upstreamĀ versionĀ 3.5.7+tut1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 *    This program is free software; you can redistribute it and/or modify
 
3
 *    it under the terms of the GNU General Public License as published by
 
4
 *    the Free Software Foundation; either version 2 of the License, or
 
5
 *    (at your option) any later version.
 
6
 *
 
7
 *    This program is distributed in the hope that it will be useful,
 
8
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
9
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
10
 *    GNU General Public License for more details.
 
11
 *
 
12
 *    You should have received a copy of the GNU General Public License
 
13
 *    along with this program; if not, write to the Free Software
 
14
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
15
 */
 
16
 
 
17
/*
 
18
 * SerializedClassifier.java
 
19
 * Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
 
20
 */
 
21
 
 
22
package weka.classifiers.misc;
 
23
 
 
24
import weka.classifiers.Classifier;
 
25
import weka.core.Capabilities;
 
26
import weka.core.Instance;
 
27
import weka.core.Instances;
 
28
import weka.core.Option;
 
29
import weka.core.SerializationHelper;
 
30
import weka.core.Utils;
 
31
import weka.core.Capabilities.Capability;
 
32
 
 
33
import java.io.File;
 
34
import java.util.Enumeration;
 
35
import java.util.Vector;
 
36
 
 
37
/**
 
38
 <!-- globalinfo-start -->
 
39
 * A wrapper around a serialized classifier model. This classifier loads a serialized models and uses it to make predictions.<br/>
 
40
 * <br/>
 
41
 * Warning: since the serialized model doesn't get changed, cross-validation cannot bet used with this classifier.
 
42
 * <p/>
 
43
 <!-- globalinfo-end -->
 
44
 * 
 
45
 <!-- options-start -->
 
46
 * Valid options are: <p/>
 
47
 * 
 
48
 * <pre> -D
 
49
 *  If set, classifier is run in debug mode and
 
50
 *  may output additional info to the console</pre>
 
51
 * 
 
52
 * <pre> -model &lt;filename&gt;
 
53
 *  The file containing the serialized model.
 
54
 *  (required)</pre>
 
55
 * 
 
56
 <!-- options-end -->
 
57
 *
 
58
 * @author  fracpete (fracpete at waikato dot ac dot nz)
 
59
 * @version $Revision: 1.3 $
 
60
 */
 
61
public class SerializedClassifier
 
62
  extends Classifier {
 
63
 
 
64
  /** for serialization */
 
65
  private static final long serialVersionUID = 4599593909947628642L;
 
66
 
 
67
  /** the serialized classifier model used for making predictions */
 
68
  protected transient Classifier m_Model = null;
 
69
  
 
70
  /** the file where the serialized model is stored */
 
71
  protected File m_ModelFile = new File(System.getProperty("user.dir"));
 
72
  
 
73
  /**
 
74
   * Returns a string describing classifier
 
75
   * 
 
76
   * @return            a description suitable for displaying in the
 
77
   *                    explorer/experimenter gui
 
78
   */
 
79
  public String globalInfo() {
 
80
    return 
 
81
        "A wrapper around a serialized classifier model. This classifier loads "
 
82
      + "a serialized models and uses it to make predictions.\n\n"
 
83
      + "Warning: since the serialized model doesn't get changed, cross-validation "
 
84
      + "cannot bet used with this classifier.";
 
85
  }
 
86
 
 
87
  /**
 
88
   * Gets an enumeration describing the available options.
 
89
   *
 
90
   * @return an enumeration of all the available options.
 
91
   */
 
92
  public Enumeration listOptions(){
 
93
    Vector              result;
 
94
    Enumeration         enm;
 
95
 
 
96
    result = new Vector();
 
97
 
 
98
    enm = super.listOptions();
 
99
    while (enm.hasMoreElements())
 
100
      result.addElement(enm.nextElement());
 
101
 
 
102
    result.addElement(new Option(
 
103
        "\tThe file containing the serialized model.\n"
 
104
        + "\t(required)",
 
105
        "model", 1, "-model <filename>"));
 
106
 
 
107
    return result.elements();
 
108
  }
 
109
  
 
110
  /**
 
111
   * returns the options of the current setup
 
112
   *
 
113
   * @return            the current options
 
114
   */
 
115
  public String[] getOptions(){
 
116
    int         i;
 
117
    Vector      result;
 
118
    String[]    options;
 
119
 
 
120
    result = new Vector();
 
121
 
 
122
    options = super.getOptions();
 
123
    for (i = 0; i < options.length; i++)
 
124
      result.add(options[i]);
 
125
 
 
126
    result.add("-model");
 
127
    result.add("" + getModelFile());
 
128
 
 
129
    return (String[]) result.toArray(new String[result.size()]);          
 
130
  }
 
131
 
 
132
  /**
 
133
   * Parses the options for this object. <p/>
 
134
   *
 
135
   <!-- options-start -->
 
136
   * Valid options are: <p/>
 
137
   * 
 
138
   * <pre> -D
 
139
   *  If set, classifier is run in debug mode and
 
140
   *  may output additional info to the console</pre>
 
141
   * 
 
142
   * <pre> -model &lt;filename&gt;
 
143
   *  The file containing the serialized model.
 
144
   *  (required)</pre>
 
145
   * 
 
146
   <!-- options-end -->
 
147
   *
 
148
   * @param options     the options to use
 
149
   * @throws Exception  if setting of options fails
 
150
   */
 
151
  public void setOptions(String[] options) throws Exception {
 
152
    String      tmpStr;
 
153
    
 
154
    super.setOptions(options);
 
155
    
 
156
    tmpStr = Utils.getOption("model", options);
 
157
    if (tmpStr.length() != 0)
 
158
      setModelFile(new File(tmpStr));
 
159
    else
 
160
      setModelFile(new File(System.getProperty("user.dir")));
 
161
  }
 
162
  
 
163
  /**
 
164
   * Returns the tip text for this property
 
165
   * 
 
166
   * @return            tip text for this property suitable for
 
167
   *                    displaying in the explorer/experimenter gui
 
168
   */
 
169
  public String modelFileTipText() {
 
170
    return "The serialized classifier model to use for predictions.";
 
171
  }
 
172
 
 
173
  /**
 
174
   * Gets the file containing the serialized model.
 
175
   *
 
176
   * @return            the file.
 
177
   */
 
178
  public File getModelFile() {
 
179
    return m_ModelFile;
 
180
  }
 
181
  
 
182
  /**
 
183
   * Sets the file containing the serialized model.
 
184
   *
 
185
   * @param value       the file.
 
186
   */
 
187
  public void setModelFile(File value) {
 
188
    m_ModelFile = value;
 
189
    
 
190
    if (value.exists() && value.isFile()) {
 
191
      try {
 
192
        initModel();
 
193
      }
 
194
      catch (Exception e) {
 
195
        throw new IllegalArgumentException("Cannot load model from file '" + value + "': " + e);
 
196
      }
 
197
    }
 
198
  }
 
199
 
 
200
  /**
 
201
   * Sets the fully built model to use, if one doesn't want to load a model
 
202
   * from a file or already deserialized a model from somewhere else.
 
203
   * 
 
204
   * @param value       the built model
 
205
   * @see               #getCurrentModel()
 
206
   */
 
207
  public void setModel(Classifier value) {
 
208
    m_Model = value;
 
209
  }
 
210
  
 
211
  /**
 
212
   * Gets the currently loaded model (can be null). Call buildClassifier method
 
213
   * to load model from file.
 
214
   * 
 
215
   * @return            the current model
 
216
   * @see               #setModel(Classifier)
 
217
   */
 
218
  public Classifier getCurrentModel() {
 
219
    return m_Model;
 
220
  }
 
221
  
 
222
  /**
 
223
   * loads the serialized model if necessary, throws an Exception if the
 
224
   * derserialization fails. Always propagates the current debug flag.
 
225
   * 
 
226
   * @throws Exception  if deserialization fails
 
227
   */
 
228
  protected void initModel() throws Exception {
 
229
    if (m_Model == null)
 
230
      m_Model = (Classifier) SerializationHelper.read(m_ModelFile.getAbsolutePath());
 
231
    
 
232
    m_Model.setDebug(getDebug());
 
233
  }
 
234
 
 
235
  /**
 
236
   * Returns default capabilities of the base classifier.
 
237
   *
 
238
   * @return      the capabilities of the base classifier
 
239
   */
 
240
  public Capabilities getCapabilities() {
 
241
    Capabilities        result;
 
242
 
 
243
    // init model if necessary
 
244
    try {
 
245
      initModel();
 
246
    }
 
247
    catch (Exception e) {
 
248
      System.err.println(e);
 
249
    }
 
250
 
 
251
    if (m_Model != null)
 
252
      result = m_Model.getCapabilities();
 
253
    else
 
254
      result = new Capabilities(this);
 
255
    
 
256
    // set dependencies
 
257
    for (Capability cap: Capability.values())
 
258
      result.enableDependency(cap);
 
259
    
 
260
    result.setOwner(this);
 
261
    
 
262
    return result;
 
263
  }
 
264
  
 
265
  /**
 
266
   * Calculates the class membership probabilities for the given test
 
267
   * instance.
 
268
   *
 
269
   * @param instance the instance to be classified
 
270
   * @return preedicted class probability distribution
 
271
   * @throws Exception if distribution can't be computed successfully 
 
272
   */
 
273
  public double[] distributionForInstance(Instance instance) throws Exception {
 
274
    double[]    result;
 
275
 
 
276
    // init model if necessary
 
277
    initModel();
 
278
    
 
279
    result = m_Model.distributionForInstance(instance);
 
280
    
 
281
    return result;
 
282
  }
 
283
  
 
284
  /**
 
285
   * loads only the serialized classifier
 
286
   * 
 
287
   * @param data        the training instances
 
288
   * @throws Exception  if something goes wrong
 
289
   */
 
290
  public void buildClassifier(Instances data) throws Exception {
 
291
    // init model if necessary
 
292
    initModel();
 
293
 
 
294
    // can classifier handle the data?
 
295
    getCapabilities().testWithFail(data);
 
296
  }
 
297
 
 
298
  /**
 
299
   * Returns a string representation of the classifier
 
300
   * 
 
301
   * @return            the string representation of the classifier
 
302
   */
 
303
  public String toString() {
 
304
    StringBuffer        result;
 
305
    
 
306
    if (m_Model == null) {
 
307
      result = new StringBuffer("No model loaded yet.");
 
308
    }
 
309
    else {
 
310
      result = new StringBuffer();
 
311
      result.append("SerializedClassifier\n");
 
312
      result.append("====================\n\n");
 
313
      result.append("File: " + getModelFile() + "\n\n");
 
314
      result.append(m_Model.toString());
 
315
    }
 
316
    
 
317
    return result.toString();
 
318
  }
 
319
  
 
320
  /**
 
321
   * Runs the classifier with the given options
 
322
   * 
 
323
   * @param args        the commandline options
 
324
   */
 
325
  public static void main(String[] args) {
 
326
    runClassifier(new SerializedClassifier(), args);
 
327
  }
 
328
}