Switch to unified view

a b/Ensemble Learning/Bagging/bagging_predict.m
1
% Practicum, Task #3, 'Compositions of algorithms'.
2
%
3
% FUNCTION:
4
% [prediction, err] = bagging_predict (model, X, y)
5
%
6
% DESCRIPTION:
7
% This function use the composition of algorithms, trained with bagging 
8
% method, for prediction.
9
%
10
% INPUT:
11
% X --- matrix of objects, N x K double matrix, N --- number of objects, 
12
%       K --- number of features.
13
% y --- vector of answers, N x 1 double vector, N --- number of objects. y
14
%       can have only two values --- +1 and -1.
15
% model --- trained composition.
16
%
17
% OUTPUT:
18
% prediction --- vector of predicted answers, N x 1 double vector.
19
% error --- the ratio of number of correct answers to number of objects on
20
%           each iteration, num_iterations x 1 vector
21
%
22
% AUTHOR: 
23
% Murat Apishev (great-mel@yandex.ru)
24
%
25
26
function [prediction, err] = bagging_predict (model, X, y)
27
28
    num_iterations = length(model.models);
29
    no_objects = length(y);
30
    pred_prediction = zeros([no_objects num_iterations]);
31
    err = zeros([num_iterations 1]);
32
    
33
    if strcmp(model.algorithm, 'svm')
34
        for alg = 1 : num_iterations
35
            pred_prediction(:,alg) = svmpredict(y, X, model.models{alg});
36
            func = @(i) find_max(pred_prediction(i,:));
37
            prediction = arrayfun(func, 1 : no_objects)';
38
            err(alg) = sum(prediction ~= y) / no_objects;
39
        end
40
    elseif strcmp(model.algorithm, 'classification_tree')
41
        for alg = 1 : num_iterations
42
            pred_prediction(:,alg) = predict(model.models{alg}, X);
43
            func = @(i) find_max(pred_prediction(i,:));
44
            prediction = arrayfun(func, 1 : no_objects)';
45
            err(alg) = sum(prediction ~= y) / no_objects;            
46
        end
47
    else
48
        error('Incorrect type of algorithm!');
49
    end    
50
end
51
52
function [result] = find_max (vector)
53
54
    if sum(vector == -1) > sum(vector == +1)
55
        result = -1;
56
    else
57
        result = +1;
58
    end
59
end