這是我在Matlab寫了去年的 k-最近鄰概率分佈的代碼:K-NN鄰居到Python
function [ p_y_x ] = p_y_x_KNN(y, K)
% Function calculates distribution p(y|x) for each class and each object
% from test dataset using KNN classifier
% y - matrix of sorted class labels for training dataset N1xN2
% K - number of nearest neighbors
% p_y_x - probability matrix for object in X
% each row of matrix represents distribution p(y|x)) N1xM
% N1 - number of elements in testing dataset
% N2 - number of elements in training dataset
% M - number of classes
N1 = size(y,1);
M = length(unique(y));
p_y_x = zeros(N1,M);
N2 = size(y,2);
for i=1:N1
for j=1:M
p_y_x(i,j) = (1/K)*sum(y(i, 1:K) == j);
end
end
end
它的工作原理。現在我需要將它翻譯成Python。到目前爲止我有這個,我不明白它有什麼問題。它不會工作。
def p_y_x_knn(y, k):
"""
Function calculates conditional probability p(y|x) for
all classes and all objects from test set using KNN classifier
:param y: matrix of sorted labels for training set N1xN2
:param k: number of nearest neighbours
:return: matrix of probabilities for objects X
"""
N1, N2 = y.shape
M = len(np.unique(y))
p_y_x = np.zeros(shape=(N1, M))
for i in range(1,N1):
for j in range(1,M):
p_y_x[i, j] = (1/k)*(np.sum(y[i,0:k] == j+1))
return p_y_x
我不能粘貼回溯,因爲這個功能僅僅是一個更大的項目的一部分,我得到的唯一輸出是「不及格」,甚至不是「錯誤」按往常一樣,在那裏我可以看到什麼不工作。與已經提供的其他東西一樣,排序標籤的矩陣是正確的。也許你們有些人可以在我的推理中看到任何明顯的錯誤?
編輯: 改變的代碼:
N1, N2 = y.shape
M = len(np.unique(y))
p_y_x = np.zeros((N1, M))
for i in range(N1):
for j in range(M):
p_y_x[i, j] = (1.0/k)*(np.sum(y[i,0:k-1] == j))
return p_y_x
我改變範圍和k作爲@StackPlayer建議,並且我失去了 'J + 1',因爲我相信,一個不應被遞增。我仍然沒有得到任何錯誤,只是一個'失敗'。
謝謝,我糊塗了所有的索引...好了,0:K-1,然後我改變了對範圍(0,N1 + 1)和(0,M + 1),是那對嗎?希望如此。現在雖然我得到的是一個錯誤而不是失敗,但「IndexError:index 4超出了大小爲4的軸1的邊界」,並且改變了k的行。 – Swaglina
我最好的猜測就是使用範圍(N1),祝你好運! –
好的,明白了!現在至少回到'失敗',哈哈。非常感謝你,我會盡我所能! :) – Swaglina