⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 perceptron.m

📁 一个matlab的工具包,里面包括一些分类器 例如 KNN KMEAN SVM NETLAB 等等有很多.
💻 M
字号:
function [Y_compute, Y_prob] = Perceptron(para, X_train, Y_train, X_test, Y_test, num_class)

global temp_model_file preprocess;

Y_compute = zeros(size(Y_test)); Y_prob = zeros(size(Y_test));
if (num_class > 2)
    error('LogitReg: The class number is larger than 2!');
end;

class_set = GetClassSet(Y_train);
p = str2num(char(ParseParameter(para, {'-CostFactor'; '-MaxIter'}, {'1'; '100'}, 1)));
CostFactor = p(1);
MaxIter = p(2);

X_train_ext = [X_train ones(size(X_train, 1), 1)];
X_test_ext = [X_test ones(size(X_test, 1), 1)];

beta = [];
if (~isempty(X_train)),
    % Convert the binary labels into +/-1
    Y_train = (Y_train == class_set(1)) - (Y_train ~= class_set(1));
    beta = LearnPercept(Y_train, X_train_ext, CostFactor, MaxIter);   
    fid = fopen(temp_model_file, 'w');
    if (fid > 0),
        fprintf('Writing to %s .... \n', temp_model_file);  
        fprintf(fid, 'File: %s\n', preprocess.input_file); 
        fprintf(fid, 'N: %d\n', size(Y_train, 1)); 
        fprintf(fid, '%d ', class_set); fprintf(fid, '\n');     
        fprintf(fid, '%.4f,', beta); fprintf(fid, '\n');     
        fclose(fid);    
    end;
else
    fid = fopen(temp_model_file, 'r');
    if (fid > 0),
        fgets(fid); fgets(fid);
        line = fgetl(fid); class_set = sscanf(line, '%d');      
        line = fgetl(fid); beta = sscanf(line, '%f,');      
        fclose(fid);    
        preprocess.ClassSet = class_set;
    end;    
end;
Logit_Y_prob = X_test_ext * beta;  

% Y_prob = (exp(Logit_Y_prob) ./ (1 + exp(Logit_Y_prob))) .* (Logit_Y_prob >= 0) + (1 ./ (1 + exp(Logit_Y_prob))) .* (Logit_Y_prob < 0);
Y_prob = exp(Logit_Y_prob) ./ (1 + exp(Logit_Y_prob));
Y_compute = class_set(1) * (Logit_Y_prob >= 0) + class_set(2) * (Logit_Y_prob < 0);

function beta = LearnPercept(Y_train, X_train_ext, CostFactor, MaxIter)   

[num_data, num_feature] = size(X_train_ext);
beta = zeros(num_feature, 1);
for t = 1:MaxIter,
    all_correct = true;
    for i = 1:num_data,
       if (Y_train(i) .* (X_train_ext(i, :) * beta)) <= 0, 
            beta = beta + Y_train(i) .* X_train_ext(i, :)';
            all_correct = false;
       end;
    end;
    if (all_correct), break; end;
end;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -