我最近被介绍了聚类技术,因为我的任务是根据他们必须回答的调查来找到我大学教授的“概况”或“模式”。我一直在研究执行此操作的一些可用选项,并且遇到了 k-means 聚类算法。由于我的大部分数据都是分类的,我必须执行一次热编码(将分类变量转换为 0-1 单列向量),然后我在 Excel 上进行了相关分析,以排除一些冗余变量。在此之后,我将 python 与 pandas、numpy、matplotlib 和 sklearn 库一起使用来执行最佳簇数检查(肘部方法),然后最后运行 k-means。
这是我用来导入带有教授调查数据的 .csv 并运行肘部方法的代码:
# loads the .csv dataframe (DF)
df = pd.read_csv('./dados_selecionados.csv', sep=",")
# prints the df
print(df)
#list for the sum of squared distances
SQD = []
#cluster number for testing in elbow method
num_clusters = 10
# runs k-means for each cluster number
for k in range(1,num_clusters+1):
kmeans = KMeans(n_clusters=k)
kmeans.fit(df)
SQD.append(kmeans.inertia_)
# sets up the plot and show it
plt.figure(figsize=(16, 8))
plt.plot(range(1, num_clusters+1), SQD, 'bx-')
plt.xlabel('Número de clusters')
plt.ylabel('Soma dos quadrados das distâncias de cada ponto ao centro de seu cluster')
plt.title('Método do cotovelo')
plt.show()
根据该图,我决定使用 3 个集群。之后,我为 3 个集群运行 k-means,并使用以下代码将集群数据发送到 .xlsx:
# runs k-means
kmeans = KMeans(n_clusters=3, max_iter=100,verbose=2)
kmeans.fit(df)
clusters = kmeans.fit_predict(df)
# dict to store clusters data
cluster_dict=[]
for c in clusters:
cluster_dict.append(c)
# prints the cluster dict
cluster_dict
# adds the cluster information as a column in the df
df['cluster'] = cluster_dict
# saves the df as a .xlsx
df.to_excel("3_clusters_k_means_selecionado.xlsx")
# shows the resulting df
print(df)
# shows each separate cluster
for c in clusters:
print(df[df['cluster'] == c].head(10))
我的主要疑问是如何对每个集群数据进行合理的分析以了解它们是如何创建的?我开始在每个变量上使用均值,并在 Excel 上使用条件格式来查看是否会出现某些模式并且它们实际上确实出现了,但我认为这不是最好的选择。
而且我还将使用这篇文章来询问有关整个方法的任何建议。也许我采取的一些步骤不是最好的。
