-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIBM.java
More file actions
751 lines (669 loc) · 18.1 KB
/
IBM.java
File metadata and controls
751 lines (669 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* IBM.java
* Copyright (C) 1999 University of Waikato, Hamilton, New Zealand
* Further Edited Utas 2012
*
*/
package weka.classifiers.lazy;
import weka.classifiers.Classifier;
import weka.classifiers.UpdateableClassifier;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import weka.core.Capabilities.Capability;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import java.lang.Math;
import java.util.LinkedList;
import java.util.Enumeration;
/**
<!-- globalinfo-start -->
* Modified Value Difference Metric (MVDM). Calculates distance tables that allow it to produce real-valued distances between instances, and attaches weights to the instances to further modify the structure of feature space. <br/>
* <br/>
* For more information, see <br/>
* <br/>
* S. Cost, S. Salzberg (1993). A Weighted Nearest Neighbor Algorithm for Learning with Symbolic Features. Machine Learning. 10:57-78.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @article{1993,
* author = {S. Cost and S. Salzberg},
* journal = {Machine Learning},
* pages = {57-78},
* title = {A Weighted Nearest Neighbor Algorithm for Learning with Symbolic Features},
* volume = {10},
* year = {1993}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
<!-- options-end -->
* @author Stuart Inglis (singlis@cs.waikato.ac.nz)
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision: 5525 $
*/
/*
* This document has been further modified by;
*
* Astrid Goss,
* David Brough, and
* James Scheibner.
*
* As a part of the KXT311 Assignment 2 at the University of Tasmania 2012.
*/
public class IBM
extends Classifier
implements UpdateableClassifier, TechnicalInformationHandler
{
/** for serialization */
static final long serialVersionUID = -6152184127304895851L;
/** The training instances used for classification. */
private Instances m_Train;
/** The minimum values for numeric attributes. */
private double [] m_MinArray;
/** The maximum values for numeric attributes. */
private double [] m_MaxArray;
/**
* Returns a string describing classifier
* @return a description suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo()
{
System.out.println("Display globalInfo now");
return "Modified Value Difference Metric (MVDM). Calculates distance tables "
+ "that allow it to produce real-valued distances between instances, "
+ "and attaches weights to the instances to further modify the structure "
+ "of feature space.\n\n"
+ "For more information, see \n\n"
+ getTechnicalInformation().toString();
}
/**
* TODO add additional article refrences here
*
* Returns an instance of a TechnicalInformation object, containing
* detailed information about the technical background of this class,
* e.g., paper reference or book this class is based on.
*
* @return the technical information about this class
*/
public TechnicalInformation getTechnicalInformation()
{
TechnicalInformation result;
result = new TechnicalInformation(Type.ARTICLE);
result.setValue(Field.AUTHOR, "S. Cost and S.Salzberg");
result.setValue(Field.YEAR, "1993");
result.setValue(Field.TITLE, "A Weighted Nearest Neighbour Algorithm with Learning for Symbolic Featurs");
result.setValue(Field.JOURNAL, "Machine Learning");
result.setValue(Field.VOLUME, "10");
result.setValue(Field.PAGES, "57-78");
return result;
}
<<<<<<< HEAD
/**
* Returns default capabilities of the classifier.
*
* @return the capabilities of this classifier
*/
public Capabilities getCapabilities()
{
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.DATE_ATTRIBUTES);
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
// instances
result.setMinimumNumberInstances(0);
return result;
}
/**
* Generates the classifier.
*
* @param instances set of instances serving as training data
* @throws Exception if the classifier has not been generated successfully
*/
public void buildClassifier(Instances instances) throws Exception
{
// can classifier handle the data?
getCapabilities().testWithFail(instances);
// remove instances with missing class
instances = new Instances(instances);
instances.deleteWithMissingClass();
m_Train = new Instances(instances, 0, instances.numInstances());
m_MinArray = new double [m_Train.numAttributes()];//+3?
m_MaxArray = new double [m_Train.numAttributes()];//+3?
for (int i = 0; i < m_Train.numAttributes(); i++)
{
m_MinArray[i] = m_MaxArray[i] = Double.NaN;
}
Enumeration enu = m_Train.enumerateInstances();
while (enu.hasMoreElements())
{
updateMinMax((Instance) enu.nextElement());
}
}
/**
* Updates the classifier.
*
* @param instance the instance to be put into the classifier
* @throws Exception if the instance could not be included successfully
*/
public void updateClassifier(Instance instance) throws Exception
{
if (m_Train.equalHeaders(instance.dataset()) == false)
{
throw new Exception("Incompatible instance types");
}
if (instance.classIsMissing())
{
return;
}
m_Train.add(instance);
updateMinMax(instance);
}
/**
* Classifies the given test instance.
*
* @param instance the instance to be classified
* @return the predicted class for the instance
* @throws Exception if the instance can't be classified
*/
public double classifyInstance(Instance instance) throws Exception
{
if (m_Train.numInstances() == 0)
{
throw new Exception("No training instances!");
}
double distance, minDistance = Double.MAX_VALUE, classValue = 0;
updateMinMax(instance);
Enumeration enu = m_Train.enumerateInstances();
while (enu.hasMoreElements())
{
Instance trainInstance = (Instance) enu.nextElement();
if (!trainInstance.classIsMissing())
{
distance = distance(instance, trainInstance);
if (distance < minDistance)
{
minDistance = distance;
classValue = trainInstance.classValue();
}
}
}
return classValue;
}
/**
* Returns a description of this classifier.
*
* @return a description of this classifier as a string.
*/
public String toString()
{
return ("IBM classifier");
}
/**
* Calculates the distance between two instances
*
* @param first the first instance
* @param second the second instance
* @return the distance between the two given instances
*/
private double distance(Instance first, Instance second)
{
double diff, distance = 0;
for(int i = 0; i < m_Train.numAttributes(); i++)
{
if (i == m_Train.classIndex())
{
continue;
}
if (m_Train.attribute(i).isNominal())
{
int firstCount = 0;
int secondCount = 0;
int firstClassCount = 0;
int secondClassCount = 0;
double attribDist = 0;
// If attribute is nominal
// Count the number of occurrences of this value for the
// attribute
LinkedList<Instance> training_Items = new LinkedList<Instance>();
//for(Instance sam : m_Train)
//for (int j=0; j < m_Train.numAttributes(); j++)
for(Instance sam : training_Items)
{
//Instances instances = m_Train.m_Instances;
//Instance sam = instances.get(j);
if (sam.toString().equals(m_Train.toString())) {
// Count the number of times first.value(i) has occured
if (((int)first.value(i) != (int)sam.value(i)))
{
++firstCount;
}
// Count the number of times second.value(i) has occured
if (((int)first.value(i) != (int)sam.value(i)))
{
++secondCount;
}
}
}
// Check to see if both values occurred at least once
// correct to avoid the divide by zero problem otherwise
// as per assignment spec
if(firstCount == 0)
{
firstCount = 1;
}
if(secondCount == 0)
{
secondCount = 1;
}
// Count the number of occurrences of this value for the
// attribute for each class
for(int classCount = 0;
classCount < m_Train.numClasses(); ++classCount)
{
// Reset the class counts for this class
firstClassCount = 0;
secondClassCount = 0;
//for(Instance sam : m_Train)
for(Instance sam : training_Items)
{
// Count the number of times first.value(i) has
// occured for this class
if (((int)first.value(i) == (int)sam.value(i)))
{
++firstClassCount;
}
// Count the number of times second.value(i) has
// occured for this class
if (((int)first.value(i) == (int)sam.value(i)))
{
++secondClassCount;
}
}
// Contribute this class vlaues to the running total
attribDist += Math.abs(firstClassCount / firstCount -
secondClassCount / secondCount);
}
distance += attribDist;
}
else
{
// If attribute is numeric
if (first.isMissing(i) || second.isMissing(i))
{
if (first.isMissing(i) && second.isMissing(i))
{
diff = 1;
}
else
{
if (second.isMissing(i))
{
diff = norm(first.value(i), i);
}
else
{
diff = norm(second.value(i), i);
}
if (diff < 0.5)
{
diff = 1.0 - diff;
}
}
}
else
{
diff = norm(first.value(i), i) - norm(second.value(i), i);
}
distance += diff * diff;
}
}
return distance;
}
=======
/**
* Returns default capabilities of the classifier.
*
* @return the capabilities of this classifier
*/
public Capabilities getCapabilities()
{
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.DATE_ATTRIBUTES);
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
// instances
result.setMinimumNumberInstances(0);
return result;
}
/**
* Generates the classifier.
*
* @param instances set of instances serving as training data
* @throws Exception if the classifier has not been generated successfully
*/
public void buildClassifier(Instances instances) throws Exception
{
// can classifier handle the data?
getCapabilities().testWithFail(instances);
// remove instances with missing class
instances = new Instances(instances);
instances.deleteWithMissingClass();
m_Train = new Instances(instances, 0, instances.numInstances());
m_MinArray = new double [m_Train.numAttributes()];//+3?
m_MaxArray = new double [m_Train.numAttributes()];//+3?
for (int i = 0; i < m_Train.numAttributes(); i++)
{
m_MinArray[i] = m_MaxArray[i] = Double.NaN;
}
Enumeration enu = m_Train.enumerateInstances();
while (enu.hasMoreElements())
{
updateMinMax((Instance) enu.nextElement());
}
}
/**
* Updates the classifier.
*
* @param instance the instance to be put into the classifier
* @throws Exception if the instance could not be included successfully
*/
public void updateClassifier(Instance instance) throws Exception
{
if (m_Train.equalHeaders(instance.dataset()) == false)
{
throw new Exception("Incompatible instance types");
}
if (instance.classIsMissing())
{
return;
}
m_Train.add(instance);
updateMinMax(instance);
}
/**
* Classifies the given test instance.
*
* @param instance the instance to be classified
* @return the predicted class for the instance
* @throws Exception if the instance can't be classified
*/
public double classifyInstance(Instance instance) throws Exception
{
if (m_Train.numInstances() == 0)
{
throw new Exception("No training instances!");
}
double distance, minDistance = Double.MAX_VALUE, classValue = 0;
updateMinMax(instance);
Enumeration enu = m_Train.enumerateInstances();
while (enu.hasMoreElements())
{
Instance trainInstance = (Instance) enu.nextElement();
if (!trainInstance.classIsMissing())
{
distance = distance(instance, trainInstance);
if (distance < minDistance)
{
minDistance = distance;
classValue = trainInstance.classValue();
}
}
}
return classValue;
}
/**
* Returns a description of this classifier.
*
* @return a description of this classifier as a string.
*/
public String toString()
{
return ("IBM classifier");
}
/**
* Calculates the distance between two instances
*
* @param first the first instance
* @param second the second instance
* @return the distance between the two given instances
*/
private double distance(Instance first, Instance second)
{
int j, i, index;
int numTrainingClasses = m_Train.numClasses();
int numTrainAttributes = m_Train.numAttributes();
int numTrainingInstances = m_Train.numInstances();
double diff, distance = 0;
// Get a listing of the classes and an array for each currentInstanceple instance
Attribute [] classList = new Attribute[m_Train.numClasses()];
// Declare a double array for storing the number of appearances for classes belonging to class 1.
double[] classCount1 = new double[m_Train.numClasses()];
// Declare a double array for storing the number of appearances for classes beloning to class 2.
double[] classCount2 = new double[m_Train.numClasses()];
Instance currentInstance;
double firstCount;
double secondCount;
double attribDist;
for(i = 0; i < numTrainAttributes; i++)
{
if (i == m_Train.classIndex())
{
continue;
}
if (m_Train.attribute(i).isNominal())
{
// If attribute is nominal
firstCount = 0;
secondCount = 0;
attribDist = 0;
/** Count the number of occurrences of this value for the
* attribute
*/
for(j = 0; j < numTrainingInstances; ++j)
{
/** Set the current training instance to be the analysed to be the
* instance value at j.
*/
currentInstance = m_Train.instance(j);
/** Check to see whether the first instance carries the same attribute value as the
* attribute value for the current training instance.
*/
if ((first.value(i) == currentInstance.value(i)))
{
// Count the number of times first.value(i) has occured by incrementing firstCount.
++firstCount;
// Then increment the classCount1 array to represent secondInstance being classified into classCount1.
++classCount1[(int)currentInstance.classValue()];
}
/** Check to see whether the first instance carries the same value as the
* current training instance.
*/
if ((second.value(i) == currentInstance.value(i)))
{
// Count the number of times second.value(i) has occured by incrementing firstCount.
++secondCount;
// Then increment the classCount2 array to represent secondInstance being classified into classCount2.
++classCount2[(int)currentInstance.classValue()];
}
}
/** Check to see if both values occurred at least once
* correct to avoid the divide by zero problem otherwise
* as per assignment spec
*/
if(firstCount == 0)
{
firstCount = 1;
}
if(secondCount == 0)
{
secondCount = 1;
}
/** Contribute this class values to the running total
* This implements the modification of the Stanfill & Waltz formula on
* page 62 of Cost & Salzberg's paper.
*/
for(index = 0; index < numTrainingClasses; ++index)
{
/**
* Add the absolute value of the quotient of classCount1 and firstCount less the quotient of the classCount2 and secondCount
* in order to determine the attribute Dist value.
*/
attribDist += Math.abs((classCount1[index]) / firstCount - (classCount2[index]) / secondCount);
}
// Calculate the Manhatten difference by adding the attribDist to distance.
distance += attribDist;
}
else
{
// If attribute is numeric
if (first.isMissing(i) || second.isMissing(i))
{
if (first.isMissing(i) && second.isMissing(i))
{
diff = 1;
}
else
{
if (second.isMissing(i))
{
diff = norm(first.value(i), i);
}
else
{
diff = norm(second.value(i), i);
}
if (diff < 0.5)
{
diff = 1.0 - diff;
}
}
}
else
{
diff = norm(first.value(i), i) - norm(second.value(i), i);
}
distance += diff * diff;
}
}
return distance;
}
>>>>>>> IBM dist fix
/**
* Normalizes a given value of a numeric attribute.
*
* @param x the value to be normalized
* @param i the attribute's index
* @return the normalized value
*/
private double norm(double x,int i)
{
if (Double.isNaN(m_MinArray[i])
|| Utils.eq(m_MaxArray[i], m_MinArray[i]))
{
return 0;
}
else
{
return (x - m_MinArray[i]) / (m_MaxArray[i] - m_MinArray[i]);
}
}
/**
* Updates the minimum and maximum values for all the attributes
* based on a new instance.
*
* @param instance the new instance
*/
private void updateMinMax(Instance instance)
{
for (int j = 0;j < m_Train.numAttributes(); j++)
{
if ((m_Train.attribute(j).isNumeric()) && (!instance.isMissing(j)))
{
if (Double.isNaN(m_MinArray[j]))
{
m_MinArray[j] = instance.value(j);
m_MaxArray[j] = instance.value(j);
}
else
{
if (instance.value(j) < m_MinArray[j])
{
m_MinArray[j] = instance.value(j);
}
else
{
if (instance.value(j) > m_MaxArray[j])
{
m_MaxArray[j] = instance.value(j);
}
}
}
}
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision()
{
return RevisionUtils.extract("$Revision: 5525 $");
}
/**
* Main method for testing this class.
*
* @param argv should contain command line arguments for evaluation
* (see Evaluation).
*/
public static void main(String [] argv)
{
runClassifier(new IBM(), argv);
}
}