数据挖掘-基于机器学习的SNS隐私策略推荐向导分类器的C++及WEKA实现与评估

来源:互联网 发布:js创建图片对象 编辑:程序博客网 时间:2024/06/05 03:26

本文接基于机器学习的SNS隐私保护策略推荐向导的设计与实现》,详细解析基于机器学习的SNS隐私策略推荐向导分类器的C++及WEKA实现与评估结果,本文完整C++程序及Java工程下载链接见点击打开链接,对数据挖掘和SNS感兴趣的朋友可以下载跑一下,有任何问题欢迎交流:)

基于机器学习的SNS隐私策略推荐向导分类器的C++及WEKA实现与评估
1 SNS朋友数据预处理与统计
要实现对朋友访问权限的自动分类,首先需要对朋友的数据进行预处理。预处理主要包括向量化和格式化输出。格式化输出主要是针对使用的数据挖掘开源程序包,WWW10’原文中实验时采用的是RapidMiner,主要使用了其中的朴素贝叶斯、决策树及KNN算法的实现。本文中SNS隐私向导分类器的实现主要基于WEKA,同样是非常著名的数据挖掘开源程序包。WEKA支持命令行、GUI、程序API等多种调用方式。为了让WEKA成功读取样本数据,首先得知道WEKA对样本数据格式的规定,如图7-1所示,给出了本项目训练样本数据文件格式,以WEKA读取数据格式ARFF文件保存。

SNS朋友向量化的JAVA实现如下

[java] view plain copy
  1. package com.pku.yangliu;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.FileInputStream;  
  5. import java.io.File;  
  6. import java.io.FileWriter;  
  7. import java.io.IOException;  
  8. import java.io.InputStreamReader;  
  9. import java.io.UnsupportedEncodingException;  
  10. import java.util.ArrayList;  
  11. import java.util.Arrays;  
  12. import java.util.HashMap;  
  13. import java.util.HashSet;  
  14. import java.util.List;  
  15.   
  16. /**Compute the vector of friends in arff format 
  17.  * @author yangliu 
  18.  * @qq 772330184  
  19.  * @mail yang.liu@pku.edu.cn 
  20.  * @blog http://blog.csdn.net/yangliuy 
  21.  */  
  22. public class ComputeFriendsVector {  
  23.     public static String dataPath = "data/";  
  24.     public static String resPath = "friendvec/";  
  25.     public static String communityFile = "friendvec/community.out.txt";  
  26.     /** 
  27.      * @param args 
  28.      * @throws IOException  
  29.      */  
  30.     public static void main(String[] args) throws IOException {  
  31.         // TODO Auto-generated method stub  
  32.         File[] dataFiles = new File(dataPath).listFiles();  
  33.         String line;  
  34.         for(int i = 0; i < dataFiles.length; i++){  
  35.             BufferedReader dataFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(dataFiles[i]), "UTF-8"));  
  36.             BufferedReader communityFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(communityFile), "UTF-8"));  
  37.             String resFile = resPath +"vec_" +dataFiles[i].getName()+".arff";  
  38.             FileWriter resFileWriter = new FileWriter(resFile);  
  39.             resFileWriter.append("@relation " + dataFiles[i].getName() + "_friends" + "\n\n");  
  40.             //先写出arf文件头信息  
  41.             writeArffHeader(resFileWriter);  
  42.             int count = 0;  
  43.             HashMap<String,String> userProfile = new HashMap<String,String>();  
  44.             HashMap<String,String> friendProfile = new HashMap<String,String>();  
  45.             HashSet<String> birthdays = new HashSet<String>();  
  46.             String communityLine = communityFileReader.readLine();//第一行数据不要,是用户的圈子信息  
  47.             communityLine = communityFileReader.readLine();  
  48.             while((line = dataFileReader.readLine()) != null){  
  49.                 count++;  
  50.                 if(count == 1){  
  51.                     System.out.print(count + " ");  
  52.                     userProfile = transToMap(line);  
  53.                     continue;  
  54.                 }else{  
  55.                     friendProfile = transToMap(line);  
  56.                     //基于frindProfile统计出现过的所有出生年份,写入arff文件头部  
  57.                     birthdays = countBirthdays(birthdays, friendProfile);  
  58.                     line = generateVecLine(friendProfile, userProfile);  
  59.                     resFileWriter.append(line + communityLine + "," + friendProfile.get("permission")+"\n");  
  60.                     System.out.println(line +" haha " + communityLine + "," + friendProfile.get("permission"));  
  61.                     communityLine = communityFileReader.readLine();   
  62.                 }  
  63.                 System.out.print(count + " ");  
  64.             }  
  65.             resFileWriter.flush();  
  66.             resFileWriter.close();  
  67.             System.out.println(birthdays.size());  
  68.             for(String birth : birthdays){  
  69.                 System.out.print(birth + ",");  
  70.             }  
  71.             System.out.println();  
  72.         }  
  73.         System.out.println("done");  
  74.     }  
  75.       
  76.     /**Count all the types of birthday 
  77.      * @param friendProfile  
  78.      * @param resFileWriter 
  79.      * @return Vector<String>  
  80.      * @throws IOException  
  81.      */  
  82.     private static HashSet<String> countBirthdays(HashSet<String> birthdays, HashMap<String, String> friendProfile) {  
  83.         // TODO Auto-generated method stub  
  84.         if(friendProfile.containsKey("birthday")){  
  85.             String year[] = friendProfile.get("birthday").split("[^0-9]");  
  86.             birthdays.add(year[0]);  
  87.         }  
  88.         return birthdays;  
  89.     }  
  90.   
  91.     /**Write the header of arff file 
  92.      * @param resFileWriter 
  93.      * @throws IOException  
  94.      */  
  95.     private static void writeArffHeader(FileWriter resFileWriter) throws IOException {  
  96.         // TODO Auto-generated method stub  
  97.         resFileWriter.append("@attribute gender {0,1}\n");  
  98.         resFileWriter.append("@attribute birthday numeric\n");  
  99.         resFileWriter.append("@attribute hometown {0,1,2}\n");  
  100.         resFileWriter.append("@attribute college {0,1}\n");  
  101.         resFileWriter.append("@attribute highschool {0,1}\n");  
  102.         resFileWriter.append("@attribute middleschool {0,1}\n");  
  103.         resFileWriter.append("@attribute primaryschool {0,1}\n");  
  104.         resFileWriter.append("@attribute G1 {0,1}\n");  
  105.         resFileWriter.append("@attribute G2 {0,1}\n");  
  106.         resFileWriter.append("@attribute G3 {0,1}\n");  
  107.         resFileWriter.append("@attribute G4 {0,1}\n");  
  108.         resFileWriter.append("@attribute G5 {0,1}\n");  
  109.         resFileWriter.append("@attribute G6 {0,1}\n");  
  110.         resFileWriter.append("@attribute G7 {0,1}\n");  
  111.         resFileWriter.append("@attribute G8 {0,1}\n");  
  112.         resFileWriter.append("@attribute G9 {0,1}\n");  
  113.         resFileWriter.append("@attribute G10 {0,1}\n");  
  114.         resFileWriter.append("@attribute G11 {0,1}\n");  
  115.         resFileWriter.append("@attribute G12 {0,1}\n");  
  116.         resFileWriter.append("@attribute G13 {0,1}\n");  
  117.         resFileWriter.append("@attribute G14 {0,1}\n");  
  118.         resFileWriter.append("@attribute G15 {0,1}\n");  
  119.         resFileWriter.append("@attribute G16 {0,1}\n");  
  120.         resFileWriter.append("@attribute G17 {0,1}\n");  
  121.         resFileWriter.append("@attribute G18 {0,1}\n");  
  122.         resFileWriter.append("@attribute G19 {0,1}\n");  
  123.         resFileWriter.append("@attribute G20 {0,1}\n");  
  124.         resFileWriter.append("@attribute permission {0,1}\n\n");  
  125.         resFileWriter.append("@data\n");      
  126.     }  
  127.   
  128.     /**Generate the line for the vector of a friend 
  129.      * @param friendProfile 
  130.      * @param userProfile  
  131.      * @return String the line for the vector of a friend 
  132.      * @throws UnsupportedEncodingException  
  133.      */  
  134.     private static String generateVecLine(  
  135.             HashMap<String, String> friendProfile,  
  136.             HashMap<String, String> userProfile) throws UnsupportedEncodingException {  
  137.         // TODO Auto-generated method stub  
  138.         String vecLine = new String();  
  139.         String[] keys = {"id""name""gender""birthday""hometown""college""highschool""middleschool""primaryschool","permission"};  
  140.         for(String key : keys){  
  141.             String userVal = userProfile.get(key);  
  142.             String friendVal = friendProfile.get(key);  
  143.             if(friendVal == null){//朋友缺失该项信息,向量中使用"?"表示  
  144.                 vecLine += "?" + ",";//arff文件分隔符为逗号  
  145.                 continue;  
  146.             } else {  
  147.                 if(key.equals("id")){  
  148.                     continue;  
  149.                 } else if(key.equals("name")){  
  150.                     continue;  
  151.                 } else if(key.equals("gender")){  
  152.                     int flag = friendVal.trim().equals(userVal.trim()) ? 1 : 0;  
  153.                     vecLine += String.valueOf(flag) + ",";  
  154.                 } else if(key.equals("birthday")){  
  155.                     vecLine += birthdayToAge(friendVal.trim()) + ",";  
  156.                 } else if(key.equals("hometown")){  
  157.                     vecLine += hometownToVecVal(userVal.trim(), friendVal.trim()) + ",";  
  158.                 } else if(key.equals("college")  
  159.                         ||key.equals("highschool")  
  160.                         ||key.equals("middleschool")  
  161.                         ||key.equals("primaryschool")){  
  162.                     vecLine += schoolToVecVal(userVal.trim(), friendVal.trim()) + ",";  
  163.                 } else if(key.equals("permission")){  
  164.                     continue;  
  165.                 }  
  166.             }     
  167.         }  
  168.         return vecLine;  
  169.     }  
  170.   
  171.     /**Transfer school information to value in vector 
  172.      * @param userVal 
  173.      * @param friendVal  
  174.      * @return String value for school in vector  
  175.      */  
  176.     private static String schoolToVecVal(String userVal, String friendVal) {  
  177.         // TODO Auto-generated method stub  
  178.         String[] userSchools = userVal.split(" ");  
  179.         String[] friendSchools = friendVal.split(" ");  
  180.         List<String> userList = new ArrayList<String>(Arrays.asList(userSchools));    
  181.         userList.retainAll(Arrays.asList(friendSchools));  
  182.         if(userList.isEmpty()) return "0";//all schools has no interset  
  183.         else return "1";  
  184.     }  
  185.       
  186.     /**Transfer hometown information to value in vector 
  187.      * @param userVal 
  188.      * @param friendVal  
  189.      * @return String value for hometown in vector  
  190.      */  
  191.     private static String hometownToVecVal(String userVal, String friendVal) {  
  192.         // TODO Auto-generated method stub  
  193.         String[] userHometown = userVal.split("-");  
  194.         String[] friendHometown = friendVal.split("-");  
  195.         if(userHometown[0].trim().equals(friendHometown[0].trim())){  
  196.             if(friendHometown.length == 1return "1";  
  197.             if(userHometown[1].trim().equals(friendHometown[1].trim())){  
  198.                 return "2";  
  199.             }  
  200.             else return "1";  
  201.         }  
  202.         else return "0";  
  203.     }  
  204.       
  205.     /**Transfer birthday information to age 
  206.      * @param userVal 
  207.      * @param friendVal  
  208.      * @return String age of friend 
  209.      */  
  210.     private static String birthdayToAge(String friendVal) {  
  211.         // TODO Auto-generated method stub  
  212.         String[] birthdayInfo = friendVal.split("[^0-9]");  
  213.         if(birthdayInfo.length == 0return "?";  
  214.         //Calendar cal = Calendar.getInstance();  
  215.         //int curYear = cal.get(Calendar.YEAR);  
  216.         //int birthYear = Integer.parseInt(birthdayInfo[0]);  
  217.         //改变一下生日的离散化算法,直接用生日年份来作为birthday  
  218.         //return String.valueOf(curYear - birthYear);  
  219.         return birthdayInfo[0].trim();  
  220.     }  
  221.   
  222.     /**Transfer the attribute of one friend to Map 
  223.      * @param line original attribute 
  224.      * @return HashMap<String,String> a Map to store the attribute information  
  225.      */  
  226.     private static HashMap<String,String> transToMap(String line) {  
  227.         // TODO Auto-generated method stub  
  228.         //System.out.println(line);  
  229.         String attri[] = line.split(";");  
  230.         HashMap<String,String> profileMap = new HashMap<String,String>();  
  231.         for(int i = 0; i < attri.length - 1; i++){  
  232.             String keyVal[] = attri[i].split(":");  
  233.             profileMap.put(keyVal[0].trim(), keyVal[1].trim());  
  234.         }  
  235.         //最后一项是分类标签permission 0-deny 1-allow  
  236.         profileMap.put("permission", attri[attri.length - 1].trim());  
  237.         return profileMap;  
  238.     }  
  239. }  

识别ARFF文件的重要依据是分行,因此不能在这种文件里随意的断行。整个ARFF文件可以分为两个部分。第一部分给出了头信息(Head information),包括了对关系的声明和对属性的声明。第二部分给出了数据信息(Data information),即数据集中给出的数据。从“@data”标记开始,后面的就是数据信息。 从图中的属性描述信息可知,朋友向量主要包括性别、生日、家乡、大学、高中、初中、小学以及抽取出的20个圈子属性。对该用户全部449个好友情况统计见表7-1。注意有部分朋友某些属性值无法获取,用“?”表示,表中没有统计入内。

    表中最后一列用户隐私偏好(allow/deny)是用户根据自己的隐私偏好手动打算的标签,以备分类实验使用,选取的资料是用户“生日”,从表中可知,该用户只希望79位朋友看到他的生日信息。

2 SNS隐私向导分类器的实现

本项目隐私向导分类器的实现基于ID3和C4.5两种算法,ID3是自己用C++实现的,C4.5及决策树可视化主要基于数据挖掘开源程序包WEKA,主要是在训练样本的不定抽样阶段使用朴素贝叶斯算法进行每轮迭代分类计算熵值;在分类阶段使用决策树算法。本项目分类器的实现采取了基于WEKA实现和全部自己开发两种途径,下面重点介绍分类器中使用的决策树算法。
决策树算法是非常常用的分类算法,是逼近离散目标函数的方法,学习得到的函数以决策树的形式表示。其基本思路是不断选取产生信息增益最大的属性来划分样例集和,构造决策树。决策树的构造过程不依赖领域知识,它使用属性选择度量来选择将元组最好地划分成不同的类的属性。所谓决策树的构造就是进行属性选择度量确定各个特征属性之间的拓扑结构。构造决策树的关键步骤是分裂属性。所谓分裂属性就是在某个节点处按照某一特征属性的不同划分构造不同的分支,其目标是让各个分裂子集尽可能地“纯”。尽可能“纯”就是尽量让一个分裂子集中待分类项属于同一类别。
属性选择度量算法有很多,一般使用自顶向下递归分治法,并采用不回溯的贪心策略。基于WEKA的分类器主要使用C4.5算法,而自己开发的决策树分类器基于ID3算法。下面简要说明这两种算法的原理。
2.1 基于决策树ID3算法的分类器
从信息论知识中我们知道,期望信息越小,信息增益越大,从而纯度越高。所以ID3算法的核心思想就是以信息增益度量属性选择,选择分裂后信息增益最大的属性进行分裂。而信息纯度可以用熵来度量。信息熵是香农提出的,用于描述信息不纯度(不稳定性)。 设D为用类别对训练元组进行的划分,则D的熵(entropy)表示为:


 
其中pi表示第i个类别在整个训练元组中出现的概率,可以用属于此类别元素的数量除以训练元组元素总数量作为估计。熵的实际意义表示是D中元组的类标号所需要的平均信息量。现在我们假设将训练元组D按属性A进行划分,则A对D划分的期望信息为:


 
而信息增益即为两者的差值:
 
ID3算法就是在每次需要分裂时,计算每个属性的增益率,然后选择增益率最大的属性进行分裂。
自己开发的基于ID3算法的SNS隐私向导的C++实现如下:

[cpp] view plain copy
  1. #include <iostream>  
  2. #include <string>  
  3. #include <vector>  
  4. #include <map>  
  5. #include <algorithm>  
  6. #include <cmath>  
  7. using namespace std;  
  8. #define MAXLEN 9//输入每行的数据个数  
  9.   
  10. /**基于决策树ID3的隐私向导分类器的C++实现 
  11.  * @author yangliu 
  12.  * @qq 772330184  
  13.  * @mail yang.liu@pku.edu.cn 
  14.  * @blog http://blog.csdn.net/yangliuy 
  15.  */  
  16.   
  17. vector <vector <string> > state;//实例集  
  18. vector <string> item(MAXLEN);//对应一行实例集  
  19. vector <string> attribute_row;//保存首行即属性行数据  
  20. string end("end");//输入结束  
  21. string yes("1");  
  22. string no("0");  
  23. string blank("");  
  24. map<string,vector < string > > map_attribute_values;//存储属性对应的所有的值  
  25. int tree_size = 0;  
  26. struct Node{//决策树节点  
  27.     string attribute;//属性值  
  28.     string arrived_value;//到达的属性值  
  29.     vector<Node *> childs;//所有的孩子  
  30.     Node(){  
  31.         attribute = blank;  
  32.         arrived_value = blank;  
  33.     }  
  34. };  
  35. Node * root;  
  36.   
  37. //根据数据实例计算属性与值组成的map  
  38. void ComputeMapFrom2DVector(){  
  39.     unsigned int i,j,k;  
  40.     bool exited = false;  
  41.     vector<string> values;  
  42.     for(i = 1; i < MAXLEN-1; i++){//按照列遍历  
  43.         for (j = 1; j < state.size(); j++){  
  44.             for (k = 0; k < values.size(); k++){  
  45.                 if(!values[k].compare(state[j][i])) exited = true;  
  46.             }  
  47.             if(!exited){  
  48.                 values.push_back(state[j][i]);//注意Vector的插入都是从前面插入的,注意更新it,始终指向vector头  
  49.             }  
  50.             exited = false;  
  51.         }  
  52.         map_attribute_values[state[0][i]] = values;  
  53.         values.erase(values.begin(), values.end());  
  54.     }     
  55. }  
  56.   
  57. //根据具体属性和值来计算熵  
  58. double ComputeEntropy(vector <vector <string> > remain_state, string attribute, string value,bool ifparent){  
  59.     vector<int> count (2,0);  
  60.     unsigned int i,j;  
  61.     bool done_flag = false;//哨兵值  
  62.     for(j = 1; j < MAXLEN; j++){  
  63.         if(done_flag) break;  
  64.         if(!attribute_row[j].compare(attribute)){  
  65.             for(i = 1; i < remain_state.size(); i++){  
  66.                 if((!ifparent&&!remain_state[i][j].compare(value)) || ifparent){//ifparent记录是否算父节点  
  67.                     if(!remain_state[i][MAXLEN - 1].compare(yes)){  
  68.                         count[0]++;  
  69.                     }  
  70.                     else count[1]++;  
  71.                 }  
  72.             }  
  73.             done_flag = true;  
  74.         }  
  75.     }  
  76.     if(count[0] == 0 || count[1] == 0 ) return 0;//全部是正实例或者负实例  
  77.     //具体计算熵 根据[+count[0],-count[1]],log2为底通过换底公式换成自然数底数  
  78.     double sum = count[0] + count[1];  
  79.     double entropy = -count[0]/sum*log(count[0]/sum)/log(2.0) - count[1]/sum*log(count[1]/sum)/log(2.0);  
  80.     return entropy;  
  81. }  
  82.       
  83. //计算按照属性attribute划分当前剩余实例的信息增益  
  84. double ComputeGain(vector <vector <string> > remain_state, string attribute){  
  85.     unsigned int j,k,m;  
  86.     //首先求不做划分时的熵  
  87.     double parent_entropy = ComputeEntropy(remain_state, attribute, blank, true);  
  88.     double children_entropy = 0;  
  89.     //然后求做划分后各个值的熵  
  90.     vector<string> values = map_attribute_values[attribute];  
  91.     vector<double> ratio;  
  92.     vector<int> count_values;  
  93.     int tempint;  
  94.     for(m = 0; m < values.size(); m++){  
  95.         tempint = 0;  
  96.         for(k = 1; k < MAXLEN - 1; k++){  
  97.             if(!attribute_row[k].compare(attribute)){  
  98.                 for(j = 1; j < remain_state.size(); j++){  
  99.                     if(!remain_state[j][k].compare(values[m])){  
  100.                         tempint++;  
  101.                     }  
  102.                 }  
  103.             }  
  104.         }  
  105.         count_values.push_back(tempint);  
  106.     }  
  107.       
  108.     for(j = 0; j < values.size(); j++){  
  109.         ratio.push_back((double)count_values[j] / (double)(remain_state.size()-1));  
  110.     }  
  111.     double temp_entropy;  
  112.     for(j = 0; j < values.size(); j++){  
  113.         temp_entropy = ComputeEntropy(remain_state, attribute, values[j], false);  
  114.         children_entropy += ratio[j] * temp_entropy;  
  115.     }  
  116.     return (parent_entropy - children_entropy);   
  117. }  
  118.   
  119. int FindAttriNumByName(string attri){  
  120.     for(int i = 0; i < MAXLEN; i++){  
  121.         if(!state[0][i].compare(attri)) return i;  
  122.     }  
  123.     cerr<<"can't find the numth of attribute"<<endl;   
  124.     return 0;  
  125. }  
  126.   
  127. //找出样例中占多数的正/负性  
  128. string MostCommonLabel(vector <vector <string> > remain_state){  
  129.     int p = 0, n = 0;  
  130.     for(unsigned i = 0; i < remain_state.size(); i++){  
  131.         if(!remain_state[i][MAXLEN-1].compare(yes)) p++;  
  132.         else n++;  
  133.     }  
  134.     if(p >= n) return yes;  
  135.     else return no;  
  136. }  
  137.   
  138. //判断样例是否正负性都为label  
  139. bool AllTheSameLabel(vector <vector <string> > remain_state, string label){  
  140.     int count = 0;  
  141.     for(unsigned int i = 0; i < remain_state.size(); i++){  
  142.         if(!remain_state[i][MAXLEN-1].compare(label)) count++;  
  143.     }  
  144.     if(count == remain_state.size()-1) return true;  
  145.     else return false;  
  146. }  
  147.   
  148. //计算信息增益,DFS构建决策树  
  149. //current_node为当前的节点  
  150. //remain_state为剩余待分类的样例  
  151. //remian_attribute为剩余还没有考虑的属性  
  152. //返回根结点指针  
  153. Node * BulidDecisionTreeDFS(Node * p, vector <vector <string> > remain_state, vector <string> remain_attribute){  
  154.     if (p == NULL)  
  155.         p = new Node();  
  156.     //先看搜索到树叶的情况  
  157.     if (AllTheSameLabel(remain_state, yes)){  
  158.         p->attribute = yes;  
  159.         return p;  
  160.     }  
  161.     if (AllTheSameLabel(remain_state, no)){  
  162.         p->attribute = no;  
  163.         return p;  
  164.     }  
  165.     if(remain_attribute.size() == 0){//所有的属性均已经考虑完了,还没有分尽  
  166.         string label = MostCommonLabel(remain_state);  
  167.         p->attribute = label;  
  168.         return p;  
  169.     }  
  170.   
  171.     double max_gain = 0, temp_gain;  
  172.     vector <string>::iterator max_it = remain_attribute.begin();  
  173.     vector <string>::iterator it1;  
  174.     for(it1 = remain_attribute.begin(); it1 < remain_attribute.end(); it1++){  
  175.         temp_gain = ComputeGain(remain_state, (*it1));  
  176.         if(temp_gain > max_gain) {  
  177.             max_gain = temp_gain;  
  178.             max_it = it1;  
  179.         }  
  180.     }  
  181.     //下面根据max_it指向的属性来划分当前样例,更新样例集和属性集  
  182.     vector <string> new_attribute;  
  183.     vector <vector <string> > new_state;  
  184.     for(vector <string>::iterator it2 = remain_attribute.begin(); it2 < remain_attribute.end(); it2++){  
  185.         if((*it2).compare(*max_it)) new_attribute.push_back(*it2);  
  186.     }  
  187.     //确定了最佳划分属性,注意保存  
  188.     p->attribute = *max_it;  
  189.     vector <string> values = map_attribute_values[*max_it];  
  190.     int attribue_num = FindAttriNumByName(*max_it);  
  191.     new_state.push_back(attribute_row);  
  192.     for(vector <string>::iterator it3 = values.begin(); it3 < values.end(); it3++){  
  193.         for(unsigned int i = 1; i < remain_state.size(); i++){  
  194.             if(!remain_state[i][attribue_num].compare(*it3)){  
  195.                 new_state.push_back(remain_state[i]);  
  196.             }  
  197.         }  
  198.         Node * new_node = new Node();  
  199.         new_node->arrived_value = *it3;  
  200.         if(new_state.size() == 0){//表示当前没有这个分支的样例,当前的new_node为叶子节点  
  201.             new_node->attribute = MostCommonLabel(remain_state);  
  202.         }  
  203.         else   
  204.             BulidDecisionTreeDFS(new_node, new_state, new_attribute);  
  205.         //递归函数返回时即回溯时需要1 将新结点加入父节点孩子容器 2清除new_state容器  
  206.         p->childs.push_back(new_node);  
  207.         new_state.erase(new_state.begin()+1,new_state.end());//注意先清空new_state中的前一个取值的样例,准备遍历下一个取值样例  
  208.     }  
  209.     return p;  
  210. }  
  211.   
  212. void Input(){  
  213.     string s;  
  214.     while(cin>>s,s.compare(end) != 0){//-1为输入结束  
  215.         item[0] = s;  
  216.         for(int i = 1;i < MAXLEN; i++){  
  217.             cin>>item[i];  
  218.         }  
  219.         state.push_back(item);//注意首行信息也输入进去,即属性  
  220.     }  
  221.     for(int j = 0; j < MAXLEN; j++){  
  222.         attribute_row.push_back(state[0][j]);  
  223.     }  
  224. }  
  225.   
  226. void PrintTree(Node *p, int depth){  
  227.     for (int i = 0; i < depth; i++) cout << '\t';//按照树的深度先输出tab  
  228.     if(!p->arrived_value.empty()){  
  229.         cout<<p->arrived_value<<endl;  
  230.         for (int i = 0; i < depth+1; i++) cout << '\t';//按照树的深度先输出tab  
  231.     }  
  232.     cout<<p->attribute<<endl;  
  233.     for (vector<Node*>::iterator it = p->childs.begin(); it != p->childs.end(); it++){  
  234.         PrintTree(*it, depth + 1);  
  235.     }  
  236. }  
  237.   
  238. void FreeTree(Node *p){  
  239.     if (p == NULL)  
  240.         return;  
  241.     for (vector<Node*>::iterator it = p->childs.begin(); it != p->childs.end(); it++){  
  242.         FreeTree(*it);  
  243.     }  
  244.     delete p;  
  245.     tree_size++;  
  246. }  
  247.   
  248. int main(){  
  249.     Input();  
  250.     vector <string> remain_attribute;  
  251.     string gender("gender");  
  252.     string birthday("birthday");  
  253.     string hometown("hometown");  
  254.     string college("college");  
  255.     string highschool("highschool");  
  256.     string middleschool("middleschool");  
  257.     string primaryschool("primaryschool");  
  258.   
  259.     remain_attribute.push_back(gender);  
  260.     remain_attribute.push_back(birthday);  
  261.     remain_attribute.push_back(hometown);  
  262.     remain_attribute.push_back(college);  
  263.     remain_attribute.push_back(highschool);  
  264.     remain_attribute.push_back(middleschool);  
  265.     remain_attribute.push_back(primaryschool);  
  266.   
  267.     vector <vector <string> > remain_state;  
  268.     for(unsigned int i = 0; i < state.size(); i++){  
  269.         remain_state.push_back(state[i]);   
  270.     }  
  271.     ComputeMapFrom2DVector();  
  272.     root = BulidDecisionTreeDFS(root,remain_state,remain_attribute);  
  273.     cout<<"the decision tree is :"<<endl;  
  274.     PrintTree(root,0);  
  275.     FreeTree(root);  
  276.     cout<<endl;  
  277.     cout<<"tree_size:"<<tree_size<<endl;  
  278.     return 0;  
  279. }  
训练数据如下

[plain] view plain copy
  1. id gender birthday hometown college highschool middleschool primaryschool permission  
  2. 18 1 1987 1 0 0 0 0 0  
  3. 19 1 1989 0 1 0 0 0 0  
  4. 20 1 1984 0 0 0 0 0 0  
  5. 21 1 1984 0 0 0 0 0 0  
  6. 22 1 1984 0 1 0 0 0 0  
  7. 23 1 1991 0 0 0 0 0 0  
  8. 24 1 1988 1 1 0 0 0 1  
  9. 25 1 1985 0 0 0 0 0 0  
  10. 26 1 1987 0 0 0 0 0 0  
  11. 27 1 1988 0 0 0 0 0 0  
  12. 28 0 1988 1 0 0 0 0 0  
  13. 29 1 1988 1 0 0 0 0 0  
  14. 30 0 1984 0 0 0 0 0 0  
  15. 31 0 1988 0 0 0 0 0 1  
  16. 32 0 1989 0 1 0 0 0 1  
  17. end  

程序根据朋友向量信息及用户标签训练数据输出的隐私向导决策树如下,当然如果训练数据越多,决策树中的结点就会越多,所得到的分类结果也就越精确。


2.2 基于决策树C4.5算法的分类器
  ID3算法存在一个问题,就是偏向于多值属性,例如,如果存在唯一标识属性ID,则ID3会选择它作为分裂属性,这样虽然使得划分充分纯净,但这种划分对分类几乎毫无用处。ID3的后继算法C4.5使用增益率(gain ratio)的信息增益扩充,试图克服这个偏倚。
C4.5算法首先定义了“分裂信息”,其定义可以表示成:
 
    其中各符号意义与ID3算法相同,然后,增益率被定义为:
 
C4.5选择具有最大增益率的属性作为分裂属性,其余建树及分类的过程和ID3类似。

3 分类器决策树可视化
本项目基于C4.5算法的决策树分类器实现主要基于WEKA,主要JAVA程序如下:

[java] view plain copy
  1. package com.pku.yangliu;  
  2.   
  3. import java.io.File;  
  4. import java.util.Random;  
  5.   
  6. import weka.classifiers.Classifier;  
  7. import weka.classifiers.Evaluation;  
  8. import weka.classifiers.trees.J48;  
  9. import weka.core.Instances;  
  10. import weka.core.converters.ArffLoader;  
  11.   
  12. /**A Classifer for access control privilege of SNS friends  
  13.  * @author yangliu 
  14.  * @qq 772330184  
  15.  * @mail yang.liu@pku.edu.cn 
  16.  * @blog http://blog.csdn.net/yangliuy 
  17.  */  
  18. public class DecisionTreeClassifer {  
  19.   
  20.     /** 
  21.      * @param args 
  22.      * @throws Exception  
  23.      */  
  24.     public static void main(String[] args) throws Exception {  
  25.         // TODO Auto-generated method stub  
  26.         Classifier m_classifier = new J48();//基于C4.5决策树的实现  
  27.         //随机抽样实验  
  28.         File inputFile = new File("friendvec/vec_profile.txt2.txt-train.arff");//训练样例  
  29.         ArffLoader atf = new ArffLoader();  
  30.         atf.setFile(inputFile);   
  31.         Instances instancesTrain = atf.getDataSet();  
  32.           
  33.         inputFile = new File("friendvec/vec_profile.txt2.txt-test.arff");//测试样例  
  34.         atf.setFile(inputFile);  
  35.         Instances instancesTest = atf.getDataSet();  
  36.         instancesTest.setClassIndex(instancesTrain.numAttributes() - 1);  
  37.           
  38.         double testAmount = instancesTest.numInstances();//测试样本总数  
  39.         double rightAmount = 0.0f;//分类正确的样本总数  
  40.           
  41.         instancesTrain.setClassIndex(instancesTrain.numAttributes() - 1);  
  42.         m_classifier.buildClassifier(instancesTrain);//基于决策树C4.5算法训练  
  43.           
  44.         //统计正确分类的结果  
  45.         for(int i = 0; i < testAmount; i++){  
  46.             if(m_classifier.classifyInstance(instancesTest.instance(i))  
  47.                 == instancesTest.instance(i).classValue()) {  
  48.                 rightAmount++;  
  49.             }  
  50.         }  
  51.           
  52.         System.out.println("Trian and test evaluateModel Results\nSNS Wizard random samples classification accuaracy:" + (rightAmount / testAmount * 100) + "00%");  
  53.           
  54.         //交叉验证法实验  
  55.         inputFile = new File("friendvec/vec_profile.txt2.txt-whole.arff");//训练样例  
  56.         atf.setFile(inputFile);   
  57.         instancesTrain = atf.getDataSet();  
  58.         instancesTrain.setClassIndex(instancesTrain.numAttributes() - 1);  
  59.           
  60.         //10组交叉验证评估分类器性能  
  61.         Evaluation eval = new Evaluation(instancesTrain);  
  62.         J48 tree = new J48();  
  63.         eval.crossValidateModel(tree, instancesTrain, 10new Random(1));  
  64.         System.out.println(eval.toSummaryString("\n\nSNS Wizard crossValidateModel classification accuaracy:"false));  
  65.   
  66.         // train classifier  
  67.         //J48 cls = new J48();  
  68.         //cls.buildClassifier(instancesTrain);  
  69.         //evaluate classifier and print some statistics  
  70.         //Evaluation eval2 = new Evaluation(instancesTrain);  
  71.         //eval2.evaluateModel(cls, instancesTest);  
  72.         //System.out.println(eval.toSummaryString("\n trian and test evaluateModel Results\n\n", false));  
  73.   
  74.     }  
  75.       
  76.   
  77. }  

同时WEKA还良好支持了数据可视化,可以将训出的决策树可视化给SNS用户,其可视化的决策树见图7-2所示。

 
图7-2 C4.5算法决策树

4 实验设计

SNS关系隐私向导分类实验结果的主要评价标准是分类的准确率,即隐私向导推荐设置准确率,主要描述了分类器计算出的隐私设置结果与用户实际隐私偏好的符合程度。其计算公式如下
 
影响隐私向导推荐设置准确率的主要因素及主要实验设计思路如下: 
1) 朋友向量的组成。是否加入了抽取的圈子信息属性,一般而言,准确抽取的圈子信息会有助于提高分类准确率;但是如果圈子信息提取误差很大,则可能起相反的作用。本项目设计实验对比了加入抽取圈子信息前后隐私设置准确率的变化情况。
2) 训练样本抽样方法。主要有随机抽样、交叉验证、基于圈子信息的抽样和不定抽样等方法,WWW10’论文里面使用的是不定抽样法,在本文的第5部分有介绍。本项目中主要采用了随机抽样和交叉验证法。
3) 分类算法。主要的分类算法有决策树、朴素贝叶斯、KNN等,不同分类算法的分类准确率和速度也会有差异,本项目实现主要对比了决策树和朴素贝叶斯算法的分类准确率。

5 实验结果及分类器评价
基于对圈子信息、抽样方法、分类算法对隐私向导推荐设置准确率的影响的分析,设计对比实验得出的隐私设置准确率见表7-2所示。

基于对实验结果的观察可以得出如下结论:
1) 朋友向量组成方面,一般而言,准确抽取的圈子信息会有助于提高分类准确率;但是在本项目实验中圈子信息提取误差很大,使得加入圈子信息后分类器的准确率下降。
2) 训练样本抽样方法方面,交叉验证法优于随机抽样法。
3) 分类算法方面,在SNS隐私策略向导分类应用上朴素贝叶斯算法和决策树算法没有显著分类准确率差异,由于数据量比较小,分类时间都很短。可以看出分类算法的选择对于隐私向导设置准确率没有显著影响。

本文完整C++程序及JAVA工程下载链接见点击打开链接,对数据挖掘和SNS感兴趣的朋友可以下载跑一下,有任何问题欢迎交流:)

0 0