Adaboost用matlab实现

合集下载

Matlab机器学习工具箱中的集成学习技术

Matlab机器学习工具箱中的集成学习技术

Matlab机器学习工具箱中的集成学习技术随着人工智能领域的发展和机器学习技术的不断推进,集成学习作为一种重要的机器学习方法,正在被广泛应用于各个领域。

在Matlab机器学习工具箱中,集成学习技术得到了很好的支持和实现。

本文将详细介绍Matlab机器学习工具箱中的集成学习技术,并探讨其在实际问题中的应用。

一、集成学习简介集成学习是一种将多个学习器进行适当组合的机器学习方法。

它通过对多个学习器的预测结果进行投票或加权平均等方式,获得更准确、更稳定的预测结果。

集成学习的核心思想是“三个臭皮匠胜过一个诸葛亮”,通过组合多个学习器的优势,从而实现更好的分类或回归效果。

在Matlab机器学习工具箱中,集成学习技术被封装在ensemble子库中。

该子库提供了多种集成学习算法的实现,包括AdaBoost、Bagging、随机森林等。

同时,Matlab还提供了相关的函数和工具,方便用户进行集成学习的模型训练、预测和评估。

二、AdaBoost算法AdaBoost是集成学习中最经典的算法之一,也是Matlab机器学习工具箱中支持的算法之一。

AdaBoost的核心思想是通过迭代的方式训练一系列弱分类器,并根据它们的性能进行加权组合,获得精确的分类器。

具体算法流程如下:1. 初始化数据权重:给每个样本一个初始权重,初始权重可以是相同的或根据样本分布设定。

2. 训练弱分类器:使用当前数据权重训练一个弱分类器,通常是使用一个简单的分类算法,比如决策树。

3. 更新样本权重:根据分类器的性能更新样本的权重,被错误分类的样本权重会得到增加,被正确分类的样本权重会得到减少。

4. 组合弱分类器:对每个弱分类器根据其分类性能进行加权组合,形成最终的分类器。

通过这种方式,AdaBoost能够不断改进分类器的性能,从而提高整体的预测准确率。

在Matlab中,可以使用ensemble子库中的adaboost函数来实现AdaBoost算法。

三、Bagging算法Bagging是另一种常见的集成学习算法,也是Matlab机器学习工具箱中支持的算法之一。

30个智能算法matlab代码

30个智能算法matlab代码

30个智能算法matlab代码以下是30个使用MATLAB编写的智能算法的示例代码: 1. 线性回归算法:matlab.x = [1, 2, 3, 4, 5];y = [2, 4, 6, 8, 10];coefficients = polyfit(x, y, 1);predicted_y = polyval(coefficients, x);2. 逻辑回归算法:matlab.x = [1, 2, 3, 4, 5];y = [0, 0, 1, 1, 1];model = fitglm(x, y, 'Distribution', 'binomial'); predicted_y = predict(model, x);3. 支持向量机算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3];y = [1, 1, -1, -1, -1];model = fitcsvm(x', y');predicted_y = predict(model, x');4. 决策树算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = fitctree(x', y');predicted_y = predict(model, x');5. 随机森林算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = TreeBagger(50, x', y');predicted_y = predict(model, x');6. K均值聚类算法:matlab.x = [1, 2, 3, 10, 11, 12]; y = [1, 2, 3, 10, 11, 12]; data = [x', y'];idx = kmeans(data, 2);7. DBSCAN聚类算法:matlab.x = [1, 2, 3, 10, 11, 12]; y = [1, 2, 3, 10, 11, 12]; data = [x', y'];epsilon = 2;minPts = 2;[idx, corePoints] = dbscan(data, epsilon, minPts);8. 神经网络算法:matlab.x = [1, 2, 3, 4, 5];y = [0, 0, 1, 1, 1];net = feedforwardnet(10);net = train(net, x', y');predicted_y = net(x');9. 遗传算法:matlab.fitnessFunction = @(x) x^2 4x + 4;nvars = 1;lb = 0;ub = 5;options = gaoptimset('PlotFcns', @gaplotbestf);[x, fval] = ga(fitnessFunction, nvars, [], [], [], [], lb, ub, [], options);10. 粒子群优化算法:matlab.fitnessFunction = @(x) x^2 4x + 4;nvars = 1;lb = 0;ub = 5;options = optimoptions('particleswarm', 'PlotFcn',@pswplotbestf);[x, fval] = particleswarm(fitnessFunction, nvars, lb, ub, options);11. 蚁群算法:matlab.distanceMatrix = [0, 2, 3; 2, 0, 4; 3, 4, 0];pheromoneMatrix = ones(3, 3);alpha = 1;beta = 1;iterations = 10;bestPath = antColonyOptimization(distanceMatrix, pheromoneMatrix, alpha, beta, iterations);12. 粒子群-蚁群混合算法:matlab.distanceMatrix = [0, 2, 3; 2, 0, 4; 3, 4, 0];pheromoneMatrix = ones(3, 3);alpha = 1;beta = 1;iterations = 10;bestPath = particleAntHybrid(distanceMatrix, pheromoneMatrix, alpha, beta, iterations);13. 遗传算法-粒子群混合算法:matlab.fitnessFunction = @(x) x^2 4x + 4;nvars = 1;lb = 0;ub = 5;gaOptions = gaoptimset('PlotFcns', @gaplotbestf);psOptions = optimoptions('particleswarm', 'PlotFcn',@pswplotbestf);[x, fval] = gaParticleHybrid(fitnessFunction, nvars, lb, ub, gaOptions, psOptions);14. K近邻算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = fitcknn(x', y');predicted_y = predict(model, x');15. 朴素贝叶斯算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = fitcnb(x', y');predicted_y = predict(model, x');16. AdaBoost算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3];y = [0, 0, 1, 1, 1];model = fitensemble(x', y', 'AdaBoostM1', 100, 'Tree'); predicted_y = predict(model, x');17. 高斯混合模型算法:matlab.x = [1, 2, 3, 4, 5]';y = [0, 0, 1, 1, 1]';data = [x, y];model = fitgmdist(data, 2);idx = cluster(model, data);18. 主成分分析算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; coefficients = pca(x');transformed_x = x' coefficients;19. 独立成分分析算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; coefficients = fastica(x');transformed_x = x' coefficients;20. 模糊C均值聚类算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; options = [2, 100, 1e-5, 0];[centers, U] = fcm(x', 2, options);21. 遗传规划算法:matlab.fitnessFunction = @(x) x^2 4x + 4; nvars = 1;lb = 0;ub = 5;options = optimoptions('ga', 'PlotFcn', @gaplotbestf);[x, fval] = ga(fitnessFunction, nvars, [], [], [], [], lb, ub, [], options);22. 线性规划算法:matlab.f = [-5; -4];A = [1, 2; 3, 1];b = [8; 6];lb = [0; 0];ub = [];[x, fval] = linprog(f, A, b, [], [], lb, ub);23. 整数规划算法:matlab.f = [-5; -4];A = [1, 2; 3, 1];b = [8; 6];intcon = [1, 2];[x, fval] = intlinprog(f, intcon, A, b);24. 图像分割算法:matlab.image = imread('image.jpg');grayImage = rgb2gray(image);binaryImage = imbinarize(grayImage);segmented = medfilt2(binaryImage);25. 文本分类算法:matlab.documents = ["This is a document.", "Another document.", "Yet another document."];labels = categorical(["Class 1", "Class 2", "Class 1"]);model = trainTextClassifier(documents, labels);newDocuments = ["A new document.", "Another new document."];predictedLabels = classifyText(model, newDocuments);26. 图像识别算法:matlab.image = imread('image.jpg');features = extractFeatures(image);model = trainImageClassifier(features, labels);newImage = imread('new_image.jpg');newFeatures = extractFeatures(newImage);predictedLabel = classifyImage(model, newFeatures);27. 时间序列预测算法:matlab.data = [1, 2, 3, 4, 5];model = arima(2, 1, 1);model = estimate(model, data);forecastedData = forecast(model, 5);28. 关联规则挖掘算法:matlab.data = readtable('data.csv');rules = associationRules(data, 'Support', 0.1);29. 增强学习算法:matlab.environment = rlPredefinedEnv('Pendulum');agent = rlDDPGAgent(environment);train(agent);30. 马尔可夫决策过程算法:matlab.states = [1, 2, 3];actions = [1, 2];transitionMatrix = [0.8, 0.1, 0.1; 0.2, 0.6, 0.2; 0.3, 0.3, 0.4];rewardMatrix = [1, 0, -1; -1, 1, 0; 0, -1, 1];policy = mdpPolicyIteration(transitionMatrix, rewardMatrix);以上是30个使用MATLAB编写的智能算法的示例代码,每个算法都可以根据具体的问题和数据进行相应的调整和优化。

Adaboost算法多类问题Matlab实现演示教学

Adaboost算法多类问题Matlab实现演示教学

A d a b o o s t算法多类问题M a t l a b实现一种adaboost多类分类算法Matlab实现一、adaboost算法简介Adaboost算法的主要思想是给定一个训练集(x1,y1),…,(xm,ym),其中xi属于某个域或者实例空间X,yi=-1或者+1。

初始化时Adaboost指定训练集上的分布为1/m,并按照该分布调用弱学习器对训练集上的分布,并按照该分布调用弱学习器对训练集进行训练,每次训练后,根据训练结果更新训练集上的分布,并按照新的样本分布进行训练。

反复迭代T轮,最终得到一个估计序列h1,..,hT,每个估计都具有一定的权重,最终的估计H是采用权重投票方式获得。

Adaboost算法的伪代码如图1所示。

图1、Adaboost算法二、多类问题从上面的流程可以看出,Adaboost算法是针对二类问题的。

但是我们面对的问题很多都是不是简单的非0即1,而是多类问题。

常见的就是解决方法,就是把多类问题转换成二类问题。

用的比较多就是两种组合方法,OAA和OAO,我这里就是采用对这种方法的结合,实现adaboost算法对多类问题的分类。

目前需要对7类问题进行分类,依次编号:0、1、2、3、4、5、6。

特征向量 28个。

样本总数 840个;OAA分类器的个数 7 个OAO分类器的个数 7(7-1)/2 = 21个。

弱分类器的个数 K= 10;弱分类用BP神经网络算法的思路:Step1、把数据分成训练集和测试集Step 2、训练OAA、OAO分类器;Step3、保存相应的分类器和投票权重;Step4、测试样本,预测所以OAA分类器的权重;Step5、选择OAA预测值中最大的两个Step6、选用OAO分类器对选取预测权重最大的两个类进行预测;Step7、输出测试结果;注:为了统一,在训练OAO分类器是,把类别序列在前的类为正样本,输出+1,类别序列号在后面的为负样本,输出为-1。

测试强分类器的识别率为:0.93左右。

adaboost算法程序matlab

adaboost算法程序matlab

adaboost算法程序matlabAdaboost算法是一种常用的集成学习方法,广泛应用于分类问题中。

它的核心思想是通过集成多个弱分类器,来构建一个强分类器,从而提高整体分类的准确性。

本文将介绍Adaboost算法的原理和主要步骤,并使用Matlab编写一个简单的Adaboost算法程序。

Adaboost算法的原理非常简单,它通过迭代的方式,每次训练一个弱分类器,并根据分类结果调整样本权重,使得分类错误的样本在下一轮训练中得到更多的关注。

最终,将所有弱分类器的结果进行加权投票,得到最终的分类结果。

Adaboost算法的主要步骤如下:1. 初始化样本权重。

将所有样本的权重初始化为相等值,通常为1/N,其中N为样本数量。

2. 迭代训练弱分类器。

在每一轮迭代中,根据当前样本权重训练一个弱分类器。

弱分类器可以是任何分类算法,如决策树、支持向量机等。

3. 计算分类误差率。

根据当前弱分类器的分类结果,计算分类误差率。

分类误差率定义为分类错误的样本权重之和。

4. 更新样本权重。

根据分类误差率,更新样本权重。

分类错误的样本权重会增加,而分类正确的样本权重会减少。

5. 计算弱分类器权重。

根据分类误差率,计算当前弱分类器的权重。

分类误差率越小的弱分类器权重越大,反之越小。

6. 更新样本权重分布。

根据弱分类器的权重,更新样本权重分布。

分类错误的样本权重会增加,而分类正确的样本权重会减少。

7. 终止条件判断。

如果达到预定的迭代次数或分类误差率满足终止条件,则停止迭代。

8. 构建强分类器。

将所有弱分类器的结果进行加权投票,得到最终的分类结果。

权重越大的弱分类器对分类结果的贡献越大。

接下来,我们使用Matlab编写一个简单的Adaboost算法程序。

假设我们有一个二分类问题的训练集,包含N个样本和D个特征。

我们使用决策树作为弱分类器。

我们需要定义一些参数,如迭代次数和弱分类器数量。

然后,我们初始化样本权重和弱分类器权重。

MATLAB_智能算法30个案例分析

MATLAB_智能算法30个案例分析

MATLAB_智能算法30个案例分析1.线性回归:使用MATLAB的回归工具箱,对给定的数据集进行线性回归分析,获取拟合的直线方程。

2.逻辑回归:使用MATLAB的分类工具箱,对给定的数据集进行逻辑回归分析,建立分类模型。

3.K均值聚类:使用MATLAB的聚类工具箱,对给定的数据集进行K 均值聚类算法,将数据集分为多个簇。

4.支持向量机:使用MATLAB的SVM工具箱,对给定的数据集进行支持向量机算法,建立分类或回归模型。

5.决策树:使用MATLAB的分类工具箱,对给定的数据集进行决策树分析,建立决策模型。

6.随机森林:使用MATLAB的分类和回归工具箱,对给定的数据集进行随机森林算法,集成多个决策树模型。

7. AdaBoost:使用MATLAB的分类工具箱,对给定的数据集进行AdaBoost算法,提升分类性能。

8.遗传算法:使用MATLAB的全局优化工具箱,利用遗传算法进行优化问题的求解。

9.粒子群优化:使用MATLAB的全局优化工具箱,利用粒子群优化算法进行优化问题的求解。

10.模拟退火算法:使用MATLAB的全局优化工具箱,利用模拟退火算法进行优化问题的求解。

11.神经网络:使用MATLAB的神经网络工具箱,构建和训练多层感知机模型。

12.卷积神经网络:使用MATLAB的深度学习工具箱,构建和训练卷积神经网络模型。

13.循环神经网络:使用MATLAB的深度学习工具箱,构建和训练循环神经网络模型。

14.长短期记忆网络:使用MATLAB的深度学习工具箱,构建和训练长短期记忆网络模型。

15.GAN(生成对抗网络):使用MATLAB的深度学习工具箱,构建和训练生成对抗网络模型。

16.自编码器:使用MATLAB的深度学习工具箱,构建和训练自编码器模型。

17.强化学习:使用MATLAB的强化学习工具箱,构建和训练强化学习模型。

18.关联规则挖掘:使用MATLAB的数据挖掘工具箱,发现数据中的关联规则。

catboost matlab代码

catboost matlab代码

一、CatBoost简介CatBoost是一种用于机器学习的开源梯度提升库,由Yandex开发。

它专门针对类别特征进行优化,能够自动处理类别特征的编码,从而减少了许多特性工程的工作量。

CatBoost能够快速训练模型,具有出色的性能,并且在大规模数据集上表现出色。

二、Matlab代码中使用CatBoost的优势1. 支持类别特征编码在传统的机器学习模型中,类别特征通常需要进行独热编码或者标签编码等处理,而CatBoost能够自动处理类别特征的编码,极大地减少了特性工程的工作量。

2. 快速训练模型由于CatBoost是专门针对大规模数据集进行优化的,因此在处理大规模数据集时,CatBoost能够比传统的机器学习模型更快速地训练模型。

3. 出色的性能CatBoost在各种机器学习任务上都展现出了出色的性能,尤其是在处理类别特征较多的数据集时,CatBoost能够更好地发挥其优势。

三、在Matlab中使用CatBoost的方法在Matlab中使用CatBoost,需要先安装CatBoost库,并在Matlab中载入CatBoost库。

接下来,可以使用CatBoost库提供的各种函数进行模型的训练和预测。

以下是一个简单的示例代码:```Matlab导入数据data = load('data.csv');X = data(:, 1:end-1);y = data(:, end);创建CatBoost模型mdl = fitcensemble(X, y, 'Method', 'catboost', 'Learners', 'tree', 'NumLearningCycles', 100);进行预测pred = predict(mdl, X);```以上代码示例中,首先导入数据,然后使用CatBoost库提供的fitcensemble函数创建CatBoost模型,最后使用predict函数进行预测。

adaboost-bp的matlab代码

adaboost-bp的matlab代码

Adaboost算法和BP算法都是常用的机器学习算法,在应用中有着广泛的应用。

本文将分别介绍Adaboost和BP算法的原理,然后给出它们在Matlab中的代码实现。

1. Adaboost算法原理Adaboost(Adaptive Boosting)算法是一种集成学习方法,它通过训练多个弱分类器,然后将这些弱分类器进行组合,构成一个强分类器。

Adaboost算法的基本思想是每一轮训练都调整数据分布,使得前一轮分类错误的样本在下一轮中受到更多的关注,以此来提高分类的准确性。

Adaboost的算法流程如下:1. 初始化训练数据的权值分布,使得每个样本的权值相等。

2. 对于每一轮训练,根据当前的数据权值分布训练一个弱分类器。

3. 计算该弱分类器的分类错误率,并根据错误率调整样本的权值分布。

4. 根据弱分类器的权重,更新最终的分类器。

5. 重复步骤2-4,直到达到预定的训练轮数或者分类误差达到要求。

2. BP算法原理BP(Back Propagation)算法是一种常用的神经网络训练算法,它通过利用梯度下降法来不断调整神经网络的权值,使得网络的输出尽可能接近于期望的输出。

BP算法的基本思想是通过计算误差的梯度来调整网络中每一个连接的权值,以最小化网络的总误差。

BP算法的算法流程如下:1. 初始化神经网络的权值,可以使用随机值来进行初始化。

2. 对于每一个训练样本,通过正向传播计算网络的输出,并计算输出与期望输出之间的误差。

3. 通过反向传播计算每个权值的梯度,并根据梯度下降法来调整权值。

4. 重复步骤2-3,直到达到预定的训练轮数或者网络的误差达到要求。

3. Adaboost的Matlab代码实现以下是Adaboost算法在Matlab中的代码实现:```function [strongClassifier, alpha] = adaboost(X, y, T)N = size(X, 1); 样本数D = ones(N, 1)/N; 初始化样本权值分布weakClassifiers = cell(1, T); 初始化弱分类器数组alpha = zeros(1, T); 初始化弱分类器权重数组for t = 1:T训练一个弱分类器[weakClassifier, error, h] = tr本人nWeakClassifier(X, y, D);if error >= 0.5break; 弱分类器误差大于0.5,停止训练end更新弱分类器权重alpha(t) = 0.5 * log((1-error)/error);更新样本权值分布D = D .* exp(-alpha(t) * y .* h);D = D / sum(D);保存弱分类器和权重weakClassifiers{t} = weakClassifier;end构建强分类器strongClassifier.weakClassifiers = weakClassifiers; strongClassifier.alpha = alpha;end```4. BP算法的Matlab代码实现以下是BP算法在Matlab中的代码实现:```function [W1, W2] = tr本人nBP(X, y, hiddenSize, lr, epochs) inputSize = size(X, 2);outputSize = size(y, 2);W1 = randn(inputSize, hiddenSize); 输入层到隐藏层的权值矩阵W2 = randn(hiddenSize, outputSize); 隐藏层到输出层的权值矩阵for epoch = 1:epochsfor i = 1:size(X, 1)正向传播z1 = X(i, :) * W1;a1 = sigmoid(z1);z2 = a1 * W2;a2 = sigmoid(z2);计算误差error = y(i, :) - a2;反向传播d2 = error .* dsigmoid(z2);d1 = (d2 * W2') .* dsigmoid(z1);更新权值W2 = W2 + lr * a1' * d2;W1 = W1 + lr * X(i, :)' * d1;endendend```以上分别介绍了Adaboost算法和BP算法的原理,以及它们在Matlab中的代码实现。

完整word版,BOOST电路设计及matlab仿真

完整word版,BOOST电路设计及matlab仿真

Boost升压电路及MATLAB仿真一、设计要求1.输入电压(VIN):12V2.输出电压(VO):18V3.输出电流(IN):5A4.电压纹波:0.1V5.开关频率设置为50KHz需设计一个闭环控制电路,输入电压在10—14V或负载电流在2—5A范围变化时,稳态输出能够保持在18V 。

根据设计要求很显然是要设计一个升压电路即Boost电路。

Boost电路又称为升压型电路,是一种开关直流升压电路,它可以是输出电压比输入电压高。

其工作过程包括电路启动时的瞬态工作过程和电路稳定后的稳态工作过程。

二、主电路设计图1主电路2.1 Boost电路的工作原理Boost升压电路电感的作用:是将电能和磁场能相互转换的能量转换器件,当MOS开关管闭合后,电感将电能转换为磁场能储存起来,当MOS断开后电感将储存的磁场能转换为电场能,且这个能量在和输入电源电压叠加后通过二极管和电容的滤波后得到平滑的直流电压提供给负载,由于这个电压是输入电源电压和电感的磁场能转换为电能的叠加后形成的,所以输出电压高于输入电压,既升压过程的完成。

Boost升压电路的肖特基二极管主要起隔离作用,即在MOS开关管闭合时,肖特基二极管的正极电压比负极的电压低,此时二极管反向截止,使此电感的储能过程不影响输出端电容对负载的正常供电;因在MOS管断开时,两种叠加后的能量通过二极向负载供电,此时二极管正向导通,要求其正向压降越小越好,尽量使更多的能量供给到负载端。

闭合开关会引起通过电感的电流增加。

打开开关会促使电流通过二极管流向输出电容因储存来自电感的电流,多个开关周期以后输出电容的电压升高,结果输出电压高于输入电压。

接下来分两部分对Boost电路作具体介绍即充电过程和放电过程。

充电过程在充电过程中,开关闭合(三极管导通),等效电路如图二,开关(三极管)处用导线代替。

这时,输入电压流过电感。

二极管防止电容对地放电。

由于输入是直流电,所以电感上的电流以一定的比率线性增加,这个比率跟电感大小有关。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Adaboost用matlab实现Adaboost用matlab实现一例。

Mathworks网站找到的。

可以直接复制下面代码到matlab中,不过会缺少两个图形。

或者把下面每个函数(共6个)分别放在6个m文件中,然后运行demo文件。

说明----------目录中包含一下文件。

1. ADABOOST_te.m2. ADABOOST_tr.m3. demo.m4. likelihood2class.m5. threshold_te.m6. threshold_tr.m本工程的目的是为被称做AdaBoost的学习算法提供一个源文件,以提高用户定义的分类的性能。

要使用adaboost,首先两个函数必须用合适的参数运行。

对于每个源文件的解释都可以通过"help"命令得到。

要看它们是如何工作的,运行demo.m,即>> demo。

demo.m中的前三行说明了训练集和测试集的长度以及若分类器的数量。

要发现bug,请马上向作者发送一封邮件。

Cuneyt Mertayake mail: cuneyt.mertayak@版本:1.0 日期:03/09/2008%% DEMONSTRATION OF ADABOOST_tr and ADABOOST_te %% Just type "demo" to run the demo. %% Using adaboost with linear threshold classifier% for a two class classification problem. %% Bug Reporting: Please contact the author for bug reporting and comments.%% Cuneyt Mertayak% email: cuneyt.mertayak@ % version: 1.0% date: 21/05/2007% Creating the training and testing sets %tr_n = 200;te_n = 200;weak_learner_n = 20;tr_set = abs(rand(tr_n,2))*100;te_set = abs(rand(te_n,2))*100;tr_labels = (tr_set(:,1)-tr_set(:,2) > 0) + 1; te_labels =(te_set(:,1)-te_set(:,2) > 0) + 1;% Displaying the training and testing sets figure;subplot(2,2,1);hold on; axis square;indices = tr_labels==1;plot(tr_set(indices,1),tr_set(indices,2),'b*'); indices = ~indices;plot(tr_set(indices,1),tr_set(indices,2),'r*'); title('Trainingset');subplot(2,2,2);hold on; axis square;indices = te_labels==1;plot(te_set(indices,1),te_set(indices,2),'b*'); indices = ~indices;plot(te_set(indices,1),te_set(indices,2),'r*'); title('Testing set');% Training and testing error ratestr_error = zeros(1,weak_learner_n);te_error = zeros(1,weak_learner_n);for i=1:weak_learner_nadaboost_model =ADABOOST_tr(@threshold_tr,@threshold_te,tr_set,tr_labels,i);[L_tr,hits_tr] =ADABOOST_te(adaboost_model,@threshold_te,tr_set,tr_labels);tr_error(i) = (tr_n-hits_tr)/tr_n;[L_te,hits_te] =ADABOOST_te(adaboost_model,@threshold_te,te_set,te_labels);te_error(i) = (te_n-hits_te)/te_n;endsubplot(2,2,3);plot(1:weak_learner_n,tr_error);axis([1,weak_learner_n,0,1]);title('Training Error');xlabel('weak classifier number');ylabel('error rate');grid on;subplot(2,2,4); axis square;plot(1:weak_learner_n,te_error);axis([1,weak_learner_n,0,1]);title('Testing Error');xlabel('weak classifier number');ylabel('error rate');grid on;function adaboost_model = ADABOOST_tr(tr_func_handle, te_func_handle, train_set, labels, no_of_hypothesis)%% ADABOOST TRAINING: A META-LEARNING ALGORITHM% adaboost_model = ADABOOST_tr(tr_func_handle,te_func_handle,% train_set,labels,no_of_hypothesis) %% 'tr_func_handle' and 'te_func_handle' are function handles for % training and testing of a weak learner, respectively. The weak learner % has to support the learning in weighted datasets. The prototypes % of these functions has to be as follows.%% model = train_func(train_set,sample_weights,labels)% train_set: a TxD-matrix where each row is a training sample in % a D dimensional feature space.% sample_weights: a Tx1 dimensional vector, the i-th entry % ofwhich denotes the weight of the i-th sample. % labels: a Tx1 dimensional vector, the i-th entry of which % is the label of the i-th sample.% model: the output model of the training phase, which can %consists of parameters estimated.%% [L,hits,error_rate] =test_func(model,test_set,sample_weights,true_labels) % model: the output of train_func% test_set: a KxD dimensional matrix, each of whose row is a %testing sample in a D dimensional feature space. % sample_weights: a Dx1 dimensional vector, the i-th entry % of which denotes the weight of the i-th sample.% true_labels: a Dx1 dimensional vector, the i-th entry of which %is the label of the i-th sample.% L: a Dx1-array with the predicted labels of the samples. % hits: number of hits, calculated with the comparison of L and % true_labels.% error_rate: number of misses divided by the number of samples. % %% 'train_set' contains the samples for training and it is NxD matrix % where N is the number of samples and D is the dimension of the % feature space. 'labels' is an Nx1 matrix containing the class % labels of the samples. 'no_of_hypothesis' is the number of weak % learners to be used.%% The output 'adaboost_model' is a structure with the fields % -'weights': 1x'no_of_hypothesis' matrix specifying the weights % of theresulted weighted majority voting combination % - 'parameters':1x'no_of_hypothesis' structure matrix specifying % the special parameters of the hypothesis that is % created at the corresponding iteration of % learning algorithm%% Specific Properties That Must Be Satisfied by The Function pointed % by 'func_handle'% ------------------------------------------------------------------ %% Note: Labels must be positive integers from 1 upto the number of classes. % Node-2: Weighting is done as specified in AIMA book, Stuart Russell et.al. (sec edition) %% Bug Reporting: Please contact the author for bug reporting and comments. %% Cuneyt Mertayak% email: cuneyt.mertayak@% version: 1.0% date: 21/05/2007%adaboost_model = struct('weights',zeros(1,no_of_hypothesis),...'parameters',[]); %cell(1,no_of_hypothesis));sample_n = size(train_set,1);samples_weight = ones(sample_n,1)/sample_n;for turn=1:no_of_hypothesisadaboost_model.parameters{turn} =tr_func_handle(train_set,samples_weight,labels);[L,hits,error_rate] =te_func_handle(adaboost_model.parameters{turn},...train_set,samples_weight,labels);if(error_rate==1)error_rate=1-eps;elseif(error_rate==0)error_rate=eps;end% The weight of the turn-th weak classifieradaboost_model.weights(turn) = log10((1-error_rate)/error_rate);C=likelihood2class(L);t_labeled=(C==labels); % true labeled samples% Importance of the true classified samples is decreased for the next weak classifiersamples_weight(t_labeled) = samples_weight(t_labeled)*...((error_rate)/(1-error_rate));% Normalizationsamples_weight = samples_weight/sum(samples_weight);end% Normalizationadaboost_model.weights=adaboost_model.weights/sum(adaboost_model.wei ghts);function [L,hits] =ADABOOST_te(adaboost_model,te_func_handle,test_set,...true_labels)%% ADABOOST TESTING%% [L,hits] = ADABOOST_te(adaboost_model,te_func_handle,train_set, % true_labels)%% 'te_func_handle' is a handle to the testing function of a % learning (weak) algorithm whose prototype is shown below. % % [L,hits,error_rate] =test_func(model,test_set,sample_weights,true_labels) % model: the output of train_func% test_set: a KxD dimensional matrix, each of whose row is a %testing sample in a D dimensional feature space. % sample_weights: a Dx1 dimensional vector, the i-th entry % of which denotes the weight of the i-th sample. % true_labels: a Dx1 dimensional vector, the i-th entry of which% is the label of the i-th sample.% L: a Dx1-array with the predicted labels of the samples. % hits: number of hits, calculated with the comparison of L and % true_labels.% error_rate: number of misses divided by the number of samples. % % It is the corresponding testing% module of the function that is specified in the training phase. % 'test_set' is a NxD matrix where N is the number of samples % in thetest set and D is the dimension of the feature space. % 'true_labels' is a Nx1 matrix specifying the class label of % each corresponding sample's features (each row) in 'test_set'. % 'adaboost_model' is the model that is generated by the function % 'ADABOOST_tr'.%% 'L' is the likelihoods that are assigned by the 'ADABOOST_te'. %'hits' is the number of correctly predicted labels. %% Specific Properties That Must Be Satisfied by The Function pointed % by 'func_handle'% ------------------------------------------------------------------ %% Notice: Labels must be positive integer values from 1 upto the number classes. %% Bug Reporting: Please contact the author for bug reporting and comments. %% Cuneyt Mertayak% email: cuneyt.mertayak@% version: 1.0% date: 21/05/2007%hypothesis_n = length(adaboost_model.weights);sample_n = size(test_set,1);class_n = length(unique(true_labels));temp_L = zeros(sample_n,class_n,hypothesis_n); % likelihoods for each weak classifier% for each weak classifier, likelihoods of test samples are collected for i=1:hypothesis_n[temp_L(:,:,i),hits,error_rate] =te_func_handle(adaboost_model.parameters{i},...test_set,ones(sample_n,1),true_labels);temp_L(:,:,i) = temp_L(:,:,i)*adaboost_model.weights(i);endL = sum(temp_L,3);hits = sum(likelihood2class(L)==true_labels);function model = threshold_tr(train_set, sample_weights, labels) % % TRAINING THRESHOLD CLASSIFIER%% Training of the basic linear classifier where seperation hyperplane % is perpedicular to one dimension.%% model = threshold_tr(train_set, sample_weights, labels) %train_set: an NxD-matrix, each row is a training sample in the D dimensional feature% space.% sample_weights: an Nx1-vector, each entry is the weight of the corresponding trainingsample% labels: Nx1 dimensional vector, each entry is the corresponding label (either 1 or 2)%% model: the ouput model. It consists of% 1) min_error: training error% 2) min_error_thr: threshold value% 3) pos_neg: whether up-direction shows the positive region (label:2, 'pos') or% the negative region (label:1, 'neg')%% Bug Reporting: Please contact the author for bug reporting and comments. %% Cuneyt Mertayak% email: cuneyt.mertayak@% version: 1.0% date: 21/05/2007model =struct('min_error',[],'min_error_thr',[],'pos_neg',[],'dim',[]);sample_n = size(train_set,1);min_error = sum(sample_weights);min_error_thr = 0;pos_neg = 'pos';% for each dimensionfor dim=1:size(train_set,2)sorted = sort(train_set(:,dim),1,'ascend');% for each interval in the specified dimensionfor i=1:(sample_n+1)if(i==1)thr = sorted(1)-0.5;elseif(i==sample_n+1)thr = sorted(sample_n)+0.5;elsethr = (sorted(i-1)+sorted(i))/2;endind1 = train_set(:,dim) < thr;ind2 = ~ind1;tmp_err = sum(sample_weights((labels.*ind1)==2)) + sum(sample_weights((labels.*ind2)==1));if(tmp_err < min_error)min_error = tmp_err;min_error_thr = thr;pos_neg = 'pos';model.dim = dim;endind1 = train_set(:,dim) < thr;ind2 = ~ind1;tmp_err = sum(sample_weights((labels.*ind1)==1)) +sum(sample_weights((labels.*ind2)==2));if(tmp_err < min_error)min_error = tmp_err;min_error_thr = thr;pos_neg = 'neg';model.dim = dim;endendendmodel.min_error = min_error;model.min_error_thr = min_error_thr; model.pos_neg = pos_neg;function [L,hits,error_rate] =threshold_te(model,test_set,sample_weights,true_labels)%% TESTING THRESHOLD CLASSIFIER%% Testing of the basic linear classifier where seperation hyperplane is % perpedicular to one dimension.%% [L,hits,error_rate] =threshold_te(model,test_set,sample_weights,true_labels) % % model: the model that is outputed from threshold_tr. It consists of % 1) min_error: training error% 2) min_error_thr: threshold value% 3) pos_neg: whether up-direction shows the positive region (label:2, 'pos') or % the negative region (label:1, 'neg') % test_set: an NxD-matrix, each row is a testing sample in the D dimensional feature % space.% sample_weights: an Nx1-vector, each entry is the weight of the corresponding test sample% true_labels: Nx1 dimensional vector, each entry is the corresponding label (either 1 or 2)%% L: an Nx2-matrix showing likelihoods of each class% hits: the number of hits% error_rate: the error rate with the sample weights%%% Bug Reporting: Please contact the author for bug reporting and comments. %% Cuneyt Mertayak% email: cuneyt.mertayak@% version: 1.0% date: 21/05/2007feat = test_set(:,model.dim);if(strcmp(model.pos_neg,'pos'))ind = (feat>model.min_error_thr)+1;elseind = (feat<model.min_error_thr)+1;endhits = sum(ind==true_labels);error_rate = sum(sample_weights(ind~=true_labels));L = zeros(length(feat),2);L(ind==1,1) = 1;L(ind==2,2) = 1;function classes = likelihood2class(likelihoods)%% LIKELIHOODS TO CLASSES%% classes = likelihood2class(likelihoods)%% Find the class assignment of the samples from the likelihoods %'likelihoods' an NxD matrix where N is the number of samples and % D is the dimension of the feature space. 'likelihoods(i,j)' is % the i-th samples likelihood of belonging to class-j. %% 'classes' contains the class index of the each sample maximum likelihood %% Bug Reporting: Please contact the author for bug reporting and comments. %% Cuneyt Mertayak% email: cuneyt.mertayak@% version: 1.0% date: 21/05/2007%[sample_n,class_n] = size(likelihoods);maxs = (likelihoods==repmat(max(likelihoods,[],2),[1,class_n])); classes=zeros(sample_n,1);for i=1:sample_nclasses(i) = find(maxs(i,:),1);end。

相关文档
最新文档