how to input train and test data in K-Nearest Neighbors

2 views (last 30 days)
i want to input images data as test and train data , how to do that in this programme.??????
function test_lbls = knnAlgo(test_data, tr_data,tr_lbls,k)
%test_data = reshape(test_data,[],1);
%tr_data = reshape(tr_data,[],1);
%tr_lbls = reshape(tr_lbls,[],1);
% k of k-nearest neighbors
k = 3 ;
% generate a test image data , a matrix of 3 by 3, values are doubles that
% range from 10 to 20
test_data = [10 20 30; 20 10 30; 20 10 30];
% generate a training/apprentissage data image from test data image
tr_data = [10 0 30;0 10 0; 20 0 30];
% generate a truth image labels with 3 by 3 matrix, values are integers
% that range from 1 to 3 (10 correspond to label 1, 20 to 2 and 30 to 3)
tr_lbls = [1 2 3; 2 1 3; 2 1 3];
% generate a training/apprentissage image labels from truth image labels
tr_lbls = [1 0 3;0 1 0; 2 0 3];
% we are looking for "test_lbls" ?
%test_lbls = knnAlgo(im_test_data, im_tr_data,im_tr_lbls,k);
num_test_data = size(test_data,1);
euclidean_dst = zeros(int8(num_test_data/2),1);
test_lbls = zeros(num_test_data,1);
for sample=2:2:num_test_data
%%Step 1: Computing euclidean distance between each test_data sample and
% training data
j = 1;
for i=1:2:num_test_data
euclidean_dst(j) = abs( test_data(sample) - tr_data(i) );
j=j+1;
end
%%Step 2: compute k nearest neighbors, and store there corresponding
% labels in k_nrst_nghbors_lbls
[~, position] = sort(euclidean_dst);
k_nrst_nghbors = position(1:k);
for i=1:k
k_nrst_nghbors(i)=2*k_nrst_nghbors(i)-1;
end
k_nrst_nghbors_lbls = tr_lbls(k_nrst_nghbors);
%%Step 3 : Voting - choosing the most frequent label, if the labels are
% unique, vote for the nearest neighbor label in the neighborhood
[M,F] = mode(k_nrst_nghbors_lbls);
if F~=1
test_lbls(sample)=M;
else
test_lbls(sample)=k_nrst_nghbors_lbls(1);
end
end

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!