ID3算法的weka实现 – Lux_Veritas的专栏 – 博客频道 – CSDN.NET

ID3:归纳决策树(Induction Decision Tree Version 3) 

ID3算法一种由数据构造递归的的过程。选择一个属性作为根节点,按照其他属性将数据集分类,每一个子节点得到一个数据集。对这种划分的质量进行评估,递归执行该过程,直至全部节点不能再进行划分。某节点不能划分的条件有2:一个是节点具有单类,二是节点具有单一属性。

质量评估的标准为:

①信息增益:根节点的信息值,与分裂子节点后各节点平均信息值的差

②信息增益率:信息增益有一个弊端,当例如ID码这种对分类结果没有任何用处,但是信息增益极大的属性,仅靠信息增益判断是不行的。

信息增益率 信息增益 节点的固有信息值(不考虑类,仅凭信息量)

虽然ID的信息增益率仍是最高的,但是他的优势已经大大减小了。在实际生产中,会相应处理掉ID码这种无用的属性。

以上是我认为ID3算法的应该注意的几个地方,下面着重分析weka的源码。

 

 

ID3算法的weka实现核心部分在建立树的部分,即makeTree()方法。前期有相关数据集的简单处理,相关作者文献信息等的处理,这里暂不介绍。

首先,Id3类要继承 AbstractClassifier

有一些比较重要的成员变量:

Id3[]成员变量是保存分类树的变量,数组的每一个元素都是当前结点的子结点

m_Attribute变量保存结点进行分裂是基于的属性,即根据哪个属性分裂结点

③如果当前结点为叶子结点,则m_ClassValue变量代表当前结点的类别

m_Distribution说明当前结点属于某种类别的概率

m_ClassAttribute变量为数据集的类别

 

算法的入口为buildClassifier()方法,在其内部调用maketree()方法

其中getCapabilities().testWithFail(data)实际上是在数据的预处理之后,判断给定的数据集是否能被Id3处理。deleteWithMissingClass()Instances类中的方法,作用是移除那些缺失某属性的实例(具体实现见Instances),得到要求的实例集。

 

makeTree()是算法的核心所在。

首先计算最大信息增益

data.numAttributes()返回属性的个数,infoGains保存每一属性的信息增益值。

enumerateAttributes()Instances类中的方法,作用是返回实例集的全部属性的集合类。

computeInfoGain(data, att)是实际计算信息增益值的函数。

最后将具有最大增益的属性赋值给m_Attribute,作为当前结点的分裂属性。

当某结点的信息增益为0时,此结点为叶子结点,不再分裂。

m_Attribute = null,已经为叶结点,分裂属性当然为null。由于m_Distribution保存类别的概率,data.numClasses()获得数据集的类别量。m_Distribution[(int) inst.classValue()]++,用于对属于各个类别的具体实例进行计数。

Utils.normalize()相当于归一化。m_ClassValue为叶子结点的类别,当然是概率最大的为其类别值。

如果不是叶结点,则要在分裂属性上将分裂当前结点。

splitData()为本类中的方法,分裂属性有多少属性值,就将数据集在当前结点分裂出多少棵子树,即:Instances[] splitData = new Instances[att.numValues()]。然后将将每一个新分裂出的数据集声明为足够大的集合类,详见Instances类中双参数的构造方法。

inst.value(att),取得属性的值,根据属性的值将各实例分配到分裂出的数据集中。最后compactify()用于调整集合类到最小容量。

    最后将每一个m_Successors声明为一个Id3类,并递归调用执行makeTree(),将每一子树进行分裂,直至到全部叶结点,程序退出。

同学,你好!
weka本身就是开源的!
你如果已经下载并安装了weka,那么你只要进入安装目录,找到“weka-src.jar“这个文件,解压缩,或者直接用eclipse打开,那么所有的源代码都在你眼前!
ID3位置:”weka-src.jar\src\main\java\weka\classifiers\trees\ID3.java“

/*
*    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.
*/
/*
*    Id3.java
*    Copyright (C) 1999 University of Waikato, Hamilton, New Zealand
*
*/
package weka.classifiers.trees;
import weka.classifiers.Classifier;
import weka.classifiers.Sourcable;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.NoSupportForMissingValuesException;
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.util.Enumeration;
/**
<!-- globalinfo-start -->
* 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:
*
* R. Quinlan (1986). Induction of decision trees. Machine Learning. 1(1):81-106.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @article{Quinlan1986,
*    author = {R. Quinlan},
*    journal = {Machine Learning},
*    number = {1},
*    pages = {81-106},
*    title = {Induction of decision trees},
*    volume = {1},
*    year = {1986}
* }
* </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 Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision: 6404 $
*/
public class Id3
extends Classifier
implements TechnicalInformationHandler, Sourcable {
/** for serialization */
static final long serialVersionUID = -2693678647096322561L;
/** The node's successors. */
private Id3[] m_Successors;
/** Attribute used for splitting. */
private Attribute m_Attribute;
/** Class value if node is leaf. */
private double m_ClassValue;
/** Class distribution if node is leaf. */
private double[] m_Distribution;
/** Class attribute of dataset. */
private Attribute m_ClassAttribute;
/**
* Returns a string describing the classifier.
* @return a description suitable for the GUI.
*/
public String globalInfo() {
return  "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: \n\n"
+ getTechnicalInformation().toString();
}
/**
* 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, "R. Quinlan");
result.setValue(Field.YEAR, "1986");
result.setValue(Field.TITLE, "Induction of decision trees");
result.setValue(Field.JOURNAL, "Machine Learning");
result.setValue(Field.VOLUME, "1");
result.setValue(Field.NUMBER, "1");
result.setValue(Field.PAGES, "81-106");
return result;
}
/**
* 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);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
// instances
result.setMinimumNumberInstances(0);
return result;
}
/**
* Builds Id3 decision tree classifier.
*
* @param data the training data
* @exception Exception if classifier can't be built successfully
*/
public void buildClassifier(Instances data) throws Exception {
// can classifier handle the data?
getCapabilities().testWithFail(data);
// remove instances with missing class
data = new Instances(data);
data.deleteWithMissingClass();
makeTree(data);
}
/**
* Method for building an Id3 tree.
*
* @param data the training data
* @exception Exception if decision tree can't be built successfully
*/
private void makeTree(Instances data) throws Exception {
// Check if no instances have reached this node.
if (data.numInstances() == 0) {
m_Attribute = null;
m_ClassValue = Instance.missingValue();
m_Distribution = new double[data.numClasses()];
return;
}
// Compute attribute with maximum information gain.
double[] infoGains = new double[data.numAttributes()];
Enumeration attEnum = data.enumerateAttributes();
while (attEnum.hasMoreElements()) {
Attribute att = (Attribute) attEnum.nextElement();
infoGains[att.index()] = computeInfoGain(data, att);
}
m_Attribute = data.attribute(Utils.maxIndex(infoGains));
// Make leaf if information gain is zero.
// Otherwise create successors.
if (Utils.eq(infoGains[m_Attribute.index()], 0)) {
m_Attribute = null;
m_Distribution = new double[data.numClasses()];
Enumeration instEnum = data.enumerateInstances();
while (instEnum.hasMoreElements()) {
Instance inst = (Instance) instEnum.nextElement();
m_Distribution[(int) inst.classValue()]++;
}
Utils.normalize(m_Distribution);
m_ClassValue = Utils.maxIndex(m_Distribution);
m_ClassAttribute = data.classAttribute();
} else {
Instances[] splitData = splitData(data, m_Attribute);
m_Successors = new Id3[m_Attribute.numValues()];
for (int j = 0; j < m_Attribute.numValues(); j++) {
m_Successors[j] = new Id3();
m_Successors[j].makeTree(splitData[j]);
}
}
}
/**
* Classifies a given test instance using the decision tree.
*
* @param instance the instance to be classified
* @return the classification
* @throws NoSupportForMissingValuesException if instance has missing values
*/
public double classifyInstance(Instance instance)
throws NoSupportForMissingValuesException {
if (instance.hasMissingValue()) {
throw new NoSupportForMissingValuesException("Id3: no missing values, "
+ "please.");
}
if (m_Attribute == null) {
return m_ClassValue;
} else {
return m_Successors[(int) instance.value(m_Attribute)].
classifyInstance(instance);
}
}
/**
* Computes class distribution for instance using decision tree.
*
* @param instance the instance for which distribution is to be computed
* @return the class distribution for the given instance
* @throws NoSupportForMissingValuesException if instance has missing values
*/
public double[] distributionForInstance(Instance instance)
throws NoSupportForMissingValuesException {
if (instance.hasMissingValue()) {
throw new NoSupportForMissingValuesException("Id3: no missing values, "
+ "please.");
}
if (m_Attribute == null) {
return m_Distribution;
} else {
return m_Successors[(int) instance.value(m_Attribute)].
distributionForInstance(instance);
}
}
/**
* Prints the decision tree using the private toString method from below.
*
* @return a textual description of the classifier
*/
public String toString() {
if ((m_Distribution == null) && (m_Successors == null)) {
return "Id3: No model built yet.";
}
return "Id3\n\n" + toString(0);
}
/**
* Computes information gain for an attribute.
*
* @param data the data for which info gain is to be computed
* @param att the attribute
* @return the information gain for the given attribute and data
* @throws Exception if computation fails
*/
private double computeInfoGain(Instances data, Attribute att)
throws Exception {
double infoGain = computeEntropy(data);
Instances[] splitData = splitData(data, att);
for (int j = 0; j < att.numValues(); j++) {
if (splitData[j].numInstances() > 0) {
infoGain -= ((double) splitData[j].numInstances() /
(double) data.numInstances()) *
computeEntropy(splitData[j]);
}
}
return infoGain;
}
/**
* Computes the entropy of a dataset.
*
* @param data the data for which entropy is to be computed
* @return the entropy of the data's class distribution
* @throws Exception if computation fails
*/
private double computeEntropy(Instances data) throws Exception {
double [] classCounts = new double[data.numClasses()];
Enumeration instEnum = data.enumerateInstances();
while (instEnum.hasMoreElements()) {
Instance inst = (Instance) instEnum.nextElement();
classCounts[(int) inst.classValue()]++;
}
double entropy = 0;
for (int j = 0; j < data.numClasses(); j++) {
if (classCounts[j] > 0) {
entropy -= classCounts[j] * Utils.log2(classCounts[j]);
}
}
entropy /= (double) data.numInstances();
return entropy + Utils.log2(data.numInstances());
}
/**
* Splits a dataset according to the values of a nominal attribute.
*
* @param data the data which is to be split
* @param att the attribute to be used for splitting
* @return the sets of instances produced by the split
*/
private Instances[] splitData(Instances data, Attribute att) {
Instances[] splitData = new Instances[att.numValues()];
for (int j = 0; j < att.numValues(); j++) {
splitData[j] = new Instances(data, data.numInstances());
}
Enumeration instEnum = data.enumerateInstances();
while (instEnum.hasMoreElements()) {
Instance inst = (Instance) instEnum.nextElement();
splitData[(int) inst.value(att)].add(inst);
}
for (int i = 0; i < splitData.length; i++) {
splitData[i].compactify();
}
return splitData;
}
/**
* Outputs a tree at a certain level.
*
* @param level the level at which the tree is to be printed
* @return the tree as string at the given level
*/
private String toString(int level) {
StringBuffer text = new StringBuffer();
if (m_Attribute == null) {
if (Instance.isMissingValue(m_ClassValue)) {
text.append(": null");
} else {
text.append(": " + m_ClassAttribute.value((int) m_ClassValue));
}
} else {
for (int j = 0; j < m_Attribute.numValues(); j++) {
text.append("\n");
for (int i = 0; i < level; i++) {
text.append("|  ");
}
text.append(m_Attribute.name() + " = " + m_Attribute.value(j));
text.append(m_Successors[j].toString(level + 1));
}
}
return text.toString();
}
/**
* Adds this tree recursively to the buffer.
*
* @param id          the unqiue id for the method
* @param buffer      the buffer to add the source code to
* @return            the last ID being used
* @throws Exception  if something goes wrong
*/
protected int toSource(int id, StringBuffer buffer) throws Exception {
int                 result;
int                 i;
int                 newID;
StringBuffer[]      subBuffers;
buffer.append("\n");
buffer.append("  protected static double node" + id + "(Object[] i) {\n");
// leaf?
if (m_Attribute == null) {
result = id;
if (Double.isNaN(m_ClassValue)) {
buffer.append("    return Double.NaN;");
} else {
buffer.append("    return " + m_ClassValue + ";");
}
if (m_ClassAttribute != null) {
buffer.append(" // " + m_ClassAttribute.value((int) m_ClassValue));
}
buffer.append("\n");
buffer.append("  }\n");
} else {
buffer.append("    checkMissing(i, " + m_Attribute.index() + ");\n\n");
buffer.append("    // " + m_Attribute.name() + "\n");
// subtree calls
subBuffers = new StringBuffer[m_Attribute.numValues()];
newID = id;
for (i = 0; i < m_Attribute.numValues(); i++) {
newID++;
buffer.append("    ");
if (i > 0) {
buffer.append("else ");
}
buffer.append("if (((String) i[" + m_Attribute.index()
+ "]).equals(\"" + m_Attribute.value(i) + "\"))\n");
buffer.append("      return node" + newID + "(i);\n");
subBuffers[i] = new StringBuffer();
newID = m_Successors[i].toSource(newID, subBuffers[i]);
}
buffer.append("    else\n");
buffer.append("      throw new IllegalArgumentException(\"Value '\" + i["
+ m_Attribute.index() + "] + \"' is not allowed!\");\n");
buffer.append("  }\n");
// output subtree code
for (i = 0; i < m_Attribute.numValues(); i++) {
buffer.append(subBuffers[i].toString());
}
subBuffers = null;
result = newID;
}
return result;
}
/**
* Returns a string that describes the classifier as source. The
* classifier will be contained in a class with the given name (there may
* be auxiliary classes),
* and will contain a method with the signature:
* <pre><code>
* public static double classify(Object[] i);
* </code></pre>
* where the array <code>i</code> contains elements that are either
* Double, String, with missing values represented as null. The generated
* code is public domain and comes with no warranty.
* Note: works only if class attribute is the last attribute in the dataset.
*
* @param className the name that should be given to the source class.
* @return the object source described by a string
* @throws Exception if the source can't be computed
*/
public String toSource(String className) throws Exception {
StringBuffer        result;
int                 id;
result = new StringBuffer();
result.append("class " + className + " {\n");
result.append("  private static void checkMissing(Object[] i, int index) {\n");
result.append("    if (i[index] == null)\n");
result.append("      throw new IllegalArgumentException(\"Null values "
+ "are not allowed!\");\n");
result.append("  }\n\n");
result.append("  public static double classify(Object[] i) {\n");
id = 0;
result.append("    return node" + id + "(i);\n");
result.append("  }\n");
toSource(id, result);
result.append("}\n");
return result.toString();
}
/**
* Returns the revision string.
*
* @return        the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision: 6404 $");
}
/**
* Main method.
*
* @param args the options for the classifier
*/
public static void main(String[] args) {
runClassifier(new Id3(), args);
}
}

来源URL:http://cache.baiducontent.com/c?m=9f65cb4a8c8507ed4fece7631046893b4c4380146d96864968d4e414c422461f002cf4bc5366474488832f261cfc091ab1a168252a5577f1c893d60bc0bc98292582263f6459db0144dc5cf8921532c151cb0ce8b81897ad814284d9d3c4af5144b959&p=8b2a975486cc41ac5ead8268460e9c&newp=98759a45d5c51df20be2963c5c5d8f231610db2151d1d64922&user=baidu&fm=sc&query=weka+id3%CB%E3%B7%A8&qid=9d1f723400018f5f&p1=2