R_decision tree

R中决策树的代码实现:

#C5.0

M1<-C5.0(traindata$x,traindata$y)

Summary(M1)

predict(M1,test$data)

table(对比结果)

#Rpart

M1<-rpart(y~., data= ,method=”class” ) #.表示所有属性都包括,如果不是就写上用+相连,method是告诉我们希望结果是分类属性,而不像我之前做的结果是数值rprart.plot(M1,type=3,extra=101, fallen.leave=TRUE)

predict(M1,testdata,type=”class”)

#CART (regression trees)

Install.packages(“rpart.plot”)

m2<-rpart(target_feature~., data= ,method=”anova”) #用anova因为预测属性是数值的 

rpart.plot<-(m1, type=3,digits=3,fallen.leaves=TRUE)

p1<-predict(m1,testdata)#用mean检验数值结果模型的豪华

Mae<-function(actual,predicted){mean(abs(actual-preidcted))}Mae<-(df$数值属性,p1)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
data = pd.read_csv("data.csv") data.replace("M",1,inplace=True) data.replace("B",0,inplace=True) #获取特征x和特征y X = data.iloc[:, 3:5].values x = np.array(X) y = data.diagnosis y = np.array(y) #创建决策树算法对象 tree_clf = DecisionTreeClassifier(max_depth=2) #构建决策树 tree_clf.fit(x,y) #绘制决策树结构 tree.plot_tree(tree_clf) from matplotlib.colors import ListedColormap plt.rcParams["font.sans-serif"] = ["SimHei"] plt.rcParams["axes.unicode_minus"] = False #定义绘制决策树边界的函数 def plot_decision_boundary(clf, X, y, axes=[0, 10 , 0 , 5], data=True, legend=False, plot_training=True): x1s = np.linspace(axes[0], axes[1], 100) x2s = np.linspace(axes[2], axes[3], 100) x1, x2 = np.meshgrid(x1s, x2s) X_new = np.c_[x1.ravel(), x2.ravel()] y_pred = clf.predict(X_new).reshape(x1.shape) custom_cmap = ListedColormap(['#fafab0', '#0909ff', '#a0faa0']) plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) if not data: custom_cmap2 = ListedColormap(['#7d7d58', '#4c4c7f', '#507d50']) plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) if plot_training: plt.plot(X[:, 0][y == 0], X[:, 1][y == 0], "yo", label="0") plt.plot(X[:, 0][y == 1], X[:, 1][y == 1],"bs", label="1") plt.axis(axes) if data: plt.xlabel("属性",fontsize=14) plt.ylabel("特征",fontsize=14) else: plt.xlabel(r"$x_1$", fontsize=18) plt.xlabel(r"$x_2$", fontsize=18,rotation=0) if legend: plt.legend(loc="lower right", fontsize=14) tree_clf1 = DecisionTreeClassifier(random_state=42) tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4,random_state=43) tree_clf1.fit(x,y) tree_clf2.fit(x,y) plt.figure(figsize=(15,6)) plt.subplot(121) plot_decision_boundary(tree_clf1, x, y, axes=[0, 40, 50, 150], data=False) plt.title('圖一') plt.subplot(122) plot_decision_boundary(tree_clf2, x, y, axes=[0, 40, 50, 150], data=False) plt.title('圖二')
最新发布
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值