sklearn之决策树实战

来源:互联网 发布:js在线压缩混淆 编辑:程序博客网 时间:2024/06/06 18:57

介绍

决策树是用于分类和回归的非参数监督学习方法。 目标是创建一个模型,通过学习从数据特征推断的简单决策规则来预测目标变量的值。

分类

DecisionTreeClassifier是能够在数据集上执行多类分类的类。

DecisionTreeClassifier将输入两个数组:数组X,大小为[n_samples,n_features],以及整数值的数组Y,大小[n_samples](类标签)。

from sklearn import tree# 特征X = [[0,0],[1,1]]# 类标签Y = [0,1]# 决策树算法(分类)clf = tree.DecisionTreeClassifier()clf = clf.fit(X,Y)# 预测print(clf.predict([2,2]))

使用iris数据集进行分类:

from sklearn.datasets import load_irisfrom sklearn import treeiris = load_iris()clf = tree.DecisionTreeClassifier()clf = clf.fit(iris.data, iris.target)#print(clf.predict([2,2,2,2]))#预测新样本的类print(clf.predict(iris.data[:1, :]))#预测样本类的概率分布print(clf.predict_proba(iris.data[:1, :]))

回归

决策树也可以应用于回归问题,使用DecisionTreeRegressor类。

与分类设置一样,拟合方法将作为参数数组X和Y,只有在这种情况下,y预期具有浮点值而不是整数值:

from sklearn import tree# 特征X = [[0,0],[1,1]]# 类标签Y = [0,1]# 回归clf = tree.DecisionTreeRegressor();clf = clf.fit(X,Y)# 预测print(clf.predict([2,2]))

可视化:

import numpy as npfrom sklearn.tree import DecisionTreeRegressorimport matplotlib.pyplot as plt# Create a random datasetrng = np.random.RandomState(1)X = np.sort(5 * rng.rand(80, 1), axis=0)y = np.sin(X).ravel()y[::5] += 3 * (0.5 - rng.rand(16))# Fit regression model# regr_1模型最大深度为2,regr_2为5regr_1 = DecisionTreeRegressor(max_depth=2)regr_2 = DecisionTreeRegressor(max_depth=5)regr_1.fit(X, y)regr_2.fit(X, y)# PredictX_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]y_1 = regr_1.predict(X_test)y_2 = regr_2.predict(X_test)# Plot the resultsplt.figure()plt.scatter(X, y, c="k", label="data")plt.plot(X_test, y_1, c="g", label="max_depth=2", linewidth=2)plt.plot(X_test, y_2, c="r", label="max_depth=5", linewidth=2)plt.xlabel("data")plt.ylabel("target")plt.title("Decision Tree Regression")plt.legend()plt.show()

这里写图片描述

参考:
http://scikit-learn.org/stable/modules/tree.html