python决策树
一、CART算法的实现
#encoding:utf-8 from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import load_digits #准备数据 digit = load_digits() data = digit.data target = digit.target #随机抽取33%的数据做测试集,其余为训练集 train_data,test_data,train_target,test_target = train_test_split(data,target,test_size=0.33,random_state=0) #创建CART分类树 clf = DecisionTreeClassifier(criterion=‘gini‘) #拟合构造CART分类树 clf = clf.fit(train_data,train_target) #用CART分类树做预测 test_predict = clf.predict(test_data) #将结果输出 print(‘实际结果为:‘,test_target,‘--预测结果为:‘,test_predict) #预测结果的准确率 score = accuracy_score(test_target,test_predict) print("CART分类树准确率%.4f" % score)