source: src/main/java/weka/associations/AssociatorEvaluation.java @ 27

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

Import di weka.

File size: 8.4 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 * AssociatorEvaluation.java
19 * Copyright (C) 2006 University of Waikato, Hamilton, New Zealand
20 */
21
22package weka.associations;
23
24import weka.core.Instances;
25import weka.core.Option;
26import weka.core.OptionHandler;
27import weka.core.RevisionHandler;
28import weka.core.RevisionUtils;
29import weka.core.Utils;
30import weka.core.Drawable;
31import weka.core.converters.ConverterUtils.DataSource;
32
33import java.util.Enumeration;
34import java.io.BufferedWriter;
35import java.io.FileWriter;
36
37/**
38 * Class for evaluating Associaters.
39 *
40 * @author  fracpete (fracpete at waikato dot ac dot nz)
41 * @version $Revision: 1.5 $
42 */
43public class AssociatorEvaluation
44  implements RevisionHandler {
45
46  /** the result string */
47  protected StringBuffer m_Result;
48   
49  /**
50   * default constructor
51   */
52  public AssociatorEvaluation() {
53    super();
54   
55    m_Result = new StringBuffer();
56  }
57 
58  /**
59   * Generates an option string to output on the commandline.
60   *
61   * @param associator  the associator to generate the string for
62   * @return            the option string
63   */
64  protected static String makeOptionString(Associator associator) {
65    StringBuffer        text;
66   
67    text = new StringBuffer();   
68   
69    // general options
70    text.append("\nGeneral options:\n\n");
71    text.append("-t <training file>\n");
72    text.append("\tThe name of the training file.\n");
73    text.append("-g <name of graph file>\n");
74    text.append("\tOutputs the graph representation (if supported) of the associator to a file.\n");
75   
76    // associator specific options, if any
77    if (associator instanceof OptionHandler) {
78      text.append(
79          "\nOptions specific to " 
80          + associator.getClass().getName().replaceAll(".*\\.", "") + ":\n\n");
81     
82      Enumeration enm = ((OptionHandler) associator).listOptions();
83      while (enm.hasMoreElements()) {
84        Option option = (Option) enm.nextElement();
85        text.append(option.synopsis() + "\n");
86        text.append(option.description() + "\n");
87      }
88    }
89   
90    return text.toString();
91  }
92
93  /**
94   * Evaluates an associator with the options given in an array of strings.
95   *
96   * @param associatorString    class of associator as a string
97   * @param options             the array of string containing the options
98   * @throws Exception          if model could not be evaluated successfully
99   * @return                    a string describing the results
100   */
101  public static String evaluate(String associatorString, String[] options) throws Exception {
102    Associator associator;       
103
104    // Create associator
105    try {
106      associator = (Associator) Class.forName(associatorString).newInstance();
107    }
108    catch (Exception e) {
109      throw new Exception("Can't find class with name " + associatorString + '.');
110    }
111   
112    return evaluate(associator, options);
113  }
114 
115  /**
116   * Evaluates the associator with the given commandline options and returns
117   * the evaluation string.
118   *
119   * @param associator  the Associator to evaluate
120   * @param options     the commandline options
121   * @return            the generated output string
122   * @throws Exception  if evaluation fails
123   */
124  public static String evaluate(Associator associator, String[] options) 
125    throws Exception {
126
127    String trainFileString = "";
128    String graphFileName = "";
129    AssociatorEvaluation eval;
130    DataSource loader;
131
132    // help?
133    if (Utils.getFlag('h', options))
134      throw new Exception("\nHelp requested.\n" + makeOptionString(associator));
135   
136    try {
137      // general options
138      trainFileString = Utils.getOption('t', options);
139      if (trainFileString.length() == 0) 
140        throw new Exception("No training file given!");
141      loader = new DataSource(trainFileString);
142
143      graphFileName = Utils.getOption('g', options);
144
145      // associator specific options
146      if (associator instanceof OptionHandler) {
147        ((OptionHandler) associator).setOptions(options);
148      }
149     
150      // left-over options?
151      Utils.checkForRemainingOptions(options);
152    }
153    catch (Exception e) {
154      throw new Exception(
155          "\nWeka exception: " 
156          + e.getMessage() + "\n" 
157          + makeOptionString(associator));
158    }
159   
160    // load file and build associations
161    eval = new AssociatorEvaluation();
162    String results = eval.evaluate(associator, new Instances(loader.getDataSet()));
163
164    // If associator is drawable output string describing graph
165    if ((associator instanceof Drawable) && (graphFileName.length() != 0)) {
166      BufferedWriter writer = new BufferedWriter(new FileWriter(graphFileName));
167      writer.write(((Drawable) associator).graph());
168      writer.newLine();
169      writer.flush();
170      writer.close();
171    }
172
173    return results;
174  }
175 
176  /**
177   * Evaluates the associator with the given commandline options and returns
178   * the evaluation string.
179   *
180   * @param associator  the Associator to evaluate
181   * @param data        the data to run the associator with
182   * @return            the generated output string
183   * @throws Exception  if evaluation fails
184   */
185  public String evaluate(Associator associator, Instances data) 
186    throws Exception {
187   
188    long startTime;
189    long endTime;
190   
191    // build associations
192    startTime = System.currentTimeMillis();
193    associator.buildAssociations(data);
194    endTime = System.currentTimeMillis();
195
196    m_Result = new StringBuffer(associator.toString());
197    m_Result.append("\n=== Evaluation ===\n\n");
198    m_Result.append("Elapsed time: " + (((double) (endTime - startTime)) / 1000) + "s");
199    m_Result.append("\n");
200   
201    return m_Result.toString();
202  }
203
204  /**
205   * Tests whether the current evaluation object is equal to another
206   * evaluation object
207   *
208   * @param obj the object to compare against
209   * @return true if the two objects are equal
210   */
211  public boolean equals(Object obj) {
212    if ((obj == null) || !(obj.getClass().equals(this.getClass())))
213      return false;
214   
215    AssociatorEvaluation cmp = (AssociatorEvaluation) obj;
216   
217    // TODO: better comparison???
218    String associatingResults1 = m_Result.toString().replaceAll("Elapsed time.*", "");
219    String associatingResults2 = cmp.m_Result.toString().replaceAll("Elapsed time.*", "");
220    if (!associatingResults1.equals(associatingResults2)) 
221      return false;
222   
223    return true;
224  }
225 
226  /**
227   * returns a summary string of the evaluation with a no title
228   *
229   * @return            the summary string
230   */
231  public String toSummaryString() {
232    return toSummaryString("");
233  }
234 
235  /**
236   * returns a summary string of the evaluation with a default title
237   *
238   * @param title       the title to print before the result
239   * @return            the summary string
240   */
241  public String toSummaryString(String title) {
242    StringBuffer        result;
243   
244    result = new StringBuffer(title);
245    if (title.length() != 0)
246      result.append("\n");
247    result.append(m_Result);
248   
249    return result.toString();
250  }
251 
252  /**
253   * returns the current result
254   *
255   * @return            the currently stored result
256   * @see               #toSummaryString()
257   */
258  public String toString() {
259    return toSummaryString();
260  }
261 
262  /**
263   * Returns the revision string.
264   *
265   * @return            the revision
266   */
267  public String getRevision() {
268    return RevisionUtils.extract("$Revision: 1.5 $");
269  }
270
271  /**
272   * A test method for this class. Just extracts the first command line
273   * argument as an associator class name and calls evaluate.
274   *
275   * @param args        an array of command line arguments, the first of which
276   *                    must be the class name of an associator.
277   */
278  public static void main(String[] args) {
279    try {
280      if (args.length == 0) {
281        throw new Exception(
282            "The first argument must be the class name of a kernel");
283      }
284      String associator = args[0];
285      args[0] = "";
286      System.out.println(evaluate(associator, args));
287    }
288    catch (Exception ex) {
289      ex.printStackTrace();
290      System.err.println(ex.getMessage());
291    }
292  }
293}
Note: See TracBrowser for help on using the repository browser.