聚类化
聚类(或聚类分析)是将一组对象划分为称为聚类的组的任务。 每个组内部应该有"相似"的对象,来自不同组的对象应该尽可能不同。 聚类和分类之间的主要区别在于组列表没有指定,并且在算法的操作过程中确定。
本示例将演示如何使用K均值方法和模糊聚类方法(C均值)执行聚类。
连接必要的库:
Pkg.add(["RDatasets", "Clustering"])
using Plots
using Clustering
上传数据集以进行聚类分析:
using RDatasets
iris = dataset("datasets", "iris");
从一个数据集到一个单独的变量中确定观察对象的特征:
iris_species = iris[:,5];
源数据在三维图形上的可视化:
plotlyjs()
setosaIndex = findall(x->x=="setosa", iris_species)
versicolorIndex = findall(x->x=="versicolor", iris_species)
virginicaIndex = findall(x->x=="virginica", iris_species)
scatter(Matrix(iris[setosaIndex, [:SepalLength]]), Matrix(iris[setosaIndex, [:SepalWidth]]), Matrix(iris[setosaIndex, [:PetalLength]]), color="red")
scatter!(Matrix(iris[versicolorIndex, [:SepalLength]]), Matrix(iris[versicolorIndex, [:SepalWidth]]), Matrix(iris[versicolorIndex, [:PetalLength]]), color="blue")
scatter!(Matrix(iris[virginicaIndex, [:SepalLength]]), Matrix(iris[virginicaIndex, [:SepalWidth]]), Matrix(iris[virginicaIndex, [:PetalLength]]), color="green")
转换为二维图,用于聚类结果与初始数据的进一步比较:
gr()
s1 = scatter(Matrix(iris[setosaIndex, [:SepalLength]]), Matrix(iris[setosaIndex, [:SepalWidth]]), color="red", markersize = 5, label="setosa")
s2 = scatter!(Matrix(iris[versicolorIndex, [:SepalLength]]), Matrix(iris[versicolorIndex, [:SepalWidth]]), color="blue", markersize = 5, label="versicolor")
s3 = scatter!(Matrix(iris[virginicaIndex, [:SepalLength]]), Matrix(iris[virginicaIndex, [:SepalWidth]]), color="green", markersize = 5, label="virginica")
p1 = plot(s3)
以可接受的格式准备数据,以便通过聚类方法进行处理:
features = collect(Matrix(iris[:, 1:4])')
K-means方法
最流行的聚类方法之一是K-means方法。 该方法的主要思想是两个步骤的迭代重复。:
- 按群集分布样本对象;
- 集群中心的重新计算。
将聚类方法应用于源数据:
result_kmeans = kmeans(features, 3); #метод kmeans() принимает как аргументы набор данных и количество кластеров
使用点图可视化解决方案:
plotlyjs()
p2 = scatter(iris.SepalLength, iris.SepalWidth,
marker_z = result_kmeans.assignments,
color =:red, legend = false, markersize = 5)
包含结果的变量(result_kmeans)中的assignments参数包含一列,其中为每个观测值分配了群集编号。 图形上点的颜色对应于特定聚类的数量。
K-means算法结果与初始数据的比较:
plot(p1, p2)
这些图表显示了算法的令人满意的结果,观察结果被分成足够接近原始数据的簇。
模糊优化方法
模糊聚类方法可以被认为是改进的k-means方法,其中对于来自所考虑的集合的每个元素,计算其属于每个聚类的程度。
将聚类方法应用于源数据:
result_fuzzy = fuzzy_cmeans(features, 3, 2, maxiter=2000, display=:iter)
基于观测对象的四个特征计算三个聚类的中心:
M = result_fuzzy.centers
计算观测对象的权重(属于特定集群的程度):
memberships = result_fuzzy.weights
从0到1的数字表示与群集中心的接近程度,其中1是最大隶属关系(位于中心),0是与中心的最大距离。
模糊逻辑方法结果的可视化:
p3 = scatter(iris.SepalLength, iris.SepalWidth,
marker_z = memberships[:,1],
legend = true, markersize = 5)
p4 = scatter(iris.SepalLength, iris.SepalWidth,
marker_z = memberships[:,3],
legend = false, markersize = 5)
p5 = scatter(iris.SepalLength, iris.SepalWidth,
marker_z = memberships[:,2],
legend = false, markersize = 5)
plot(p3, p4, p5, p1, legend = false)
前三个图显示了模糊逻辑方法的结果,其中色标显示了属于特定聚类的程度。
最后一个图表显示了初始(可靠)数据。
通过首先将鼠标光标悬停在具有初始数据的图形上,然后在具有使用该方法获得的点的图形上,可以比较结果并直观地评估该方法的准确性。
结论:
在这个例子中,考虑了两种最常用的聚类方法。 用于实现这些方法的函数是从聚类库中调用的。jl,它还提供了许多其他更先进的方法。
在应用过程中得到的结果很好,但并不理想,需要更多的数据来提高算法的质量。
