AP聚类Matlab程序

function [idx a r output] = affprop(s, options)
m = size(s,1);

defaultopt = struct( 'MaxIter', 200,...
                     'StallIter', 20, ...
                     'FunValCheck','off', ...
                     'Dampening', .5, ...
                     'OutputFcn',[]);

if nargin < 2
    options = [];
end;

maxiter   = optimget(options,'MaxIter',   defaultopt,'fast');
stalliter = optimget(options,'StallIter', defaultopt,'fast');
lambda    = optimget(options,'Dampening', defaultopt,'fast');
outputfcn = optimget(options,'OutputFcn', defaultopt,'fast');

if isempty(outputfcn)
    haveoutputfcn = false;
else
    haveoutputfcn = true;
end


% useful indices
ri = (1:m)';
di = 1:(m+1):m*m;         %index to diagonal elements

% initialize responsibility matrix
r = zeros(m);

% availability matrix,a, evidence from other datapoints how an exemplar
% point i will make
a      = zeros(m);
a_prev = zeros(m);

%initialize exemplar vector
idx_prev = ri;

iter = 1;
converged = false;
ccount = 0;

while ~converged
    %% Part I. Update or initialize r, the responsibility matrix
    % update (or initialize) r, the responsibility matrix, such that element
    % r(i,j) indicates how good an exemple point x(j,:) would make for
    % point x(i,:)

    %  given as = a + s,
    %  set d(i,j) = max( as(i,k) ), for k not equal to j
    as = a + s;

    %rmax is the row maximum for all elements
    [rmax k] = max(as,[],2);
    kp = sub2ind( [m m], ri, k );

    %rmax2 is the row maximum for when j=k would be the row maximum
    as(kp) = nan;
    rmax2  = max(as,[],2);

    d = repmat( rmax, 1, m );
    d(kp) = rmax2;

    %     r = s - d;                                                 %eq(1)
    r = lambda*r + (1-lambda)*(s-d);       % dampended


    %% Part II. Update the availability matrix [ eq2 and eq3 ]
    %  The availability matrix is evidence that point k is an exemplar based on
    %  positive responsibiliities sent to it from the other points
    % a(i,j) = min[ 0, r(j,j) + sum( max(0, r(k,j) ) ],
    % for all k not in (i,j)

    % calculate c = max(r,0)
    c = r;
    c(c<0) = 0;     % only consider positive elements

    % calculate the sum( max(0, r(k,j) ), where k not in (i,j) this is done
    % by setting c(j,j) to zero. Then sum the columns and form a new
    % matrix,cs, by replication. Finally, subtracting c(i,j) gives
    % the desired matrix, c (reuse storage)
    c(di) = 0;                   % set diagonal elements to zero
    cs = repmat(sum(c),m,1);     % sum columns
    c = cs - c;

    %     a = min(0, repmat( diag(r)', m, 1) + c );                   %eq(2)
    %     a(di) = cs(di);                                             %eq(3)
    %
    a = lambda*a_prev + (1-lambda)*(min(0, repmat( diag(r)', m, 1) + c ));
    a(di) = lambda*a_prev(di) + (1-lambda)*cs(di);

    a_prev = a;

    if haveoutputfcn
        outputfcn(a,r);
    end

    iter = iter+1;
    if iter > maxiter
        converged = true;
    end

    [rmax idx] = max( a+r,[],2);
    if isequal(idx,idx_prev)
        ccount = ccount + 1;
        if ccount == stalliter
            converged = true;
        end
    else
        idx_prev = idx;
        ccount = 0;
    end




end

output.iter      = iter;
output.stalliter = ccount;
M = [5 0; 0 5; 10 10];
idx = repmat( 1:3, 50, 1 );
x = M(idx(:),:) + randn(150,2);

% generate similarity matrix
m     = size(x,1);
s     = zeros(m);

o     = nchoosek(1:150,2);      % set up all possible pairwise comparisons 
xx    = x(o(:,1),:)';           % point 1
xy    = x(o(:,2),:)';           % point 2
d2    = (xx - xy).^2;           % distance squared
d     = -sqrt(sum(d2));          % distance

k     = sub2ind([m m], o(:,1), o(:,2) );    % prepare to make square 
s(k)  = d;             
s     = s + s';
di = 1:(m+1):m*m;         %index to diagonal elements

s(di) = min(d);

%% clustering
options.StallIter = 10;
options.OutputFcn = @(a,r) affprop_plot(a,r,x,'k.');

figure
ex       = affprop(s, options );


function affprop_plot( a, r, x, cc )
%AFFPROP_PLOT throw away function to illustrate affinity propagation
% 
%Example
%   for example see
%See also affprop_demo, affprop

if nargin < 4
    cc = '.';
end

m = size(x,1);
subplot(2,2,1);
cla
plot(x(:,1),x(:,2), cc, 'markersize', 3 );

[rmax k] = max( a+r,[],2);


% color examplars
i = (1:m)';
hold on;
plot(x(i==k,1),x(i==k,2), 'r.', 'markersize', 7 );

j = i~=k;

% quiver( x(j,1),              x(j,2), ...
%         x(k(j),1) - x(j,1),  x(k(j),2) - x(j,2), ...
%         0 );

quiver( x(j,1),              x(j,2), ...
    x(k(j),1) - x(j,1),  x(k(j),2) - x(j,2), ...
    0, '.' );

subplot(2,2,2)
colormap(copper)
imagesc(a);
title('availability')

subplot(2,2,3);
colormap(copper)
imagesc(r);
title('responsibility')

subplot(2,2,4);
colormap(copper)
imagesc(a+r);
title('availability+responsibility');
pause(0.1);
drawnow
  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
AP聚类(Affinity Propagation clustering)是一种聚类算法,用于将数据集分为不同的簇。在MATLAB中,可以使用Statistics and Machine Learning Toolbox中的`apcluster`函数来实现AP聚类。 以下是使用MATLAB进行AP聚类的基本步骤: 1. 准备数据:将待聚类的数据组织成一个矩阵,每一行表示一个样本,每一列表示一个特征。 2. 导入Statistics and Machine Learning Toolbox:确保已经导入Statistics and Machine Learning Toolbox,可以使用`apcluster`函数。 3. 设置参数:根据需要,可以设置一些参数来控制AP聚类的行为,例如阈值、最大迭代次数等。 4. 执行AP聚类:使用`apcluster`函数执行AP聚类,将数据矩阵作为输入,并将返回的结果保存在一个变量中。 下面是一个简单的示例代码: ```matlab % 准备数据 data = [1, 2; 2, 3; 3, 3; 8, 7; 8, 8; 9, 6]; % 导入Statistics and Machine Learning Toolbox % 设置参数 preferences = median(pdist(data))^2; % 设置相似度阈值为数据间距离的中位数的平方 % 执行AP聚类 [idx, ~] = apcluster(data, 'preference', preferences); % 输出聚类结果 disp(idx); ``` 在上面的示例中,我们首先准备了一个包含6个样本的数据矩阵。然后根据数据的特点,设置了相似度阈值为数据间距离的中位数的平方。最后,使用`apcluster`函数执行AP聚类,并将聚类结果存储在变量`idx`中。最后输出了聚类结果。 请注意,AP聚类算法的结果可能会有多种不同的簇划分,因此每次运行该算法可能得到不同的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值