matlab 下交叉验证与 svm (多分类)模型的使用

笔记

下面是代码,注释一般都能看懂的。

%datas为读入的数据集 labels为读入的标签

%规范化数据
[datas_normal] = premnmx(datas) ;


%交叉验证
k =10;%预将数据分成十份
sum_accuracy_svm = 0;
[m,n] = size(datas_normal);
%交叉验证,使用十折交叉验证  Kfold  
%indices为 m 行一列数据,表示每个训练样本属于k份数据的哪一份
indices = crossvalind('Kfold',m,k);

for i = 1:k
    test_indic = (indices == i);
    train_indic = ~test_indic;
    train_datas = datas_normal(train_indic,:);%找出训练数据与标签
    train_labels = labels(train_indic,:);
    test_datas = datas_normal(test_indic,:);%找出测试数据与标签
    test_labels = labels(test_indic,:);
    % 开始svm多分类训练,fitcsvm用于二分类,fitcecoc用于多分类,    
    classifer = fitcecoc(train_datas,train_labels);%训练模型
    predict_label  = predict(classifer, test_datas);%测试
    accuracy_svm = length(find(predict_label == test_labels))/length(test_labels)%准确率
    sum_accuracy_svm = sum_accuracy_svm + accuracy_svm;
end

%求平均准确率
mean_accuracy_svm = sum_accuracy_svm / k;
disp('平均准确率:');   
disp( mean_accuracy_svm); 

以后不能吃红烧肉了,减肥ing

你可能感兴趣的:(机器学习)