数据科学:AdaBoost分类器

大数据
在本文中,我们讨论了理解AdaBoost算法的各种方法.AdaBoost就像是一个恩赐,如果正确使用它可以提高分类算法的准确性。

[[328383]]

介绍:

  • Boosting是一种集成技术,用于从多个弱分类器创建强分类器。 集成技术的一个众所周知的例子是随机森林(Random Forest),它使用多个决策树来创建一个随机森林。

直觉:

  • AdaBoost,Adaptive Boosting的缩写,是第一个成功的针对二进制分类开发的Boosting算法。它是一种监督式机器学习算法,用于提高任何机器学习算法的性能。 最好与像决策树这样的弱学习者一起使用。 这些模型在分类问题上的准确性要高于随机机会。

AdaBoost的概念很简单:

  • 我们将把数据集传递给多个基础学习者,每个基础学习者将尝试更正其前辈分类错误的记录。

我们会将数据集(如下所示,所有行)传递给Base Learner1。所有被Base Learner 1误分类的记录(行5,6和7被错误分类)将被传递给Base Learner 2,类似地,所有Base分类器的错误分类记录 学习者2将被传递给基本学习者3。最后,根据每个基本学习者的多数票,我们将对新记录进行分类。

 

数据科学:AdaBoost分类器

让我们逐步了解AdaBoost分类器的实现:

步骤1:获取数据集,并将初始权重分配给指定数据集中的所有样本(行)。

W = 1 / n => 1/7,其中n是样本数。

 

数据科学:AdaBoost分类器

步骤2:我们将创建第一个基础学习器。在AdaBoost中,我们将决策树用作基础学习器。这里要注意的是,我们将仅创建深度为1的决策树,它们被称为决策树桩或树桩。

 

数据科学:AdaBoost分类器

我们将为数据集的每个特征创建一个树桩,就像在我们的例子中,我们将创建三个树桩,每个特征一个。

步骤3:我们需要根据每个特征的熵值或吉尼系数,选择任何基础学习器模型(为特征1创建的基础学习器1,为特征2创建的基础学习器2,为特征3创建的基础学习器3) (我在决策树文章中已经讨论了Ginni和熵)。

熵或吉尼系数值最小的基础学习器,我们将为第一个基础学习器模型选择该模型。

第4步:我们需要找到在第3步中选择的基本学习者模型正确分类了多少条记录以及错误分类了多少条记录。

我们必须找到所有错误分类的总错误,让我们说我们是否正确分类了4条记录而错误分类了1条记录

Total Error =分类错误的记录的样本权重的总和。

因为我们只有1个错误,所以总错误= 1/7

步骤5:通过以下公式检查树桩的性能。

 

数据科学:AdaBoost分类器

当我们将Total Error放入该公式时,我们将得到0.895的值(不要偷懒地将这些值进行计算)

通过以下等式更新正确和错误分类的样本(行)的样本权重。

错误分类的样本的新样本权重=

 

数据科学:AdaBoost分类器

 

数据科学:AdaBoost分类器

正确分类的样本的新样本权重=

 

数据科学:AdaBoost分类器

 

数据科学:AdaBoost分类器

 

数据科学:AdaBoost分类器

注意:我们假设第3行的分类不正确

步骤6:我们在这里考虑的要点是,当我们将所有样本权重相加时,它等于1,但如果更新了权重,则总和不等于1。因此,我们将每个更新的权重除以总和,然后归一化 值为1。

更新权重的总和是0.68

 

数据科学:AdaBoost分类器

第7步:我们将通过删除"样品重量"和"更新重量"功能来创建数据集,并将每个样品(行)分配到一个桶中。

 

数据科学:AdaBoost分类器

步骤8:建立新的资料集。 为此,我们必须从0到1(对于每个样本(行))中随机选择一个值,然后选择该样本,该样本在" Bucket"下掉落,并将该样本保留在" NEW DATASET"中。 由于分类错误的记录具有较大的存储桶大小,因此选择该记录的可能性非常高。

 

数据科学:AdaBoost分类器

我们在这里可以看到,由于数据桶大小比其他行大,因此已在我们的数据集中选择了3次错误分类的record(Row3)。

第9步:为下一个树桩(基础学习者2,基础学习者3)获取此新数据集,并按照步骤1至8进行所有功能。

Adaboost模型通过让森林中的每棵树对样本进行分类来进行预测。然后,根据树木的决策将它们分成几组。现在,对于每组,我们对各树中每棵树的重要性进行累加。 整个森林的数量由总和最大的群体决定。下图。

 

数据科学:AdaBoost分类器

Adaboost分类器的逐步Python代码:

  1. In [1]: 
  2. #General idea behind boosting methods is to train predictors sequentially,each trying to correct its predecessor 
  3.  
  4. # AdaBoost Classifier Example In Python 
  5. # Step 1: Initialize the sample weights 
  6. # Step 2: Build a decision tree with each feature, classify the data and evaluate the result 
  7. # Step 3: Calculate the significance of the tree in the final classification 
  8. # Step 4: Update the sample weights so that the next decision tree will take the errors made by the preceding decision tree into account 
  9. # Step 5: Form a new dataset 
  10. # Step 6: Repeat steps 2 through 5 until the number of iterations equals the number specified by the hyperparameter (i.e. number of estimators) 
  11. # Step 7: Use the forest of decision trees to make predictions on data outside of the training set 
  12. In [2]: 
  13. from sklearn.ensemble import AdaBoostClassifier 
  14. from sklearn.tree import DecisionTreeClassifier 
  15. from sklearn.datasets import load_breast_cancer 
  16. import pandas as pd 
  17. import numpy as np 
  18. import seaborn as sns 
  19. import matplotlib.pyplot as plt 
  20. from sklearn.model_selection import train_test_split 
  21. from sklearn.metrics import confusion_matrix,accuracy_score 
  22. from sklearn.preprocessing import LabelEncoder 
  23. import warnings 
  24. warnings.filterwarnings('ignore'
  25. In [3]: 
  26. cancer_data=load_breast_cancer() 
  27. In [4]: 
  28. X=pd.DataFrame(cancer_data.data,columns=cancer_data.feature_names) 
  29. In [5]: 
  30. y = pd.Categorical.from_codes(cancer_data.target, cancer_data.target_names) 
  31. In [6]: 
  32. #y=pd.DataFrame(y,columns=['Cancer_Target']) 
  33. Data Preprocessing 
  34. In [7]: 
  35. X.describe() 
  36. Out[7]: 
  37. mean radius mean texture    mean perimeter  mean area   mean smoothness mean compactness    mean concavity  mean concave points mean symmetry   mean fractal dimension  ... worst radius    worst texture   worst perimeter worst area  worst smoothness    worst compactness   worst concavity worst concave points    worst symmetry  worst fractal dimension 
  38. count   569.000000  569.000000  569.000000  569.000000  569.000000  569.000000  569.000000  569.000000  569.000000  569.000000  ... 569.000000  569.000000  569.000000  569.000000  569.000000  569.000000  569.000000  569.000000  569.000000  569.000000 
  39. mean    14.127292   19.289649   91.969033   654.889104  0.096360    0.104341    0.088799    0.048919    0.181162    0.062798    ... 16.269190   25.677223   107.261213  880.583128  0.132369    0.254265    0.272188    0.114606    0.290076    0.083946 
  40. std 3.524049    4.301036    24.298981   351.914129  0.014064    0.052813    0.079720    0.038803    0.027414    0.007060    ... 4.833242    6.146258    33.602542   569.356993  0.022832    0.157336    0.208624    0.065732    0.061867    0.018061 
  41. min 6.981000    9.710000    43.790000   143.500000  0.052630    0.019380    0.000000    0.000000    0.106000    0.049960    ... 7.930000    12.020000   50.410000   185.200000  0.071170    0.027290    0.000000    0.000000    0.156500    0.055040 
  42. 25% 11.700000   16.170000   75.170000   420.300000  0.086370    0.064920    0.029560    0.020310    0.161900    0.057700    ... 13.010000   21.080000   84.110000   515.300000  0.116600    0.147200    0.114500    0.064930    0.250400    0.071460 
  43. 50% 13.370000   18.840000   86.240000   551.100000  0.095870    0.092630    0.061540    0.033500    0.179200    0.061540    ... 14.970000   25.410000   97.660000   686.500000  0.131300    0.211900    0.226700    0.099930    0.282200    0.080040 
  44. 75% 15.780000   21.800000   104.100000  782.700000  0.105300    0.130400    0.130700    0.074000    0.195700    0.066120    ... 18.790000   29.720000   125.400000  1084.000000 0.146000    0.339100    0.382900    0.161400    0.317900    0.092080 
  45. max 28.110000   39.280000   188.500000  2501.000000 0.163400    0.345400    0.426800    0.201200    0.304000    0.097440    ... 36.040000   49.540000   251.200000  4254.000000 0.222600    1.058000    1.252000    0.291000    0.663800    0.207500 
  46. rows × 30 columns 
  47.  
  48. In [8]: 
  49. X.isnull().count() 
  50. Out[8]: 
  51. mean radius                569 
  52. mean texture               569 
  53. mean perimeter             569 
  54. mean area                  569 
  55. mean smoothness            569 
  56. mean compactness           569 
  57. mean concavity             569 
  58. mean concave points        569 
  59. mean symmetry              569 
  60. mean fractal dimension     569 
  61. radius error               569 
  62. texture error              569 
  63. perimeter error            569 
  64. area error                 569 
  65. smoothness error           569 
  66. compactness error          569 
  67. concavity error            569 
  68. concave points error       569 
  69. symmetry error             569 
  70. fractal dimension error    569 
  71. worst radius               569 
  72. worst texture              569 
  73. worst perimeter            569 
  74. worst area                 569 
  75. worst smoothness           569 
  76. worst compactness          569 
  77. worst concavity            569 
  78. worst concave points       569 
  79. worst symmetry             569 
  80. worst fractal dimension    569 
  81. dtype: int64 
  82. In [9]: 
  83. def heatMap(df): 
  84.     #Create Correlation df 
  85.     corr = X.corr() 
  86.     #Plot figsize 
  87.     fig, ax = plt.subplots(figsize=(25, 25)) 
  88.     #Generate Color Map 
  89.     colormap = sns.diverging_palette(220, 10, as_cmap=True
  90.     #Generate Heat Map, allow annotations and place floats in map 
  91.     sns.heatmap(corr, cmap=colormap, annot=True, fmt=".2f"
  92.     #Apply xticks 
  93.     plt.xticks(range(len(corr.columns)), corr.columns); 
  94.     #Apply yticks 
  95.     plt.yticks(range(len(corr.columns)), corr.columns) 
  96.     #show plot 
  97.     plt.show() 
  98. In [10]: 
  99. heatMap(X) 
  100.  
  101. All the above correlated features can be dropped 
  102. In [11]: 
  103. X.boxplot(figsize=(10,15)) 
  104. Out[11]: 
  105. <matplotlib.axes._subplots.AxesSubplot at 0x1e1a0eb7fd0> 
  106.  
  107. In [12]: 
  108. le=LabelEncoder() 
  109. In [13]: 
  110. y=pd.Series(le.fit_transform(y)) 
  111. Data Split and Model Initialization 
  112. In [14]: 
  113. X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.20,random_state=42) 
  114. In [15]: 
  115. adaboost=AdaBoostClassifier(DecisionTreeClassifier(max_depth=1),n_estimators=200) 
  116. In [16]: 
  117. adaboost.fit(X_train,y_train) 
  118. Out[16]: 
  119. AdaBoostClassifier(algorithm='SAMME.R'
  120.           base_estimator=DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=1, 
  121.             max_features=None, max_leaf_nodes=None, 
  122.             min_impurity_decrease=0.0, min_impurity_split=None, 
  123.             min_samples_leaf=1, min_samples_split=2, 
  124.             min_weight_fraction_leaf=0.0, presort=False, random_state=None, 
  125.             splitter='best'), 
  126.           learning_rate=1.0, n_estimators=200, random_state=None) 
  127. In [17]: 
  128. adaboost.score(X_train,y_train) 
  129. Out[17]: 
  130. 1.0 
  131. In [18]: 
  132. adaboost.score(X_test,y_test) 
  133. Out[18]: 
  134. 0.9736842105263158 
  135. In [19]: 
  136. y_pred=adaboost.predict(X_test) 
  137. In [20]: 
  138. y_pred 
  139. Out[20]: 
  140. array([0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 
  141.        1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 
  142.        0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 
  143.        1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 
  144.        0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 
  145.        1, 0, 0, 1]) 
  146. Result Visualization 
  147. In [21]: 
  148. cm=confusion_matrix(y_test,y_pred) 
  149. print('Confusion Matrix\n {} '.format(cm)) 
  150. Confusion Matrix 
  151.  [[70  1] 
  152.  [ 2 41]]  
  153. In [22]: 
  154. ax= plt.subplot() 
  155. sns.heatmap(cm, annot=True, ax = ax); 
  156. # labels, title and ticks 
  157. ax.set_xlabel('Predicted labels'); 
  158. ax.set_ylabel('True labels');  
  159. ax.set_title('Confusion Matrix'); 
  160.  
  161. In [23]: 
  162. acc=accuracy_score(y_test,y_pred) 
  163. print('Model Accuracy is {} % '.format(round(acc,3))) 
  164. Model Accuracy is 0.974 %  

AdaBoost分类器的优点:

  • AdaBoost可用于提高弱分类器的准确性,从而使其更灵活。 现在,它已扩展到二进制分类之外,并且还发现了文本和图像分类中的用例。
  • AdaBoost具有很高的精度。
  • 不同的分类算法可以用作弱分类器。

缺点:

  • 提升技巧是逐步学习的,确保您拥有高质量的数据非常重要。
  • AdaBoost对噪声数据和异常值也非常敏感,因此,如果您打算使用AdaBoost,则强烈建议消除它们。
  • AdaBoost还被证明比XGBoost慢。

结论:在本文中,我们讨论了理解AdaBoost算法的各种方法.AdaBoost就像是一个恩赐,如果正确使用它可以提高分类算法的准确性。

希望您喜欢我的文章。请鼓掌(最多50次),这会激发我写更多的文章。

责任编辑:未丽燕 来源: 今日头条
相关推荐

2018-04-16 12:14:34

数据科学机器学习神经网络

2022-08-19 07:38:51

数据备份系统存储

2018-04-16 11:11:56

2020-05-27 11:16:49

数据科学机器学习Python

2017-08-04 15:53:10

大数据真伪数据科学家

2016-10-21 19:24:35

数据科学家数据科学

2022-11-14 10:36:55

数据科学数据分析

2018-06-29 16:00:56

数据科学家数据清理数据分析

2015-06-11 10:27:29

数据科学家

2015-07-23 14:53:50

贝叶斯分类器

2019-09-30 09:10:11

Python编程语言数据科学

2023-10-16 10:25:34

数据科学大数据

2020-10-25 20:00:18

数据科学数据科学家

2009-11-18 13:41:42

路由器分类

2021-10-08 13:45:23

大数据数据科学家货币

2018-11-06 20:30:23

Python开源工具机器学习

2012-12-26 10:51:20

数据科学家

2015-07-29 11:14:20

r语言数据科学

2014-07-01 09:20:56

大数据

2020-12-31 06:18:08

人工智能物联网大数据
点赞
收藏

51CTO技术栈公众号