您的位置:首页 > 其它

【机器学习】实验五 集成学习(投票方式)

2018-12-31 19:48 162 查看
版权声明:本文为博主原创文章,转载请标明出处 https://blog.csdn.net/C2681595858/article/details/85405240

文章目录


实验代码(github)

一、实验内容

  • 投票方式的集成学习。
  • 用5-6个模型。
  • 使用MNIST数据集。

二、理论准备

  • 图解集成学习:

    就是使用训练数据集训练出不同的模型,然后把同一个测试数据输给每个模型,然后根据这些模型的输出,按照少数服从多数的原则决定最终结果。

三、实验环境

  • winindows10
  • vs2017
  • c++

四、实验过程

  • 这次实验选择相同的分类器,用不同的训练数据集去训练他们。
  • 分类器使用的是KNN,使用5个kNN分类器,每个分类器使用200个训练数据,最后在用100个测试数据进行测试。
    函数说明如下:
    void read_Mnist_Label(string data_type, int size,unsigned char labels[1000])

    这个函数负责读取标签文件 data_type是说明要读取测试数据集(train_data)还是训练数据集(test_data).
  • size:说明要读取多少个标签数据。
  • labels:存储读取出来的标签。
    void read_Mnist_Images(string data_type,int size, unsigned char images[][784])

    这个函数负责读取图像数据。
  • 前两个参数和读取label的函数参数作用相同。
  • images存放读取出来的图像数据,这里把一幅图像存放在一个一数组中,而整个读取出来的数据集是一个二维数组.
    unsigned char KNN(unsigned char training_set[1000][784], unsigned char labels[1000], int start, int size, int k, unsigned char test[784])

    这个函数就是进行kNN分类的核心函数,
    各个参数意义如下:
  • training_set:训练数据
  • labels:训练数据标签
  • start:从训练数据的哪个位置开始作为该KNN分类器的训练数据开始的下标
  • size:样本数据大小
  • k:最近的k个样本
  • test:传入一个测试数据

然后在main中,使用一个循环来进行测试模型的正确率:

int test_number = 100;
int correct = 0;
for (int counter0 = 0; counter0 < test_number;counter0++ )//测试循环
{
//统计每个分类器的输出
int count[10] = { 0 };
for (int counter1 = 0; counter1 < 5; counter1++)
{
count[(int)(KNN(train_images, train_labels, counter1 * 200, 200, 20, test_images[counter0]))]++;//每200个训练数据作为一个分类器的训练数
}

//进行投票
unsigned char index = 0, max = 0;
for (int counter2 = 0; counter2 < 10; counter2++)
{
if (count[counter2] > max)
{
max = count[counter2];
index = counter2;
}
}
//判断分类是否正确
if (index == test_labels[counter0])
correct++;
}
cout << "正确率: " << (double)correct / (double)test_number<<endl;

五、实验结果

正确率0.7

六、实验总结

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: