刚才写了ID3决策树的建立,这个是通过决策树来进行预测。这里主要用到的就是XML的遍历解析,比较简单。

关于xml的解析,参考了:

http://blog.csdn.net/soszou/article/details/8049220

http://lavasoft.blog.51cto.com/62575/71669/

思路:

先将要预测的数据,例如"sunny mild normal TRUE"根据特征表变成一个map,方便后续查找,结果为

outlook sunny

temperature windy

humidity normal 

windy TRUE这样的map

接着就变量xml文件,从root的子节点开始,如果该节点不存在子节点,就说明是叶节点了,那么就直接输出text,就是其分类的类别。如果有子节点,就根据map中的value去找对应的节点,并将该节点作为下一次迭代的节点参数。

 1 import java.io.File;
 2 import java.io.IOException;
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 import org.dom4j.Document;
 9 import org.dom4j.DocumentException;
10 import org.dom4j.Element;
11 import org.dom4j.io.SAXReader;
12 
13 public class Predict {
14 
15     public static Map<String,String> getMap(String data,ArrayList<String> featureList){
16         Map<String,String> map=new HashMap();
17         String[] s=data.split(" ");
18         for(int i=0;i<s.length;i++){
19             map.put(featureList.get(i),s[i]);
20         }
21         return map;
22     }
23     
24     public static int predict(Map<String,String> map,Element e){
25         List<Element> childList=e.elements();
26         if(childList.size()==0){
27             System.out.println( e.getText());
28             return 1;
29         }
30         String value=map.get(childList.get(0).getName());
31         for(Element next:childList){
32             String t=next.attributeValue("value");//这里的属性名都为value,所以这样就能获得该属性的值
33             if(t.compareTo(value)==0){
34                 predict(map,next);
35             }
36         }
37         return 1;
38     }
39     
40     
41     /**
42      * @param args
43      * @throws DocumentException 
44      * @throws IOException 
45      */
46     public static void main(String[] args) throws DocumentException, IOException {
47         // TODO Auto-generated method stub
48         String xml="C:/Users/Administrator/Desktop/upload/DT1.xml";
49         String file="C:/Users/Administrator/Desktop/upload/DT.txt";
50         String data="sunny mild normal TRUE";
51         ArrayList<String> featureList=Utils.loadFeature(file);    
52         Map<String,String> map=getMap(data,featureList);
53 
54         SAXReader saxReader=new SAXReader();
55         Document document =saxReader.read(new File(xml));
56         Element root=document.getRootElement();
57 
58         predict(map,root);
59         System.out.println("finished");
60     }
61 
62 }

 

posted on 2015-06-09 10:30  sunrye  阅读(646)  评论(0编辑  收藏  举报