- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
这是我去年写的一个概率分布代码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/
我从 SpatialPolygonsDataFrame 开始,它包含用于创建加纳各地区 map 的数据(可在 http://www.diva-gis.org/datadown 获取)。我正在尝试创建一
我遇到了一个问题,我需要根据存储在前一个元素中的信息修改容器的元素。示例: 如果前一个 vector 元素可被 2 整除,则将当前元素乘以 10 vector -> [12, 11, 33, 10]
总的来说,我对脚本编写还很陌生。我正在编写一个 expect 脚本,它通过 ssh 进入 Cisco 交换机,并运行“show cdp neighbors”命令来获取连接到交换机的所有设备的列表。然后
我正在尝试比较节点的值。使用 flood-fill 算法,我能够垂直和水平检查网格的每个节点。现在我必须更新我的代码以检查位于对 Angular 线上的单元格,如下图所示: 红色是当前节点,黄色是需要
我使用预先计算的指标使用 Scikit-Learn 的最近邻/半径分类。这意味着,我将成对距离的 n_samples_train x n_samples_train 矩阵传递给分类器的拟合方法。 现在
我有一个大的稀疏图,我将其表示为邻接矩阵(100k x 100k 或更大),存储为边数组。具有(非稀疏)4 x 4 矩阵的示例: 0 7 4 0 example_array = [ [7,1,2],
从有向图中并给出两个顶点 (v, u) 我需要找到:共同的“出”邻居和共同的“入”邻居。 例如: import networkx as nx ghybrid = nx.DiGraph() ghybri
我正在使用 JavaScript 进行图像处理,我想知道是否有任何通用公式可以确定像素的 x 邻居。 我知道对于 3*3 的正方形,可以使用特定的 x 和 y 像素确定 8 个邻居。 (x-1,y-1
在 CentOS 6.4(内核 2.6.32)上,为什么下面的第二个 arping 调用会创建一个新的 ARP 表条目,而第一个不会?网络行为是相同的,我感到困惑的是,在我看来,系统调用实际上是等同的
我是一名优秀的程序员,十分优秀!