正如其他人所提到的,层次聚类需要计算成对距离矩阵,该矩阵太大而无法在您的情况下放入内存中。
尝试改用 K-Means 算法:
numClusters = 4;
T = kmeans(X, numClusters);
或者,您可以选择数据的随机子集并用作聚类算法的输入。接下来,您将集群中心计算为每个集群组的平均值/中位数。最后,对于未在子集中选择的每个实例,您只需计算其到每个质心的距离并将其分配给最近的一个。
这是一个示例代码来说明上述想法:
%# random data
X = rand(25000, 2);
%# pick a subset
SUBSET_SIZE = 1000; %# subset size
ind = randperm(size(X,1));
data = X(ind(1:SUBSET_SIZE), :);
%# cluster the subset data
D = pdist(data, 'euclid');
T = linkage(D, 'ward');
CUTOFF = 0.6*max(T(:,3)); %# CUTOFF = 5;
C = cluster(T, 'criterion','distance', 'cutoff',CUTOFF);
K = length( unique(C) ); %# number of clusters found
%# visualize the hierarchy of clusters
figure(1)
h = dendrogram(T, 0, 'colorthreshold',CUTOFF);
set(h, 'LineWidth',2)
set(gca, 'XTickLabel',[], 'XTick',[])
%# plot the subset data colored by clusters
figure(2)
subplot(121), gscatter(data(:,1), data(:,2), C), axis tight
%# compute cluster centers
centers = zeros(K, size(data,2));
for i=1:size(data,2)
centers(:,i) = accumarray(C, data(:,i), [], @mean);
end
%# calculate distance of each instance to all cluster centers
D = zeros(size(X,1), K);
for k=1:K
D(:,k) = sum( bsxfun(@minus, X, centers(k,:)).^2, 2);
end
%# assign each instance to the closest cluster
[~,clustIDX] = min(D, [], 2);
%#clustIDX( ind(1:SUBSET_SIZE) ) = C;
%# plot the entire data colored by clusters
subplot(122), gscatter(X(:,1), X(:,2), clustIDX), axis tight