educoder 机器学习之随机森林算法

第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

你可能感兴趣的:(educoder,机器学习,算法,随机森林)