gpt4 book ai didi

python - K-NN 邻居从 Matlab 到 Python

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:22 25 4
gpt4 key购买 nike

这是我去年写的一个概率分布代码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

我不能粘贴回溯,因为这个函数只是一个更大项目的一部分,我得到的唯一输出是“FAIL”,甚至不是像往常一样的“ERROR”,在那里我可以看到什么不是在职的。排序标签的 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”,因为我相信,那个不应该递增。我仍然没有收到任何错误,只是“失败”。

最佳答案

您可能需要将 0:k 调整为 0:k-1和 for 循环一样,按原样使用范围(不要尝试将 MATLAB 1 索引强制执行到 Python 的 0 索引!)

关于python - K-NN 邻居从 Matlab 到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43419077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com