这是我去年在Matlab中为k近邻概率分布编写的代码:
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我无法粘贴回溯,因为这个函数只是一个更大项目的一部分,我得到的唯一输出是“失败”,而不是像往常一样的“错误”,在那里我可以看到什么不起作用。排序标签的y矩阵是正确的,就像已经提供的其他所有内容一样。也许你们中的一些人能看出我的推理中有什么明显的错误?
编辑:更改代码:
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正如@StackPlayer建议的那样,我更改了范围和k,并且我失去了'j+1‘,因为我相信不应该增加这个值。我还是没有得到任何错误,只是‘失败’。
发布于 2017-04-14 20:58:36
您可能需要将0:k调整为0:k-1,对于for循环也是一样的,请按照它的方式使用范围(不要尝试在Python的0索引上强制MATLAB 1索引!)
发布于 2017-04-14 21:05:17
堆栈播放器说得对。我对这个答案的补充是在这个函数中使用python3,或者将(1/k)更改为(1.0/k),并使用python2.*,因为在python2 (1/k)中,k是整数,返回整数0,所有元素都是零。
好的,在Python上用这段代码进行测试,你的Matlab代码给了我相同的结果。
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((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] == j+1))
return p_y_xhttps://stackoverflow.com/questions/43419077
复制相似问题