matlab for循环出现问题,最近质心仅显示在第一个定型示例中

wlp8pajw  于 2022-11-30  发布在  Matlab
关注(0)|答案(1)|浏览(117)

我目前正在做一个机器学习课程,我的代码有一个小问题。我正在创建一个函数,它将返回最接近训练示例X的聚类质心的索引,其中initial_centroids = [3 3; X1 -3 = [1.8421,4.6076; 5.6586,4.8; 6.3526,3.2909]
我的想法是做一个for循环,计算X1和质心1/2/3之间的距离,然后选择最小的一个,返回最小的索引。
调用函数时,我的答案(已提供)应为[1 3 2]。
我收到的是[1 0 0]。
我相信我的for循环有一个错误,因为idx之前被设置为0的向量,而现在只有第一个0被改为1。
我似乎找不到错误,我是编程新手,我不想看这些练习的现成解决方案,所以我希望有人至少能指导我正确的方向,不需要直接的解决方案。

function idx = findClosestCentroids(X, centroids)
%FINDCLOSESTCENTROIDS computes the centroid memberships for every example
%   idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids
%   in idx for a dataset X where each row is a single example. idx = m x 1 
%   vector of centroid assignments (i.e. each entry in range [1..K])
%

% Set K
K = size(centroids, 1);
tempidx = zeros(1,2);

% You need to return the following variables correctly.
idx = zeros(size(X,1), 1);
for i = 1:X;
    C = [(X(i,:)-centroids(1,:)).^2;(X(i,:)-centroids(2,:)).^2;(X(i,:)-centroids(3,:)).^2];
    Ctot = sum(C(i),2);
    [res,dx] = min(Ctot);
    idx(i,:) = dx;
end;
% ====================== YOUR CODE HERE ======================
% Instructions: Go over every example, find its closest centroid, and store
%               the index inside idx at the appropriate location.
%               Concretely, idx(i) should contain the index of the centroid
%               closest to example i. Hence, it should be a value in the 
%               range 1..K
%
% Note: You can use a for-loop over the examples to compute this.
%


The lines that call function and return [1 0 0] (should be [1 3 2] are:
idx = findClosestCentroids(X, initial_centroids);
fprintf('Closest centroids for the first 3 examples: %d %d %d', idx(1:3))

我试图改变的是:

for i = 1:X;
    C = [(X(i,:)-centroids(1,:)).^2;(X(i,:)-centroids(2,:)).^2;(X(i,:)-centroids(3,:)).^2];
    Ctot(i) = sum(C(i),2);
    [res,dx] = min(Ctot(i));
    idx(i,:) = dx(i);
end;

还是不工作,返回[100]....
我想也许我指的不是迭代。

wixjitnu

wixjitnu1#

我自己找到了答案。(非常自豪)
正要注销.这时我看到我的for循环已经建立:对于i = 1:X。
这将导致循环在1处停止,修复程序正在设置for循环:
对于i = 1:大小(X,1)
我的工作方案:

idx = zeros(size(X,1), 1);
for i = 1:size(X,1);
C = [(X(i,:)-centroids(1,:)).^2;(X(i,:)-centroids(2,:)).^2;(X(i,:)-centroids(3,:)).^2];

Ctot = sum(C,2);

[res,dx] = min(Ctot);

idx(i,:) = dx;
end;

相关问题