CART(classification and regression tree)

基尼指数

在分类问题中,假设有K个类,样本点属于第k类的概率为pk,则概率分布的基尼指数定义为CART(classification and regression tree)_第1张图片
Gini指数越小表示集合的纯度越高,反之,集合越不纯

CART

CART分类树默认使用基尼指数选择最优特征
常见数构建算法:
CART(classification and regression tree)_第2张图片
ID3:信息增益标示按某种特性分类后,剩余特性的信息熵的大小的衰减程度,信息熵越小,证明已经分好的类别就更加的纯粹单一

C4.5:选择了信息增益比替代信息增益;由于ID3算法会倾向于选取特征值较多的特征进行分类(因为这样会让信息增益很大)

基尼系数:代表了模型的不纯度,基尼系数越小,则不纯度越低,特征越好
sklearn中使用sklearn.tree.DecisionTreeClassifier可以实现CART分类树,默认使用gini指数选择特征。

在使用DecisionTreeClassifier对训练数据集进行拟合后,可使用下面封装的绘图函数进行观察

def plot_decision_boundary(model, axis):
  
  x0, x1 = np.meshgrid(
    np.linspace(axis[0], axis[1], int((axis[1]-axis[0])*100)).reshape(-1, 1),
      # axis=1表示横轴
      # reshape(-1,1)会根据col=1自动计算row值
    np.linspace(axis[2], axis[3], int((axis[3]-axis[2])*100)).reshape(-1, 1),
   )
  X_new = np.c_[x0.ravel(), x1.ravel()]
  y_predict = model.predict(X_new)
  zz = y_predict.reshape(x0.shape)
  from matplotlib.colors import ListedColormap
  custom_cmap = ListedColormap(['#EF9A9A','#FFF59D','#90CAF9'])
  plt.contourf(x0, x1, zz, linewidth=5, cmap=custom_cmap)

简单例子

from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 加载示例数据集(鸢尾花数据集)
data = load_iris()
X = data.data  # 特征
y = data.target  # 目标

# 只选择两个类别进行二元分类
X = X[y != 0]
y = y[y != 0]

# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建分类树(CART)
clf = DecisionTreeClassifier()

# 训练分类树
clf.fit(X_train, y_train)

# 使用分类树进行预测
y_pred = clf.predict(X_test)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)

你可能感兴趣的:(ML——algorithm,人工智能,机器学习,python)