基于Python的机器学习系列(16):扩展 - AdaBoost

简介

        在本篇中,我们将扩展之前的AdaBoost算法实现,深入探索其细节并进行一些修改。我们将重点修复代码中的潜在问题,并对AdaBoost的实现进行一些调整,以提高其准确性和可用性。

1. 修复Alpha计算中的问题

        在AdaBoost中,如果分类器的错误率 e 为0,则计算出的权重 α 将是未定义的。为了解决这个问题,我们可以在计算过程中向分母中添加一个非常小的值,以避免除零错误。

2. 调整学习率

    sklearn的AdaBoost实现中包含一个learning_rate参数,这实际上是1/2​在α计算中的一部分。我们将这个参数重命名为eta,并尝试不同的eta值,以观察其对模型准确性的影响。sklearn的默认值为1。

3. 自定义决策桩

    sklearn中的DecisionTreeClassifier使用加权基尼指数来评估分裂,而我们学到的是加权错误率。我们将实现一个自定义的DecisionStump类,它使用加权错误率来替代基尼指数。为了验证自定义桩的有效性,我们将检查其是否能够与sklearn的实现提供相似的准确性。需要注意的是,如果不将标签 y 更改为-1,准确性可能会非常差。

代码示例

        以下是扩展AdaBoost实现的代码示例:

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.metrics import classification_report

# 生成数据集
X, y = make_classification(n_samples=500, random_state=1)
y = np.where(y == 0, -1, 1)  # 将标签0转换为-1

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42)

# 自定义决策桩类
class DecisionStump():
    def __init__(self):
        self.polarity = 1
        self.feature_index = None
        self.threshold = None
        self.alpha = None

    def fit(self, X, y, weights):
        m, n = X.shape
        min_error = float('inf')
        
        for feature_index in range(n):
            feature_values = np.unique(X[:, feature_index])
            for threshold in feature_values:
                for polarity in [-1, 1]:
                    predictions = np.ones(m)
                    predictions[X[:, feature_index] < threshold] = -1
                    predictions *= polarity
                    error = np.dot(weights, predictions != y)
                    
                    if error < min_error:
                        min_error = error
                        self.polarity = polarity
                        self.threshold = threshold
                        self.feature_index = feature_index

    def predict(self, X):
        predictions = np.ones(X.shape[0])
        if self.polarity == -1:
            predictions[X[:, self.feature_index] < self.threshold] = -1
        else:
            predictions[X[:, self.feature_index] >= self.threshold] = -1
        return predictions

# 自定义AdaBoost类
class AdaBoost():
    def __init__(self, S=5, eta=0.5):
        self.S = S
        self.eta = eta

    def fit(self, X, y):
        m, n = X.shape
        W = np.full(m, 1/m)
        self.clfs = []

        for _ in range(self.S):
            clf = DecisionStump()
            clf.fit(X, y, W)
            predictions = clf.predict(X)
            error = np.dot(W, predictions != y)
            
            if error == 0:
                error = 1e-10  # 避免除零错误
            
            alpha = self.eta * 0.5 * np.log((1 - error) / error)
            clf.alpha = alpha
            W *= np.exp(alpha * (predictions != y))
            W /= np.sum(W)
            self.clfs.append(clf)

    def predict(self, X):
        clf_preds = np.zeros((X.shape[0], len(self.clfs)))
        for i, clf in enumerate(self.clfs):
            clf_preds[:, i] = clf.predict(X)
        return np.sign(np.dot(clf_preds, [clf.alpha for clf in self.clfs]))

# 训练和评估自定义AdaBoost模型
ada_clf = AdaBoost(S=50, eta=0.5)
ada_clf.fit(X_train, y_train)
y_pred = ada_clf.predict(X_test)

print("自定义AdaBoost模型的分类报告:")
print(classification_report(y_test, y_pred))

结语

        在本篇中,我们扩展了AdaBoost的实现,解决了计算中的潜在问题,并尝试了不同的学习率以优化模型性能。与决策树、Bagging和随机森林相比,AdaBoost通过加权组合多个弱分类器,能够进一步提高分类性能。决策树为基础分类器提供了简单有效的分裂方式,而AdaBoost则通过提升算法强化了模型的准确性。与Bagging和随机森林不同,AdaBoost侧重于通过关注分类错误的样本来提升弱分类器的性能,从而在许多复杂任务中表现出色。

如果你觉得这篇博文对你有帮助,请点赞、收藏、关注我,并且可以打赏支持我!

欢迎关注我的后续博文,我将分享更多关于人工智能、自然语言处理和计算机视觉的精彩内容。

谢谢大家的支持!

你可能感兴趣的:(信息系统,机器学习,人工智能,python,机器学习,开发语言)