机器学习实验------随机森林

第1关:Bagging

任务描述

本关任务:补充 python 代码,完成 BaggingClassifier 类中的 fit 和 predict 函数。请不要修改 Begin-End 段之外的代码。

python 复制代码
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关:随机森林算法流程

任务描述

本关任务:补充 python 代码,完成 RandomForestClassifier 类中的 fit 和 predict 函数。请不要修改 Begin-End 段之外的代码。

python 复制代码
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关:手写数字识别

任务描述

本关任务:使用 sklearn 中的 RandomForestClassifier 类完成手写数字识别任务。请不要修改Begin-End段之外的代码。

python 复制代码
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 **************#
相关推荐
武子康18 分钟前
H3-World 为何在加载 LoRA 前,先检查导入的代码?
人工智能·深度学习·算法
装不满的克莱因瓶37 分钟前
【SpringAI Alibaba】ReactAgent结构化输出OutputType与OutputSchema实战
java·人工智能·ai·springai·springaialibaba
楚山之石1 小时前
【Radiology】影像组学的标准化与可重复性:IBSI 卷积滤波器共识及其未能覆盖的环节
人工智能·学习·机器学习·mri
东姬AI1 小时前
挖出948个内核漏洞、自动写补丁:GPT-6 Cyber把AI推进“实战岗“,内容行业还卡在哪一关?
人工智能·网络安全·openai·gpt-6
用户2991422196801 小时前
GitHub 热榜项目:日榜(2026-11-10)
人工智能·开源·github
用户2991422196801 小时前
AI 日报(2026年11月10日)
人工智能
QXWZ_IA1 小时前
定位数据怎么推给 IoT 平台?消息协议选型与接入准备
网络·人工智能·物联网·安全
java_logo1 小时前
Docker 部署 ReMe:轻松搭建 AI Agent 记忆管理平台
人工智能·docker·容器·ai agent·轩辕镜像·reme·agentscope-ai
硅谷秋水2 小时前
从VLM规划器到机器人智能体:面向依赖历史信息的操控任务自演化框架
人工智能·机器学习·语言模型·机器人
西安小哥2 小时前
端侧跑大模型,真正的门槛不在参数量:一次 596 秒到 10 秒的压缩路径复盘
前端·人工智能