所以我在MATLAB中编写了一个k-means脚本,因为本机函数看起来效率不高,而且似乎完全可以运行。它似乎适用于我正在使用的小型训练集(通过文本文件提供的150x2矩阵)。但是,对于我的目标数据集,运行时间呈指数增长,这是一个3924x19矩阵。
我不是最好的矢量化,所以任何建议都会非常感激。到目前为止这是我的k-means脚本(我知道我将不得不调整我的收敛条件,因为它正在寻找完全匹配,我可能需要更大的数据集迭代,但我想要它能够在一个合理的时间内完成,然后我开始说出这个数字):
clear all;
%take input file (manually specified by user
disp('Please type input filename (in working directory): ')
target_file = input('filename: ', 's');
%parse and load into matrix
data = load(target_file);
%prompt name of output file for later) UNCOMMENT BELOW TWO LINES LATER
% disp('Please type output filename (to be saved in working directory): ')
% output_name = input('filename:', 's')
%prompt number of clusters
disp('Please type desired number of clusters: ')
c = input ('number of clusters: ');
%specify type of kmeans algorithm ('regular' for regular, 'fuzzy' for fuzzy)
%UNCOMMENT BELOW TWO LINES LATER
% disp('Please specify type (regular or fuzzy):')
% runtype = input('type: ', 's')
%initialize cluster centroid locations within bounds given by data set
%initialize rangemax and rangemin row vectors
%with length same as number of dimensions
rangemax = zeros(1,size(data,2));
rangemin = zeros(1,size(data,2));
%map max and min values for bounds
for dim = 1:size(data,2)
rangemax(dim) = max(data(:,dim));
rangemin(dim) = min(data(:,dim));
end
% rangemax
% rangemin
%randomly initialize mu_k (center) locations in (k x n) matrix where k is
%cluster number and n is number of dimensions/coordinates
mu_k = zeros(c,size(data,2));
for k = 1:size(data,2)
mu_k(k,:) = rangemin + (rangemax - rangemin).*rand(1,1);
end
mu_k
%iterate k-means
%initialize holding variable for distance comparison
comparisonmatrix = [];
%initialize assignment vector
assignment = zeros(size(data,1),1);
%initialize distance holding vector
dist = zeros(1,size(data,2));
%specify convergence threshold
%threshold = 0.001;
for iteration = 1:25
%save current assignment values to check convergence condition
hold_assignment = assignment;
for point = 1:size(data,1)
%calculate distances from point to centers
for k = 1:c
%holding variables
comparisonmatrix = [data(point,:);mu_k(k,:)];
dist(k) = pdist(comparisonmatrix);
end
%record location of mininum distance (location value will be between 1
%and k)
[minval, location] = min(dist);
%assign cluster number (analogous to location value)
assignment(point) = location;
end
%check convergence criteria
if isequal(assignment,hold_assignment)
break
end
%revise mu_k locations
%count number of each label
assignment_count = zeros(1,c);
for i = 1:size(data,1)
assignment_count(assignment(i)) = assignment_count(assignment(i)) + 1;
end
%compute centroids
point_total = zeros(size(mu_k));
for row = 1:size(data,1)
point_total(assignment(row),:) = point_total(assignment(row)) + data(row,:);
end
%move mu_k values to centroids
for center = 1:c
mu_k(center,:) = point_total(center,:)/assignment_count(center);
end
end
那里有很多循环,所以我觉得有很多优化要做。但是,我想我已经盯着这段代码太久了,所以一些新鲜的眼睛可以帮助。如果我需要澄清代码块中的任何内容,请告诉我。
当在大型数据集上执行上述代码块(在上下文中)时,根据MATLAB的分析器,需要3732.152秒进行完整的25次迭代(我假设它没有根据我的“收敛” 150个集群的标准,但其中大约130个返回NaNs(mu_k中130行)。
答案 0 :(得分:4)
分析将有所帮助,但重新编写代码的地方是避免循环数据点(for point = 1:size(data,1)
)。矢量化。
在for iteration
循环中,这是一个快速的部分示例,
[nPoints,nDims] = size(data);
% Calculate all high-dimensional distances at once
kdiffs = bsxfun(@minus,data,permute(mu_k,[3 2 1])); % NxDx1 - 1xDxK => NxDxK
distances = sum(kdiffs.^2,2); % no need to do sqrt
distances = squeeze(distances); % Nx1xK => NxK
% Find closest cluster center for each point
[~,ik] = min(distances,[],2); % Nx1
% Calculate the new cluster centers (mean the data)
mu_k_new = zeros(c,nDims);
for i=1:c,
indk = ik==i;
clustersizes(i) = nnz(indk);
mu_k_new(i,:) = mean(data(indk,:))';
end
这不是唯一(或最好)的方式,但它应该是一个不错的例子。
其他一些评论:
input
,而是将此脚本转换为有效处理输入参数的函数。uigetfile
。max
,min
,sum
,mean
等,您可以指定函数应该运行的维度。这样,您可以在矩阵上运行它并同时计算多个条件/维度的值。ik
与欧几里德距离的平方值相同。