机器学习之随机森林算法

第1关:Bagging

import numpy as np
from collections import Counter
from sklearn.tree import DecisionTreeClassifier
class BaggingClassifier():
    def __init__(self, n_model=10):
        '''
        初始化函数
        '''
        #分类器的数量,默认为10
        self.n_model = n_model
        #用于保存模型的列表,训练好分类器后将对象append进去即可
        self.models = []
    def fit(self, feature, label):
        '''
        训练模型
        :param feature: 训练数据集所有特征组成的ndarray
        :param label:训练数据集中所有标签组成的ndarray
        :return: None
        '''
        #************* Begin ************#
        for i in range(self.n_model):
            m = len(feature)
            index = np.random.choice(m, m)
            sample_data = feature[index]
            sample_lable = label[index]
            model = DecisionTreeClassifier()
            model = model.fit(sample_data, sample_lable)
            self.models.append(model)
        #************* End **************#
    def predict(self, feature):
        '''
        :param feature:训练数据集所有特征组成的ndarray
        :return:预测结果,如np.array([0, 1, 2, 2, 1, 0])
        '''
        #************* Begin ************#
        result = []
        vote = []
        for model in self.models:
            r = model.predict(feature)
            vote.append(r)
        vote = np.array(vote)
        for i in range(len(feature)):
            v = sorted(Counter(vote[:, i]).items(), key=lambda x: x[1], reverse=True)
            result.append(v[0][0])
        return np.array(result)
        #************* End **************#

第2关:随机森林算法流程

import numpy as np
from collections import  Counter
from sklearn.tree import DecisionTreeClassifier
class RandomForestClassifier():
    def __init__(self, n_model=10):
        '''
        初始化函数
        '''
        #分类器的数量,默认为10
        self.n_model = n_model
        #用于保存模型的列表,训练好分类器后将对象append进去即可
        self.models = []
        #用于保存决策树训练时随机选取的列的索引
        self.col_indexs = []
    def fit(self, feature, label):
        '''
        训练模型
        :param feature: 训练数据集所有特征组成的ndarray
        :param label:训练数据集中所有标签组成的ndarray
        :return: None
        '''
        #************* Begin ************#
        for i in range(self.n_model):
            m = len(feature)
            index = np.random.choice(m, m)
            col_index = np.random.permutation(len(feature[0]))[:int(np.log2(len(feature[0])))]
            sample_data = feature[index]
            sample_data = sample_data[:, col_index]
            sample_lable = label[index]
            model = DecisionTreeClassifier()
            model = model.fit(sample_data, sample_lable)
            self.models.append(model)
            self.col_indexs.append(col_index)
        #************* End **************#
    def predict(self, feature):
        '''
        :param feature:训练数据集所有特征组成的ndarray
        :return:预测结果,如np.array([0, 1, 2, 2, 1, 0])
        '''
        #************* Begin ************#
        result = []
        vote = []
        for i, model in enumerate(self.models):
            f = feature[:, self.col_indexs[i]]
            r = model.predict(f)
            vote.append(r)
        vote = np.array(vote)
        for i in range(len(feature)):
            v = sorted(Counter(vote[:, i]).items(), key=lambda x: x[1], reverse=True)
            result.append(v[0][0])
        return np.array(result)
        #************* End **************#

第3关:手写数字识别

from sklearn.ensemble import RandomForestClassifier
import numpy as np
def digit_predict(train_image, train_label, test_image):
    '''
    实现功能:训练模型并输出预测结果
    :param train_image: 包含多条训练样本的样本集,类型为ndarray,shape为[-1, 8, 8]
    :param train_label: 包含多条训练样本标签的标签集,类型为ndarray
    :param test_image: 包含多条测试样本的测试集,类型为ndarry
    :return: test_image对应的预测标签,类型为ndarray
    '''

    #************* Begin ************#
    X = np.reshape(train_image, newshape=(-1, 64))
    clf=RandomForestClassifier(n_estimators=500, max_depth=10)
    clf.fit(X, y=train_label)
    return clf.predict(test_image)
    #************* End **************#
对于基础模型的实现,你可以选择使用决策树和支持向量机。下面是分别使用决策树和支持向量机作为基础模型的示例代码: 使用决策树作为基础模型: ```python from sklearn.tree import DecisionTreeClassifier class DecisionTreeModel: def __init__(self): self.model = DecisionTreeClassifier() def fit(self, X, y): self.model.fit(X, y) def predict(self, X): return self.model.predict(X) ``` 使用支持向量机作为基础模型: ```python from sklearn.svm import SVC class SVMModel: def __init__(self): self.model = SVC() def fit(self, X, y): self.model.fit(X, y) def predict(self, X): return self.model.predict(X) ``` 在集成学习中,你可以使用这些基础模型进行训练和预测,并将它们整合到集成模型中。例如,在Bagging算法中,你可以创建多个决策树或支持向量机模型,并对它们的预测结果进行投票或平均。 ```python from sklearn.utils import resample class BaggingClassifier: def __init__(self, base_model, n_estimators): self.base_model = base_model self.n_estimators = n_estimators self.models = [] def fit(self, X, y): for _ in range(self.n_estimators): model = self.base_model() # 随机采样训练数据集 sample_X, sample_y = resample(X, y) model.fit(sample_X, sample_y) self.models.append(model) def predict(self, X): predictions = [] for model in self.models: predictions.append(model.predict(X)) # 进行投票或平均 return self._majority_vote(predictions) def _majority_vote(self, predictions): result = [] for i in range(len(predictions[0])): votes = [p[i] for p in predictions] counts = {v: votes.count(v) for v in set(votes)} majority = max(counts, key=counts.get) result.append(majority) return result ``` 以上示例代码只是简单的示例,实际使用中还需要考虑更多的细节和参数调优。通过这种方式,你可以使用决策树和支持向量机作为基础模型来实现集成学习。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值