实验二报告一决策树实验
决策树实验
一、实验原理
决策树是一个类似于流程图的树结构,其中每个内部结点表示在一个属性上的测试,每个分支代表一个测试输入,而每个树叶结点代表类或类分布。数的最顶层结点是根结点。一棵典型的决策树如图1所示。它表示概念buys_computer,它预测顾客是否可能购买计算机。内部结点用矩形表示,而树叶结点用椭圆表示。为了对未知的样本分类,样本的属性值在决策树上测试。决策树从根到叶结点的一条路径就对应着一条合取规则,因此决策树容易转化成分类规则。
图1
ID3算法:
■???? 决策树中每一个非叶结点对应着一个非类别属性,树枝代表这个属性的值。一个叶结点代表从树根到叶结点之间的路径对应的记录所属的类别属性值。
■???? 每一个非叶结点都将与属性中具有最大信息量的非类别属性相关联。
■???? 采用信息增益来选择能够最好地将样本分类的属性。
信息增益基于信息论中熵的概念。ID3总是选择具有最高信息增益(或最大熵压缩)的属性作为当前结点的测试属性。该属性使得对结果划分中的样本分类所需的信息量最小,并反映划分的最小随机性或“不纯性”。
二、算法伪代码
算法Decision_Tree(data,AttributeName)
输入由离散值属性描述的训练样本集data;
候选属性集合AttributeName。
输出一棵决策树。
(1) 创建节点N;
(2) If samples 都在同一类C中then
(3) 返回N作为叶节点,以类C标记;
(4) If attribute_list为空then
(5) 返回N作为叶节点,以samples 中最普遍的类标记;//多数表决
(6) 选择attribute_list 中具有最高信息增益的属性test_attribute;
(7) 以test_attribute 标记节点N;
(8) For each test_attribute 的已知值v //划分 samples
(9) 由节点N分出一个对应test_attribute=v的分支;
(10令Sv为 samples中 test_attribute=v 的样本集合;//一个划分块
(11)If Sv为空 then
(12)加上一个叶节点,以samples中最普遍的类标记;
(13)Else 加入一个由Decision_Tree(Sv,attribute_list-test_attribute)返回节点值。
实验主函数
#include iostream
#include string
#include vector
#include map
#include algorithm
#include cmath
using namespace std;
#define MAXLEN 5//输入每行的数据个数
vector vector string state;//实例集
vector string item(MAXLEN);//对应一行实例集
vector string attribute_row;//保存首行即属性行数据
string end(end);//输入结束
string yes(危险);
string no(不危险);
string blank();
mapstring,vector string map_attribute_values;//存储属性对应的所有的值
int tree_size = 0;
struct Node{//决策树节点
string attribute;//属性值
string arrived_value;//到达的属性值
vectorNode * childs;//所有的孩子
Node(){
attribute = blank;
arrived_value = blank;
}
};
Node * root;
//根据数据实例计算属性与值组成的map
void ComputeMapFrom2DVector(){
unsigned int i,j,k;
bool exited = false;
v
原创力文档

文档评论(0)