package DecisionTree;

import java.io.*;
import java.util.*; public class ID3 { //节点类
public class DTNode {
private String attribute;
private HashMap<String, DTNode> children = new HashMap<String, DTNode>();
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public HashMap<String, DTNode> getChildren() {
return children;
}
public void setChildren(HashMap<String, DTNode> children) {
this.children = children;
}
} private String decisionColumn; //决定字段 public String getDecisionColumn() {
return decisionColumn;
} public void setDecisionColumn(String decisionColumn) {
this.decisionColumn = decisionColumn;
} //统计每个属性在集合中出现的次数
public HashMap<String, Integer> getTypeCounts(ArrayList<String> dataset) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < dataset.size(); i++) {
String key = dataset.get(i);
if(!map.containsKey(key))
map.put(key, 1);
else
map.put(key, map.get(key)+1);
}
return map;
} //获取key的indexlist
public ArrayList<Integer> getIndex(String key, ArrayList<String> dataset){
ArrayList<Integer> indexlist = new ArrayList<Integer>(); for(int i = 0; i < dataset.size(); i++){
if(key.equals(dataset.get(i)))
indexlist.add(Integer.valueOf(i));
}
return indexlist;
} //根据index获取数据集
public ArrayList<String> getSubset(ArrayList<Integer> indexlist, ArrayList<String> dataset) {
ArrayList<String> subset = new ArrayList<String>();
for(Integer i : indexlist){
subset.add(dataset.get(i.intValue()));
}
return subset;
} //计算信息熵
public double getEntropy(ArrayList<String> dataset) {
double entropy = 0;
double prob = 0;
int sum = dataset.size();
HashMap<String, Integer> map = getTypeCounts(dataset);
Iterator<String> iter = map.keySet().iterator();
while(iter.hasNext()){
String key = iter.next();
prob = (double)map.get(key).intValue()/sum;
entropy += -1*prob*Math.log10(prob)/Math.log10(2);
}
return entropy;
} //计算已知条件下的信息熵
public double getConditionEntropy(HashMap<String, ArrayList<String>> dataset, String IndexCol) {
double entropy = 0;
double prob = 0;
int sum = dataset.get(IndexCol).size();
HashMap<String, Integer> map = getTypeCounts(dataset.get(IndexCol));
Iterator<String> iter = map.keySet().iterator();
while(iter.hasNext()){
String key = iter.next();
prob = (double)map.get(key)/sum;
entropy+=prob*getEntropy(getSubset(getIndex(key,dataset.get(IndexCol)),dataset.get(this.decisionColumn)));
}
return entropy;
} //建立决策树
public DTNode buildDT(HashMap<String, ArrayList<String>>dataset) { DTNode node = new DTNode();
double info_entropy = getEntropy(dataset.get(this.decisionColumn));
//递归结束条件
if(info_entropy == 0){
node.setAttribute((dataset.get(this.decisionColumn).get(0)));
return node;
} //求出拥有最小熵数据集的column,即最大entropy gain
double max_gain = 0; //设置默认值
double gain = 0;
String max_column="";
Iterator<String> entropy_iter = dataset.keySet().iterator(); while(entropy_iter.hasNext()){
String key = entropy_iter.next();
if(key.equals(this.decisionColumn))
continue;
gain = getEntropy(dataset.get(decisionColumn)) - getConditionEntropy(dataset,key); //计算信息增益
if(gain > max_gain){
max_gain = gain;
max_column = key;
}
} node.setAttribute(max_column);
ArrayList<String> ds = dataset.get(max_column); //最小熵数据集 //生成新数据集
Iterator<String> iter = getTypeCounts(ds).keySet().iterator();
while(iter.hasNext()){
String key = iter.next();
HashMap<String, ArrayList<String>> subset = new HashMap<String, ArrayList<String>>();
DTNode childNode;
ArrayList<Integer> indexlist = getIndex(key,ds);
Iterator<String> sub_iter = dataset.keySet().iterator();
while(sub_iter.hasNext()){
String sub_key = sub_iter.next();
if(!sub_key.equals(max_column))
subset.put(sub_key, getSubset(indexlist,dataset.get(sub_key)));
} childNode = buildDT(subset);
node.getChildren().put(key, childNode);
} return node;
} //输出树
public void printDT(DTNode root){ if(root == null)
return;
System.out.println(root.attribute);
if(root.getChildren() == null)
return; Iterator<String> iter = root.getChildren().keySet().iterator();
while(iter.hasNext()){
String key = iter.next();
System.out.print(key+" ");
printDT(root.getChildren().get(key));
}
} //读取源文件
public HashMap<String,ArrayList<String>> read(String path){
HashMap<String,ArrayList<String>> dataset = new HashMap<String,ArrayList<String>>();
try{
File file = new File(path);
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader input = new InputStreamReader(new FileInputStream(file),"UTF-8");
BufferedReader read = new BufferedReader(input);
String line = null; ArrayList<ArrayList<String>> ds = new ArrayList<ArrayList<String>>();
while((line = read.readLine()) != null){
String[] data = line.split(",");
ArrayList<String> temp = new ArrayList<String>();
for(int i = 0; i < data.length; i++)
temp.add(data[i]);
ds.add(temp);
} for(int i = 0; i < ds.get(0).size(); i++){
ArrayList<String> newds = new ArrayList<String>();
for(int j = 0; j < ds.size(); j++){
newds.add(ds.get(j).get(i));
}
String key = newds.get(0);
newds.remove(0);
dataset.put(key,newds);
}
input.close();
}
}catch(Exception e){
e.printStackTrace();
} return dataset;
} public static void main(String[] args) {
ID3 tree = new ID3();
HashMap<String,ArrayList<String>> ds = tree.read("C:"+File.separator+"Users"+File.separator+"mhua005"+File.separator+
"Desktop"+File.separator+"sample.txt");
tree.setDecisionColumn("play");
ArrayList<String> attr = new ArrayList<String>();
attr.add("outlook");
attr.add("temperature");
attr.add("humidity");
attr.add("windy");
attr.add("play");
DTNode root = tree.buildDT(ds);
tree.printDT(root);
}
}

源文件内容:

outlook,temperature,humidity,windy,play
sunny,hot,high,FALSE,no
sunny,hot,high,TRUE,no
overcast,hot,high,FALSE,yes
rainy,mild,high,FALSE,yes
rainy,cool,normal,FALSE,yes
rainy,cool,normal,TRUE,no
overcast,cool,normal,TRUE,yes
sunny,mild,high,FALSE,no
sunny,cool,normal,FALSE,yes
rainy,mild,normal,FALSE,yes
sunny,mild,normal,TRUE,yes
overcast,mild,high,TRUE,yes
overcast,hot,normal,FALSE,yes
rainy,mild,high,TRUE,no

ID3决策树的Java实现的更多相关文章

  1. ID3决策树预测的java实现

    刚才写了ID3决策树的建立,这个是通过决策树来进行预测.这里主要用到的就是XML的遍历解析,比较简单. 关于xml的解析,参考了: http://blog.csdn.net/soszou/articl ...

  2. ID3算法(Java实现)

    数据存储文件:buycomputer.properties #数据个数 datanum=14 #属性及属性值 nodeAndAttribute=年龄:青/中/老,收入:高/中/低,学生:是/否,信誉: ...

  3. Python3实现机器学习经典算法(三)ID3决策树

    一.ID3决策树概述 ID3决策树是另一种非常重要的用来处理分类问题的结构,它形似一个嵌套N层的IF…ELSE结构,但是它的判断标准不再是一个关系表达式,而是对应的模块的信息增益.它通过信息增益的大小 ...

  4. 决策树ID3算法的java实现(基本试用所有的ID3)

    已知:流感训练数据集,预定义两个类别: 求:用ID3算法建立流感的属性描述决策树 流感训练数据集 No. 头痛 肌肉痛 体温 患流感 1 是(1) 是(1) 正常(0) 否(0) 2 是(1) 是(1 ...

  5. 决策树ID3算法的java实现

    决策树的分类过程和人的决策过程比较相似,就是先挑“权重”最大的那个考虑,然后再往下细分.比如你去看医生,症状是流鼻涕,咳嗽等,那么医生就会根据你的流鼻涕这个权重最大的症状先认为你是感冒,接着再根据你咳 ...

  6. 决策树ID3算法的java实现(基本适用所有的ID3)

    已知:流感训练数据集,预定义两个类别: 求:用ID3算法建立流感的属性描述决策树 流感训练数据集 No. 头痛 肌肉痛 体温 患流感 1 是(1) 是(1) 正常(0) 否(0) 2 是(1) 是(1 ...

  7. ID3决策树---Java

    1)熵与信息增益: 2)以下是实现代码: //import java.awt.color.ICC_ColorSpace; import java.io.*; import java.util.Arra ...

  8. java编写ID3决策树

    说明:每个样本都会装入Data样本对象,决策树生成算法接收的是一个Array<Data>样本列表,所以构建测试数据时也要符合格式,最后生成的决策树是树的根节点,通过里面提供的showTre ...

  9. python ID3决策树实现

    环境:ubuntu 16.04 python 3.6 数据来源:UCI wine_data(比较经典的酒数据) 决策树要点: 1. 如何确定分裂点(CART ID3 C4.5算法有着对应的分裂计算方式 ...

随机推荐

  1. 20145308刘昊阳 《Java程序设计》第3周学习总结

    20145308刘昊阳 <Java程序设计>第3周学习总结 教材学习内容总结 第四章 认识对象 要产生对象必须先定义类,类是对象的设计图,对象是类的实例 类是从少数实例推广到大量相似实例的 ...

  2. ACM:a^b%p-数论-快速幂-快速乘

    a^b Time Limit: 1000MS   Memory Limit: 65535KB   64bit IO Format: Description 求a的b次方,取模mod(1<=a,b ...

  3. PHP面向对象学习六 多态

    OOP的模式并不仅仅是把很多函数和功能集合起来,目的而是使用类,继承,多态的方式描述我们生活中的一种情况.从而使得我们的代码更具有“物”的意义.帮助我们减少一些重复性的代码和条件语句的判断.   运算 ...

  4. 九、UINavigationController切换视图 实例

    现版本 SDK 8.4 Xcode 运行Xcode 选择 Create a new Xcode project ->Single View Application 命名 NavigationCo ...

  5. List<string>中的泛型委托

    我们先看List<T>.Sort().其定义是:public void Sort( Comparison<T> comparison ) 其要求传入的参数是Comparison ...

  6. MVVMLight Messenging

    Basically there are two possible ways to send a message, first using an overload of the RaisePropert ...

  7. js如何使得新打开的窗口居中

    <a href="#" class="blue" onclick="window.open('/Content/service.html', ' ...

  8. 快排java实现

    package sort; public class QuickSort { public static final int cutoff = 3; /** * insertion sort * * ...

  9. Android studio使用增量更新进行版本升级

    今天将Android Studio更新了一下,特此记录一下升级过程,以后可能还会用得着. 首先通过菜单栏进入 Help --> Check for update 查看下当前版本是否需要更新.事实 ...

  10. [CareerCup] 17.5 Game of Master Mind 猜字游戏

    17.5 The Came of Master Mind is played as follows: The computer has four slots, and each slot will c ...