树介绍:
1、根节点:第一个选择点,只有出,木有入
2、非叶子节点与分支:中间过程,有进有出
3、叶子节点:最终决策结果,只有入木有出
熵介绍
1、表示随机变量不确定性的度量==>混乱程度
2、不确定性越大,赏越大
3、信息增益:表示特征X使Y的不确定性减少的程度
原熵值为x,选择某一特征后熵值成为了y,信息增益为x-y
信息增益越大越好
决策树:
定义:从根节点开始一步步走到叶子节点
1、问题:
1、怎样进行划分:
连续值:排序后找分界点==>连续数据离散化
离散值:用众数
2、怎样选择节点的顺序:选择信息增益最大的值
2、计算
1、熵值计算:
2、实例:
四种分类:outlook,temperature,humidity,windy==>play
四种因素决定是否能够出去踢足球
1、初始:14天中由9天打球,5天不打球:
熵值:
2、outlook分类:
sunny:5天,2天打球,3天不打球:H=0.971
overcast:4天都打球:H=0
rainy:5天,3天打球,2天不打球:H=0.971
由outlook分类:
信息增益=0.247
计算其他分类的信息增益Gain
Gain(temperature)=0.029
Gain(humidity)=0.152
Gain(windy)=0.048
所有第一个分类使outlook
3、按同样方法计算下一级,找下一级的分类
3、决策树算法
ID3:信息增益
C4.5:信息增益率
CART:GNIN系数
4、剪枝策略
1、为什么剪枝:决策树过拟合风险过大
2、剪枝策略:
预剪枝:便建立决策树,边剪枝
1、限制深度
2、限制叶子节点个数
3、限制叶子节点样本数
4、限制信息增益
后剪枝:当建立完成后再剪枝
5、绘图
1、绘制决策树
1、导入数据:
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
iris=load_iris()
x=iris.data[:,2:]#Bunch petal length in cm
# - petal width in cm
y=iris.target
print(x[:2,:],y)
tree_clf=DecisionTreeClassifier(max_depth=2)#是监督学习
tree_clf.fit(x,y)
2、训练树模型
from sklearn.tree import export_graphviz
export_graphviz(
tree_clf,#树模型
out_file='iris_tree.dot',#输出的文件名和类型
feature_names=iris.feature_names[2:],
class_names=iris.target_names,
rounded=True,
filled=True
)
#可以将graphviz中的dot命令将.dot文件转换成各种各样的格式
#注意要找到指定文件再执行命令
# $ dot -Tpng iris_tree.dot -o iris_tree.png
3、图片呈现
from IPython.display import Image
#将图片显示在这里
Image(filename='iris_tree.png',width=400,height=400)
4、决策树预测:
1、预测概率:
tree_clf.predict_proba([[5,1.5]])#array([[0. , 0.90740741, 0.09259259]])
2、预测哪一类的
tree_clf.predict([[5,1.5]])#array([1])
2、决策边界绘制:
1、定义绘制决策边界的函数:
1、找到四周的数值,min(x)、min(y)、max(x)、max(y)
2、np.meshgrid生成网格举证
3、将向量拉直再组合起来
4、将所求转换成原网格的形状
from matplotlib.colors import ListedColormap
def plot_decision_boundary(clf,x,y,iris=True,
legend=False,plot_training=True):
x1=np.linspace(np.min(x),np.max(x),100)
x2=np.linspace(np.min(y),np.max(y),100)
x1,x2=np.meshgrid(x1,x2)
x_new = np.c_[x1.ravel(), x2.ravel()]
y_pred=clf.predict(x_new).reshape(x1.shape)
custom_cmap=ListedColormap(['#fafab0','#9898ff','#a0faa0'])
plt.contourf(x1,x2,y_pred,alpha=0.3,cmap=custom_cmap)
if not iris:
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="Iris-Setosa")
plt.plot(x[:, 0][y==1], x[:, 1][y==1], "bs", label="Iris-Versicolor")
plt.plot(x[:, 0][y==2], x[:, 1][y==2], "g^", label="Iris-Virginica")
plt.axis([np.min(x),np.max(x),np.min(y),np.max(y)])
if iris:
plt.xlabel("Petal length", fontsize=14)
plt.ylabel("Petal width", fontsize=14)
else:
plt.xlabel(r"$x_1$", fontsize=18)
plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
if legend:
plt.legend(loc="lower right", fontsize=14)
2、绘制
plt.figure(figsize=(8, 4))
plot_decision_boundary(tree_clf, x, y)
3、正则化
对比设置了了min_sample_leaf
from sklearn.datasets import make_moons
x,y = make_moons(n_samples=100,noise=0.25,random_state=53)
tree_clf1 = DecisionTreeClassifier(random_state=42)
tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4,random_state=42)
tree_clf1.fit(x,y)
tree_clf2.fit(x,y)
plt.figure(figsize=(12,4))
plt.subplot(121)
plot_decision_boundary(tree_clf1,x,y,iris=False)
plt.title('No restrictions')
plt.subplot(122)
plot_decision_boundary(tree_clf2,x,y,iris=False)
plt.title('min_samples_leaf=4')
很好的防止了过拟合
4、回归数据
回归:mse,squared_error
分类:Gini
回归数据木有决策边界,就是在预测值处画红线
1、导入数据:
np.random.seed(42)
m=200
x=np.random.rand(m,1)
y = 4*(x-0.5)**2
y = y + np.random.randn(m,1)/10#高斯抖动
2、训练模型:
from sklearn.tree import DecisionTreeRegressor#决策树回归
tree_reg = DecisionTreeRegressor(max_depth=2)
tree_reg.fit(x,y)
3、对比max_depth:
from sklearn.tree import DecisionTreeRegressor
tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
tree_reg1.fit(x, y)
tree_reg2.fit(x, y)
#回归问题木有决策边界
def plot_regression_predictions(tree_reg, x, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
y_pred = tree_reg.predict(x1)
plt.axis(axes)
plt.xlabel("$x_1$", fontsize=18)
if ylabel:
plt.ylabel(ylabel, fontsize=18, rotation=0)
plt.plot(x, y, "b.")
plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
plt.figure(figsize=(11, 4))
plt.subplot(121)
plot_regression_predictions(tree_reg1, x, y)
plt.legend(loc="upper center", fontsize=18)
plt.title("max_depth=2", fontsize=14)
plt.subplot(122)
plot_regression_predictions(tree_reg2, x, y, ylabel=None)
plt.text(0.3, 0.5, "Depth=2", fontsize=13)
plt.title("max_depth=3", fontsize=14)
plt.show()