標籤:
剛才寫了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 args43 * @throws DocumentException 44 * @throws IOException 45 */46 public static void main(String[] args) throws DocumentException, IOException {47 // TODO Auto-generated method stub48 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 }
ID3決策樹預測的java實現