2011-01-30 168 views
0

我見過blog post對計算技術的K近鄰如下:MATLAB函數矩陣參數

function test_targets = knn(train_patterns, train_targets, test_patterns, K) 
    % Hubungi budi santosa di [email protected] 
    % untuk laporan kesalahan (bug). 
    % Implementasi the Nearest neighbor algorithm 
    % Inputs: 
    % train_patterns - Train patterns (obs x dim) D x N 
    % train_targets - Train targets    1 x N (classes) 
    % test_patterns - Test patterns    D x M (M testing) 
    % K    - jumlah nearest neighbors 
    % 
    % Outputs 
    % test_targets - Predicted targets 

    L = length(train_targets); 
    Uc   = unique(train_targets); 

    if (L < K), 
     error(’tetangga lebih banyak dari jumlah titik training’) 
    end 

    N    = size(test_patterns, 1); 
    test_targets = zeros(N,1); 
    for i = 1:N, 
     jar=(train_patterns - repmat(test_patterns(i,:),L,1)).^2; 
     dist   = sum(jar,2);%jarak tiap titik data test terhadap data training 
     [m, indices] = sort(dist);%urutkan jarak dr yg terkecil 
     yt=train_targets(indices(1:K));%ambil K jarak terkecil dan periksa labelnya 
     n    = hist(yt, Uc);%menempatkan data testing ke kelas mana (tergantung Uc) 

     [m, best]  = max(n);%mencari frekuensi maksimum kelas mana paling banyak dari K tetangga terdekat 

     test_targets(i) = Uc(best); 
    end 

我的問題是,我不斷收到以下MATLAB消息:

??? Error using ==> minus 
Matrix dimensions must agree. 

我有2個矩陣:

A is NxD A = 
670.00 1630.00 2380.00 1 
721.00 1680.00 2400.00 1 
750.00 1710.00 2440.00 1 
660.00 1800.00 2150.00 1 
660.00 1800.00 2150.00 1 
680.00 1958.00 2542.00 1 
440.00 1120.00 2210.00 2 
400.00 1070.00 2280.00 2 

B is MxD B = 
750.00 1710.00 2440.00 1 
680.00 1910.00 2440.00 1 
500.00 1000.00 2325.00 2 
500.00 1000.00 2325.00 2 

正如你所看到的,第4列說明了這個例子的類。我使用的功能,如:

train_patterns = A(:,:)  %HOW TO PASS A??, A(:,1:3)? A(1:size(B,1),:) ?? which???? 
train_targets = A(:,4)  %pass the column 4 as vector of classes 
test_patterns = B(:,1:3) %pass only the 3 columns 
Knn    = 3 

所以輸出必須與所有B例子預測的矢量1 x M。我怎樣才能做到這一點?

回答

1

您需要transpose A和B從NxD到DxN(使用'運算符)。

這樣:

train_patterns = A(:,1:3)'; %'# 3-by-N 
train_targets = A(:,4)'; %'# 1-by-N 
test_patterns = B(:,1:3)'; %'# 3-by-M (last column will be used by you for checking) 
+0

哇喬納斯,那確實的答案,非常感謝你 – cMinor 2011-01-30 03:31:08