~ubuntu-branches/ubuntu/precise/weka/precise

« back to all changes in this revision

Viewing changes to weka/estimators/EstimatorUtils.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
 *    EstimatorUtils.java
 
19
 *    Copyright (C) 2004 University of Waikato, Hamilton, New Zealand
 
20
 *
 
21
 */
 
22
 
 
23
package weka.estimators;
 
24
 
 
25
import java.io.FileOutputStream;
 
26
import java.io.PrintWriter;
 
27
import java.util.*;
 
28
import weka.core.*;
 
29
 
 
30
/** 
 
31
 * Contains static utility functions for Estimators.<p>
 
32
 *
 
33
 * @author Gabi Schmidberger (gabi@cs.waikato.ac.nz)
 
34
 * @version $Revision: 1.3 $
 
35
 */
 
36
public class EstimatorUtils {
 
37
  
 
38
  /** 
 
39
   * Find the minimum distance between values
 
40
   * @param inst sorted instances, sorted
 
41
   * @param attrIndex index of the attribute, they are sorted after
 
42
   * @return the minimal distance
 
43
   */
 
44
  public static double findMinDistance(Instances inst, int attrIndex) {
 
45
    double min = Double.MAX_VALUE;
 
46
    int numInst = inst.numInstances();
 
47
    double diff;
 
48
    if (numInst < 2) return min;
 
49
    int begin = -1;
 
50
    Instance instance = null;
 
51
    do { 
 
52
      begin++;
 
53
      if (begin < numInst) 
 
54
        { instance = inst.instance(begin); }
 
55
    } while (begin < numInst && instance.isMissing(attrIndex)); 
 
56
 
 
57
    double secondValue = inst.instance(begin).value(attrIndex);
 
58
    for (int i = begin; i < numInst && !inst.instance(i).isMissing(attrIndex);  i++) {
 
59
      double firstValue = secondValue; 
 
60
      secondValue = inst.instance(i).value(attrIndex);
 
61
      if (secondValue != firstValue) {
 
62
        diff = secondValue - firstValue;
 
63
        if (diff < min && diff > 0.0) {
 
64
          min = diff;
 
65
        }
 
66
      }
 
67
    }
 
68
    return min;
 
69
  }
 
70
 
 
71
  /** 
 
72
   * Find the minimum and the maximum of the attribute and return it in 
 
73
   * the last parameter..
 
74
   * @param inst instances used to build the estimator
 
75
   * @param attrIndex index of the attribute
 
76
   * @param minMax the array to return minimum and maximum in
 
77
   * @return number of not missing values
 
78
   * @exception Exception if parameter minMax wasn't initialized properly
 
79
   */
 
80
  public static int getMinMax(Instances inst, int attrIndex, double [] minMax) 
 
81
    throws Exception {
 
82
    double min = Double.NaN;
 
83
    double max = Double.NaN;
 
84
    Instance instance = null;
 
85
    int numNotMissing = 0;
 
86
    if ((minMax == null) || (minMax.length < 2)) {
 
87
      throw new Exception("Error in Program, privat method getMinMax");
 
88
    }
 
89
    
 
90
    Enumeration enumInst = inst.enumerateInstances();
 
91
    if (enumInst.hasMoreElements()) {
 
92
      do {
 
93
        instance = (Instance) enumInst.nextElement();
 
94
      } while (instance.isMissing(attrIndex) && (enumInst.hasMoreElements()));
 
95
      
 
96
      // add values if not  missing
 
97
      if (!instance.isMissing(attrIndex)) {
 
98
        numNotMissing++;
 
99
        min = instance.value(attrIndex);
 
100
        max = instance.value(attrIndex);
 
101
      }
 
102
      while (enumInst.hasMoreElements()) {
 
103
        instance = (Instance) enumInst.nextElement();
 
104
        if (!instance.isMissing(attrIndex)) {
 
105
          numNotMissing++;
 
106
          if (instance.value(attrIndex) < min) {
 
107
            min = (instance.value(attrIndex));
 
108
          } else {
 
109
            if (instance.value(attrIndex) > max) {            
 
110
              max = (instance.value(attrIndex));
 
111
            }
 
112
          }
 
113
        }
 
114
      }
 
115
    }
 
116
    minMax[0] = min;
 
117
    minMax[1] = max;
 
118
    return numNotMissing;
 
119
  }
 
120
 
 
121
  /**
 
122
   * Returns a dataset that contains all instances of a certain class value.
 
123
   *
 
124
   * @param data dataset to select the instances from
 
125
   * @param attrIndex index of the relevant attribute
 
126
   * @param classIndex index of the class attribute
 
127
   * @param classValue the relevant class value 
 
128
   * @return a dataset with only 
 
129
   */
 
130
  public static Vector getInstancesFromClass(Instances data, int attrIndex,
 
131
                                             int classIndex,
 
132
                                             double classValue, Instances workData) {
 
133
    //Oops.pln("getInstancesFromClass classValue"+classValue+" workData"+data.numInstances());
 
134
    Vector dataPlusInfo = new Vector(0);
 
135
    int num = 0;
 
136
    int numClassValue = 0;
 
137
    //workData = new Instances(data, 0);
 
138
    for (int i = 0; i < data.numInstances(); i++) {
 
139
      if (!data.instance(i).isMissing(attrIndex)) {
 
140
        num++;
 
141
        if (data.instance(i).value(classIndex) == classValue) {
 
142
          workData.add(data.instance(i));
 
143
          numClassValue++;
 
144
        }
 
145
      }
 
146
    } 
 
147
 
 
148
    Double alphaFactor = new Double((double)numClassValue/(double)num);
 
149
    dataPlusInfo.add(workData);
 
150
    dataPlusInfo.add(alphaFactor);
 
151
    return dataPlusInfo;
 
152
  }
 
153
 
 
154
 
 
155
  /**
 
156
   * Returns a dataset that contains of all instances of a certain class value.
 
157
   * @param data dataset to select the instances from
 
158
   * @param classIndex index of the class attribute
 
159
   * @param classValue the class value 
 
160
   * @return a dataset with only instances of one class value
 
161
   */
 
162
  public static Instances getInstancesFromClass(Instances data, int classIndex,
 
163
                                                double classValue) {
 
164
     Instances workData = new Instances(data, 0);
 
165
    for (int i = 0; i < data.numInstances(); i++) {
 
166
      if (data.instance(i).value(classIndex) == classValue) {
 
167
        workData.add(data.instance(i));
 
168
      }
 
169
     
 
170
    }
 
171
    return workData;
 
172
  }
 
173
  
 
174
    
 
175
   
 
176
  /**
 
177
   * Output of an n points of a density curve.
 
178
   * Filename is parameter f + ".curv".
 
179
   *
 
180
   * @param f string to build filename
 
181
   * @param est
 
182
   * @param min
 
183
   * @param max
 
184
   * @param numPoints
 
185
   * @throws Exception if something goes wrong
 
186
   */
 
187
  public static void writeCurve(String f, Estimator est, 
 
188
                                double min, double max,
 
189
                                int numPoints) throws Exception {
 
190
 
 
191
    PrintWriter output = null;
 
192
    StringBuffer text = new StringBuffer("");
 
193
    
 
194
    if (f.length() != 0) {
 
195
      // add attribute indexnumber to filename and extension .hist
 
196
      String name = f + ".curv";
 
197
      output = new PrintWriter(new FileOutputStream(name));
 
198
    } else {
 
199
      return;
 
200
    }
 
201
 
 
202
    double diff = (max - min) / ((double)numPoints - 1.0);
 
203
    try {
 
204
      text.append("" + min + " " + est.getProbability(min) + " \n");
 
205
 
 
206
      for (double value = min + diff; value < max; value += diff) {
 
207
        text.append("" + value + " " + est.getProbability(value) + " \n");
 
208
      }
 
209
      text.append("" + max + " " + est.getProbability(max) + " \n");
 
210
    } catch (Exception ex) {
 
211
      ex.printStackTrace();
 
212
      System.out.println(ex.getMessage());
 
213
    }
 
214
    output.println(text.toString());    
 
215
 
 
216
    // close output
 
217
    if (output != null) {
 
218
      output.close();
 
219
    }
 
220
  }
 
221
 
 
222
  /**
 
223
   * Output of an n points of a density curve.
 
224
   * Filename is parameter f + ".curv".
 
225
   *
 
226
   * @param f string to build filename
 
227
   * @param est
 
228
   * @param classEst
 
229
   * @param classIndex
 
230
   * @param min
 
231
   * @param max
 
232
   * @param numPoints
 
233
   * @throws Exception if something goes wrong
 
234
   */
 
235
  public static void writeCurve(String f, Estimator est, 
 
236
                                Estimator classEst,
 
237
                                double classIndex,
 
238
                                double min, double max,
 
239
                                int numPoints) throws Exception {
 
240
 
 
241
    PrintWriter output = null;
 
242
    StringBuffer text = new StringBuffer("");
 
243
    
 
244
    if (f.length() != 0) {
 
245
      // add attribute indexnumber to filename and extension .hist
 
246
      String name = f + ".curv";
 
247
      output = new PrintWriter(new FileOutputStream(name));
 
248
    } else {
 
249
      return;
 
250
    }
 
251
 
 
252
    double diff = (max - min) / ((double)numPoints - 1.0);
 
253
    try {
 
254
      text.append("" + min + " " + 
 
255
                  est.getProbability(min) * classEst.getProbability(classIndex)
 
256
                  + " \n");
 
257
 
 
258
      for (double value = min + diff; value < max; value += diff) {
 
259
        text.append("" + value + " " + 
 
260
                    est.getProbability(value) * classEst.getProbability(classIndex)
 
261
                    + " \n");
 
262
      }
 
263
      text.append("" + max + " " +
 
264
                  est.getProbability(max) * classEst.getProbability(classIndex)
 
265
                  + " \n");
 
266
    } catch (Exception ex) {
 
267
      ex.printStackTrace();
 
268
      System.out.println(ex.getMessage());
 
269
    }
 
270
    output.println(text.toString());    
 
271
 
 
272
    // close output
 
273
    if (output != null) {
 
274
      output.close();
 
275
    }
 
276
  }
 
277
 
 
278
  
 
279
  /**
 
280
   * Returns a dataset that contains of all instances of a certain value
 
281
   * for the given attribute.
 
282
   * @param data dataset to select the instances from
 
283
   * @param index the index of the attribute  
 
284
   * @param v the value 
 
285
   * @return a subdataset with only instances of one value for the attribute 
 
286
   */
 
287
  public static Instances getInstancesFromValue(Instances data, int index,
 
288
                                          double v) {
 
289
    Instances workData = new Instances(data, 0);
 
290
    for (int i = 0; i < data.numInstances(); i++) {
 
291
      if (data.instance(i).value(index) == v) {
 
292
        workData.add(data.instance(i));
 
293
      }
 
294
    } 
 
295
    return workData;
 
296
  }
 
297
 
 
298
   
 
299
  /**
 
300
   * Returns a string representing the cutpoints
 
301
   */
 
302
  public static String cutpointsToString(double [] cutPoints, boolean [] cutAndLeft) {
 
303
    StringBuffer text = new StringBuffer("");
 
304
    if (cutPoints == null) {
 
305
      text.append("\n# no cutpoints found - attribute \n"); 
 
306
    } else {
 
307
      text.append("\n#* "+cutPoints.length+" cutpoint(s) -\n"); 
 
308
      for (int i = 0; i < cutPoints.length; i++) {
 
309
        text.append("# "+cutPoints[i]+" "); 
 
310
        text.append(""+cutAndLeft[i]+"\n");
 
311
      }
 
312
      text.append("# end\n");
 
313
    }
 
314
    return text.toString();
 
315
  }
 
316
 
 
317
 
 
318
}