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. Android中使用反应式编程RxJava

    GitHut 地址: https://github.com/ReactiveX/RxAndroid (1)RxJava简介: RxJava 是一个在Java虚拟机上实现的响应式扩展库:提供了基于obs ...

  2. 【BZOJ】2237: [NCPC2009]Flight Planning

    题意 \(n(1 \le n \le 2500)\)个点的树,求删掉一条边再加上一条边使得还是一棵树,且任意两点最大距离最小. 分析 考虑枚举删掉每一条边,我们只需要考虑如何加边容易求得新树的最大距离 ...

  3. 配置安装CocoPods后进行 项目基本配置

    配置安装CocoPods后进行 项目基本配置总结 1)终端在文件根目录下输入 $ touch Podfile 创建一个空白的Podfile文件 2)然后在使用编辑器打开Podfile文件进行需要配置的 ...

  4. Java_Servlet 中文乱码问题及解决方案剖析

    一.常识了解 1.GBK包含GB2312,即如果通过GB2312编码后可以通过GBK解码,反之可能不成立; 2.java.nio.charset.Charset.defaultCharset() 获得 ...

  5. Spring MVC和Struts2的比较(二)

    1.Spring MVC的controller+command object模式比Struts2的Action模式更安全一些.而在Struts2中,自动数据绑定发生在Action对象上.这样,在Act ...

  6. Linux_安装软件包

    一.软件包: 源码包 二进制包(rpm包,编译完成) 依赖性 包A-->包B-->包C 一.rpm 挂载镜像,从镜像文件中找到要安装的rpm包 [root@hadoop09-linux ~ ...

  7. odoo XMLRPC 新库 OdooRPC 尝鲜

    无意中发现了python居然有了OdoRPC的库,惊喜之下赶紧尝试一番,比XMLRPC简洁了不少,机制看样子是利用的JsonRPC. #原文出自KevinKong的博客http://www.cnblo ...

  8. 禁止浏览器直接访问php文件

    框架中很多php文件并不是用来如果熟悉框架的路径就能直接访问这个文件,虽然访问到了也不能看到什么(他看到的是编译过后的html文件),但还是觉的很不安全. 可以通过下面这种方法拒绝他人的从浏览器中的访 ...

  9. zk回车事件

    private Textbox testTextB; testTextB.addEventListener(Events.ON_OK, new EventListener<Event>() ...

  10. unity3d插件Daikon Forge GUI 中文教程2-基础控件Label的使用

    我们先来设置 UI Root 中的如下:屏幕大小为1024*768 2.1  新建一个Label 控件 先来看看Control Properties (基本上是所有控件都共用的)的以后不再介绍,参数: ...