source: src/main/java/weka/classifiers/misc/SerializedClassifier.java @ 8

Last change on this file since 8 was 4, checked in by gnappo, 14 years ago

Import di weka.

File size: 8.7 KB
Line 
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
22package weka.classifiers.misc;
23
24import weka.classifiers.Classifier;
25import weka.classifiers.AbstractClassifier;
26import weka.core.Capabilities;
27import weka.core.Instance;
28import weka.core.Instances;
29import weka.core.Option;
30import weka.core.RevisionUtils;
31import weka.core.SerializationHelper;
32import weka.core.Utils;
33import weka.core.Capabilities.Capability;
34
35import java.io.File;
36import java.util.Enumeration;
37import java.util.Vector;
38
39/**
40 <!-- globalinfo-start -->
41 * A wrapper around a serialized classifier model. This classifier loads a serialized models and uses it to make predictions.<br/>
42 * <br/>
43 * Warning: since the serialized model doesn't get changed, cross-validation cannot bet used with this classifier.
44 * <p/>
45 <!-- globalinfo-end -->
46 *
47 <!-- options-start -->
48 * Valid options are: <p/>
49 *
50 * <pre> -D
51 *  If set, classifier is run in debug mode and
52 *  may output additional info to the console</pre>
53 *
54 * <pre> -model &lt;filename&gt;
55 *  The file containing the serialized model.
56 *  (required)</pre>
57 *
58 <!-- options-end -->
59 *
60 * @author  fracpete (fracpete at waikato dot ac dot nz)
61 * @version $Revision: 5928 $
62 */
63public class SerializedClassifier
64  extends AbstractClassifier {
65
66  /** for serialization */
67  private static final long serialVersionUID = 4599593909947628642L;
68
69  /** the serialized classifier model used for making predictions */
70  protected transient Classifier m_Model = null;
71 
72  /** the file where the serialized model is stored */
73  protected File m_ModelFile = new File(System.getProperty("user.dir"));
74 
75  /**
76   * Returns a string describing classifier
77   *
78   * @return            a description suitable for displaying in the
79   *                    explorer/experimenter gui
80   */
81  public String globalInfo() {
82    return 
83        "A wrapper around a serialized classifier model. This classifier loads "
84      + "a serialized models and uses it to make predictions.\n\n"
85      + "Warning: since the serialized model doesn't get changed, cross-validation "
86      + "cannot bet used with this classifier.";
87  }
88
89  /**
90   * Gets an enumeration describing the available options.
91   *
92   * @return an enumeration of all the available options.
93   */
94  public Enumeration listOptions(){
95    Vector              result;
96    Enumeration         enm;
97
98    result = new Vector();
99
100    enm = super.listOptions();
101    while (enm.hasMoreElements())
102      result.addElement(enm.nextElement());
103
104    result.addElement(new Option(
105        "\tThe file containing the serialized model.\n"
106        + "\t(required)",
107        "model", 1, "-model <filename>"));
108
109    return result.elements();
110  }
111 
112  /**
113   * returns the options of the current setup
114   *
115   * @return            the current options
116   */
117  public String[] getOptions(){
118    int         i;
119    Vector      result;
120    String[]    options;
121
122    result = new Vector();
123
124    options = super.getOptions();
125    for (i = 0; i < options.length; i++)
126      result.add(options[i]);
127
128    result.add("-model");
129    result.add("" + getModelFile());
130
131    return (String[]) result.toArray(new String[result.size()]);         
132  }
133
134  /**
135   * Parses the options for this object. <p/>
136   *
137   <!-- options-start -->
138   * Valid options are: <p/>
139   *
140   * <pre> -D
141   *  If set, classifier is run in debug mode and
142   *  may output additional info to the console</pre>
143   *
144   * <pre> -model &lt;filename&gt;
145   *  The file containing the serialized model.
146   *  (required)</pre>
147   *
148   <!-- options-end -->
149   *
150   * @param options     the options to use
151   * @throws Exception  if setting of options fails
152   */
153  public void setOptions(String[] options) throws Exception {
154    String      tmpStr;
155   
156    super.setOptions(options);
157   
158    tmpStr = Utils.getOption("model", options);
159    if (tmpStr.length() != 0)
160      setModelFile(new File(tmpStr));
161    else
162      setModelFile(new File(System.getProperty("user.dir")));
163  }
164 
165  /**
166   * Returns the tip text for this property
167   *
168   * @return            tip text for this property suitable for
169   *                    displaying in the explorer/experimenter gui
170   */
171  public String modelFileTipText() {
172    return "The serialized classifier model to use for predictions.";
173  }
174
175  /**
176   * Gets the file containing the serialized model.
177   *
178   * @return            the file.
179   */
180  public File getModelFile() {
181    return m_ModelFile;
182  }
183 
184  /**
185   * Sets the file containing the serialized model.
186   *
187   * @param value       the file.
188   */
189  public void setModelFile(File value) {
190    m_ModelFile = value;
191   
192    if (value.exists() && value.isFile()) {
193      try {
194        initModel();
195      }
196      catch (Exception e) {
197        throw new IllegalArgumentException("Cannot load model from file '" + value + "': " + e);
198      }
199    }
200  }
201
202  /**
203   * Sets the fully built model to use, if one doesn't want to load a model
204   * from a file or already deserialized a model from somewhere else.
205   *
206   * @param value       the built model
207   * @see               #getCurrentModel()
208   */
209  public void setModel(Classifier value) {
210    m_Model = value;
211  }
212 
213  /**
214   * Gets the currently loaded model (can be null). Call buildClassifier method
215   * to load model from file.
216   *
217   * @return            the current model
218   * @see               #setModel(Classifier)
219   */
220  public Classifier getCurrentModel() {
221    return m_Model;
222  }
223 
224  /**
225   * loads the serialized model if necessary, throws an Exception if the
226   * derserialization fails.
227   *
228   * @throws Exception  if deserialization fails
229   */
230  protected void initModel() throws Exception {
231    if (m_Model == null)
232      m_Model = (Classifier) SerializationHelper.read(m_ModelFile.getAbsolutePath());
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      result.disableAll();
256    }
257   
258    // set dependencies
259    for (Capability cap: Capability.values())
260      result.enableDependency(cap);
261   
262    result.setOwner(this);
263   
264    return result;
265  }
266 
267  /**
268   * Calculates the class membership probabilities for the given test
269   * instance.
270   *
271   * @param instance the instance to be classified
272   * @return preedicted class probability distribution
273   * @throws Exception if distribution can't be computed successfully
274   */
275  public double[] distributionForInstance(Instance instance) throws Exception {
276    double[]    result;
277
278    // init model if necessary
279    initModel();
280   
281    result = m_Model.distributionForInstance(instance);
282   
283    return result;
284  }
285 
286  /**
287   * loads only the serialized classifier
288   *
289   * @param data        the training instances
290   * @throws Exception  if something goes wrong
291   */
292  public void buildClassifier(Instances data) throws Exception {
293    // init model if necessary
294    initModel();
295
296    // can classifier handle the data?
297    getCapabilities().testWithFail(data);
298  }
299
300  /**
301   * Returns a string representation of the classifier
302   *
303   * @return            the string representation of the classifier
304   */
305  public String toString() {
306    StringBuffer        result;
307   
308    if (m_Model == null) {
309      result = new StringBuffer("No model loaded yet.");
310    }
311    else {
312      result = new StringBuffer();
313      result.append("SerializedClassifier\n");
314      result.append("====================\n\n");
315      result.append("File: " + getModelFile() + "\n\n");
316      result.append(m_Model.toString());
317    }
318   
319    return result.toString();
320  }
321 
322  /**
323   * Returns the revision string.
324   *
325   * @return            the revision
326   */
327  public String getRevision() {
328    return RevisionUtils.extract("$Revision: 5928 $");
329  }
330 
331  /**
332   * Runs the classifier with the given options
333   *
334   * @param args        the commandline options
335   */
336  public static void main(String[] args) {
337    runClassifier(new SerializedClassifier(), args);
338  }
339}
Note: See TracBrowser for help on using the repository browser.