Source Code Cross Referenced for Id3.java in  » Science » weka » weka » classifiers » trees » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Science » weka » weka.classifiers.trees 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         *    This program is free software; you can redistribute it and/or modify
003:         *    it under the terms of the GNU General Public License as published by
004:         *    the Free Software Foundation; either version 2 of the License, or
005:         *    (at your option) any later version.
006:         *
007:         *    This program is distributed in the hope that it will be useful,
008:         *    but WITHOUT ANY WARRANTY; without even the implied warranty of
009:         *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
010:         *    GNU General Public License for more details.
011:         *
012:         *    You should have received a copy of the GNU General Public License
013:         *    along with this program; if not, write to the Free Software
014:         *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
015:         */
016:
017:        /*
018:         *    Id3.java
019:         *    Copyright (C) 1999 University of Waikato, Hamilton, New Zealand
020:         *
021:         */
022:
023:        package weka.classifiers.trees;
024:
025:        import weka.classifiers.Classifier;
026:        import weka.core.Attribute;
027:        import weka.core.Capabilities;
028:        import weka.core.Instance;
029:        import weka.core.Instances;
030:        import weka.core.NoSupportForMissingValuesException;
031:        import weka.core.TechnicalInformation;
032:        import weka.core.TechnicalInformationHandler;
033:        import weka.core.Utils;
034:        import weka.core.Capabilities.Capability;
035:        import weka.core.TechnicalInformation.Field;
036:        import weka.core.TechnicalInformation.Type;
037:
038:        import java.util.Enumeration;
039:
040:        /**
041:         <!-- globalinfo-start -->
042:         * Class for constructing an unpruned decision tree based on the ID3 algorithm. Can only deal with nominal attributes. No missing values allowed. Empty leaves may result in unclassified instances. For more information see: <br/>
043:         * <br/>
044:         * R. Quinlan (1986). Induction of decision trees. Machine Learning. 1(1):81-106.
045:         * <p/>
046:         <!-- globalinfo-end -->
047:         *
048:         <!-- technical-bibtex-start -->
049:         * BibTeX:
050:         * <pre>
051:         * &#64;article{Quinlan1986,
052:         *    author = {R. Quinlan},
053:         *    journal = {Machine Learning},
054:         *    number = {1},
055:         *    pages = {81-106},
056:         *    title = {Induction of decision trees},
057:         *    volume = {1},
058:         *    year = {1986}
059:         * }
060:         * </pre>
061:         * <p/>
062:         <!-- technical-bibtex-end -->
063:         *
064:         <!-- options-start -->
065:         * Valid options are: <p/>
066:         * 
067:         * <pre> -D
068:         *  If set, classifier is run in debug mode and
069:         *  may output additional info to the console</pre>
070:         * 
071:         <!-- options-end -->
072:         *
073:         * @author Eibe Frank (eibe@cs.waikato.ac.nz)
074:         * @version $Revision: 1.20 $ 
075:         */
076:        public class Id3 extends Classifier implements 
077:                TechnicalInformationHandler {
078:
079:            /** for serialization */
080:            static final long serialVersionUID = -2693678647096322561L;
081:
082:            /** The node's successors. */
083:            private Id3[] m_Successors;
084:
085:            /** Attribute used for splitting. */
086:            private Attribute m_Attribute;
087:
088:            /** Class value if node is leaf. */
089:            private double m_ClassValue;
090:
091:            /** Class distribution if node is leaf. */
092:            private double[] m_Distribution;
093:
094:            /** Class attribute of dataset. */
095:            private Attribute m_ClassAttribute;
096:
097:            /**
098:             * Returns a string describing the classifier.
099:             * @return a description suitable for the GUI.
100:             */
101:            public String globalInfo() {
102:
103:                return "Class for constructing an unpruned decision tree based on the ID3 "
104:                        + "algorithm. Can only deal with nominal attributes. No missing values "
105:                        + "allowed. Empty leaves may result in unclassified instances. For more "
106:                        + "information see: \n\n"
107:                        + getTechnicalInformation().toString();
108:            }
109:
110:            /**
111:             * Returns an instance of a TechnicalInformation object, containing 
112:             * detailed information about the technical background of this class,
113:             * e.g., paper reference or book this class is based on.
114:             * 
115:             * @return the technical information about this class
116:             */
117:            public TechnicalInformation getTechnicalInformation() {
118:                TechnicalInformation result;
119:
120:                result = new TechnicalInformation(Type.ARTICLE);
121:                result.setValue(Field.AUTHOR, "R. Quinlan");
122:                result.setValue(Field.YEAR, "1986");
123:                result.setValue(Field.TITLE, "Induction of decision trees");
124:                result.setValue(Field.JOURNAL, "Machine Learning");
125:                result.setValue(Field.VOLUME, "1");
126:                result.setValue(Field.NUMBER, "1");
127:                result.setValue(Field.PAGES, "81-106");
128:
129:                return result;
130:            }
131:
132:            /**
133:             * Returns default capabilities of the classifier.
134:             *
135:             * @return      the capabilities of this classifier
136:             */
137:            public Capabilities getCapabilities() {
138:                Capabilities result = super .getCapabilities();
139:
140:                // attributes
141:                result.enable(Capability.NOMINAL_ATTRIBUTES);
142:
143:                // class
144:                result.enable(Capability.NOMINAL_CLASS);
145:                result.enable(Capability.MISSING_CLASS_VALUES);
146:
147:                // instances
148:                result.setMinimumNumberInstances(0);
149:
150:                return result;
151:            }
152:
153:            /**
154:             * Builds Id3 decision tree classifier.
155:             *
156:             * @param data the training data
157:             * @exception Exception if classifier can't be built successfully
158:             */
159:            public void buildClassifier(Instances data) throws Exception {
160:
161:                // can classifier handle the data?
162:                getCapabilities().testWithFail(data);
163:
164:                // remove instances with missing class
165:                data = new Instances(data);
166:                data.deleteWithMissingClass();
167:
168:                makeTree(data);
169:            }
170:
171:            /**
172:             * Method for building an Id3 tree.
173:             *
174:             * @param data the training data
175:             * @exception Exception if decision tree can't be built successfully
176:             */
177:            private void makeTree(Instances data) throws Exception {
178:
179:                // Check if no instances have reached this node.
180:                if (data.numInstances() == 0) {
181:                    m_Attribute = null;
182:                    m_ClassValue = Instance.missingValue();
183:                    m_Distribution = new double[data.numClasses()];
184:                    return;
185:                }
186:
187:                // Compute attribute with maximum information gain.
188:                double[] infoGains = new double[data.numAttributes()];
189:                Enumeration attEnum = data.enumerateAttributes();
190:                while (attEnum.hasMoreElements()) {
191:                    Attribute att = (Attribute) attEnum.nextElement();
192:                    infoGains[att.index()] = computeInfoGain(data, att);
193:                }
194:                m_Attribute = data.attribute(Utils.maxIndex(infoGains));
195:
196:                // Make leaf if information gain is zero. 
197:                // Otherwise create successors.
198:                if (Utils.eq(infoGains[m_Attribute.index()], 0)) {
199:                    m_Attribute = null;
200:                    m_Distribution = new double[data.numClasses()];
201:                    Enumeration instEnum = data.enumerateInstances();
202:                    while (instEnum.hasMoreElements()) {
203:                        Instance inst = (Instance) instEnum.nextElement();
204:                        m_Distribution[(int) inst.classValue()]++;
205:                    }
206:                    Utils.normalize(m_Distribution);
207:                    m_ClassValue = Utils.maxIndex(m_Distribution);
208:                    m_ClassAttribute = data.classAttribute();
209:                } else {
210:                    Instances[] splitData = splitData(data, m_Attribute);
211:                    m_Successors = new Id3[m_Attribute.numValues()];
212:                    for (int j = 0; j < m_Attribute.numValues(); j++) {
213:                        m_Successors[j] = new Id3();
214:                        m_Successors[j].makeTree(splitData[j]);
215:                    }
216:                }
217:            }
218:
219:            /**
220:             * Classifies a given test instance using the decision tree.
221:             *
222:             * @param instance the instance to be classified
223:             * @return the classification
224:             * @throws NoSupportForMissingValuesException if instance has missing values
225:             */
226:            public double classifyInstance(Instance instance)
227:                    throws NoSupportForMissingValuesException {
228:
229:                if (instance.hasMissingValue()) {
230:                    throw new NoSupportForMissingValuesException(
231:                            "Id3: no missing values, " + "please.");
232:                }
233:                if (m_Attribute == null) {
234:                    return m_ClassValue;
235:                } else {
236:                    return m_Successors[(int) instance.value(m_Attribute)]
237:                            .classifyInstance(instance);
238:                }
239:            }
240:
241:            /**
242:             * Computes class distribution for instance using decision tree.
243:             *
244:             * @param instance the instance for which distribution is to be computed
245:             * @return the class distribution for the given instance
246:             * @throws NoSupportForMissingValuesException if instance has missing values
247:             */
248:            public double[] distributionForInstance(Instance instance)
249:                    throws NoSupportForMissingValuesException {
250:
251:                if (instance.hasMissingValue()) {
252:                    throw new NoSupportForMissingValuesException(
253:                            "Id3: no missing values, " + "please.");
254:                }
255:                if (m_Attribute == null) {
256:                    return m_Distribution;
257:                } else {
258:                    return m_Successors[(int) instance.value(m_Attribute)]
259:                            .distributionForInstance(instance);
260:                }
261:            }
262:
263:            /**
264:             * Prints the decision tree using the private toString method from below.
265:             *
266:             * @return a textual description of the classifier
267:             */
268:            public String toString() {
269:
270:                if ((m_Distribution == null) && (m_Successors == null)) {
271:                    return "Id3: No model built yet.";
272:                }
273:                return "Id3\n\n" + toString(0);
274:            }
275:
276:            /**
277:             * Computes information gain for an attribute.
278:             *
279:             * @param data the data for which info gain is to be computed
280:             * @param att the attribute
281:             * @return the information gain for the given attribute and data
282:             * @throws Exception if computation fails
283:             */
284:            private double computeInfoGain(Instances data, Attribute att)
285:                    throws Exception {
286:
287:                double infoGain = computeEntropy(data);
288:                Instances[] splitData = splitData(data, att);
289:                for (int j = 0; j < att.numValues(); j++) {
290:                    if (splitData[j].numInstances() > 0) {
291:                        infoGain -= ((double) splitData[j].numInstances() / (double) data
292:                                .numInstances())
293:                                * computeEntropy(splitData[j]);
294:                    }
295:                }
296:                return infoGain;
297:            }
298:
299:            /**
300:             * Computes the entropy of a dataset.
301:             * 
302:             * @param data the data for which entropy is to be computed
303:             * @return the entropy of the data's class distribution
304:             * @throws Exception if computation fails
305:             */
306:            private double computeEntropy(Instances data) throws Exception {
307:
308:                double[] classCounts = new double[data.numClasses()];
309:                Enumeration instEnum = data.enumerateInstances();
310:                while (instEnum.hasMoreElements()) {
311:                    Instance inst = (Instance) instEnum.nextElement();
312:                    classCounts[(int) inst.classValue()]++;
313:                }
314:                double entropy = 0;
315:                for (int j = 0; j < data.numClasses(); j++) {
316:                    if (classCounts[j] > 0) {
317:                        entropy -= classCounts[j] * Utils.log2(classCounts[j]);
318:                    }
319:                }
320:                entropy /= (double) data.numInstances();
321:                return entropy + Utils.log2(data.numInstances());
322:            }
323:
324:            /**
325:             * Splits a dataset according to the values of a nominal attribute.
326:             *
327:             * @param data the data which is to be split
328:             * @param att the attribute to be used for splitting
329:             * @return the sets of instances produced by the split
330:             */
331:            private Instances[] splitData(Instances data, Attribute att) {
332:
333:                Instances[] splitData = new Instances[att.numValues()];
334:                for (int j = 0; j < att.numValues(); j++) {
335:                    splitData[j] = new Instances(data, data.numInstances());
336:                }
337:                Enumeration instEnum = data.enumerateInstances();
338:                while (instEnum.hasMoreElements()) {
339:                    Instance inst = (Instance) instEnum.nextElement();
340:                    splitData[(int) inst.value(att)].add(inst);
341:                }
342:                for (int i = 0; i < splitData.length; i++) {
343:                    splitData[i].compactify();
344:                }
345:                return splitData;
346:            }
347:
348:            /**
349:             * Outputs a tree at a certain level.
350:             *
351:             * @param level the level at which the tree is to be printed
352:             * @return the tree as string at the given level
353:             */
354:            private String toString(int level) {
355:
356:                StringBuffer text = new StringBuffer();
357:
358:                if (m_Attribute == null) {
359:                    if (Instance.isMissingValue(m_ClassValue)) {
360:                        text.append(": null");
361:                    } else {
362:                        text.append(": "
363:                                + m_ClassAttribute.value((int) m_ClassValue));
364:                    }
365:                } else {
366:                    for (int j = 0; j < m_Attribute.numValues(); j++) {
367:                        text.append("\n");
368:                        for (int i = 0; i < level; i++) {
369:                            text.append("|  ");
370:                        }
371:                        text.append(m_Attribute.name() + " = "
372:                                + m_Attribute.value(j));
373:                        text.append(m_Successors[j].toString(level + 1));
374:                    }
375:                }
376:                return text.toString();
377:            }
378:
379:            /**
380:             * Main method.
381:             *
382:             * @param args the options for the classifier
383:             */
384:            public static void main(String[] args) {
385:                runClassifier(new Id3(), args);
386:            }
387:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.