2015-09-19 120 views
0

所以我想用我的數據,我下面定義(有兩個標籤),並使用KNN進行培訓和測試,也交叉驗證。我無法找到有用的MATLAB教程,所以如果你們能幫助我,我很感激。KNN Matlab列車測試交叉驗證

想象我有

Data=rand(2000,2); 
Lables=[ones(1000,1);-1*ones(1000,1)]; 

我想用KNN和有:培訓數據的

  • 50%
  • 25%交叉驗證
  • 25%的測試

回答

0

你給的數據不是這麼好的d因爲兩套之間沒有差異。您應該使用

Data = [rand(1000,2)+delta;rand(1000,2)-delta]; 

就越容易將分類 背後k近鄰的想法最大的三角洲是,你不需要任何培訓。

假設您有一個包含N個標籤值的數據集。現在假設你有一個你想分類的條目。

如果您考慮1-NN分類器,則計算輸入和N標記的訓練示例之間的距離。輸入分類爲具有最短距離的示例標籤。

在k-NN分類器中,檢查具有最短距離的示例的k個標籤。具有最多NN數量的類獲勝。

在MATLAB中,您可以使用knnserach來查找最近的k個索引,或者使用knnclassify來獲取標籤。

這裏是knnserach一個例子

delta = 0.3; 
N1 = 50; 
N2 = 50; 
Data1 = rand(1000,2)+delta; 
Data2 = rand(1000,2)-delta; 
train = [Data1(1:N1,:);Data2(1:N2,:)]; % create a training set 
labels = [ones(N1,1);-1*ones(N2,1)]; % create labels for the training 
plot(train(1:N1,1),train(1:N1,2),'xb',train(N1+1:end,1),train(N1+1:end,2),'or') 
k = 7; % Can't be an even number 
idx = knnsearch(train,Data1(N1+1:end,:),'K',k); % classify for the rest of data 1 
res1 = 0; 
for i=1:size(idx,1) 
    if sum(labels(idx(i,:))) < 0; 
     res1 = res1 + 0; % wrong answer 
    else 
     res1 = res1 + 1; % correct answer 
    end 
end 
idx2 = knnsearch(train,Data2(N2+1:end,:),'K',k); % classify for the rest of data 2 
res2 = 0; 
for i=1:size(idx2,1) 
    if sum(labels(idx2(i,:))) > 0; 
     res2 = res2 + 0; % wrong answer 
    else 
     res2 = res2 + 1; % correct answer 
    end 
end 
corr = res1+res2; 
tot = size(idx2,1)+size(idx,1); 
fprintf('Classified %d right out of %d. %.2f correct\n',corr,tot,corr/tot * 100)