这是我的 k-最近邻算法代码:
function [preds, distances, indices] = knnfull(HandTrain,HandTest)
nn_value = 10; % how many nearest
inputs = HandTrain(:,2:end);
Y = HandTrain(:,1);
[preds, distances, indices] = knn_alg(inputs, y, HandTest, nn_value);
end
function [preds, D, I] = knn_alg(train_inputs, train_y, test_inputs, nn_value)
num_train_inputs = size(train_inputs,2);
num_train_examples = size(train_inputs,1)
num_test_inputs = size(test_inputs,2);
num_test_examples = size(test_inputs,1)
preds = zeros(size(test_inputs,1),1);
[D,I] = pdist2(train_inputs,test_inputs,'euclidean','Smallest',nn_value);
preds = mode(train_y(I'),2);
end
如果你问为什么我有两个独立的函数,这是一个很好的问题。但无论如何,我得到了错误:
Error in knnkaggle>knn_alg (line 16)
num_train_inputs = size(train_inputs,2);
Output argument "indices" (and maybe others) not assigned during call to
"C:...knn_alg".
Error in knnkaggle (line 10)
[preds, distances, indices] = knn_alg(inputs, y, HandTest, nn_value);
想不通问题。