K原型聚类手肘法绘图时plotnine报Cluster未定义错误如何解决
报错原因
- 你执行
df_cost.transpose()时没有将转置后的结果赋值回df_cost变量,原df_cost的行索引为Cluster、Cost,列索引为数字,不存在名为Cluster和Cost的列,plotnine读取映射字段时找不到对应列就触发了报错。 - 你定义字典
a时硬编码了range(1, 6),但前面的K原型聚类循环遇到异常就会终止,cost列表的长度不一定是5,还可能出现字段长度不匹配的潜在问题。
解决方法
修改数据框构造部分的代码即可,修正后的完整对应代码段如下:
# Converting the results into a dataframe and plotting them # 动态匹配cost长度,直接按列生成数据框,不需要多余的转置操作 a = {'Cluster':range(1, len(cost)+1), 'Cost':cost} df_cost = pd.DataFrame(a) # Data viz plotnine.options.figure_size = (8, 4.8) ( ggplot(data = df_cost)+ geom_line(aes(x = 'Cluster', y = 'Cost'))+ geom_point(aes(x = 'Cluster', y = 'Cost'))+ geom_label(aes(x = 'Cluster', y = 'Cost', label = 'Cluster'), size = 10, nudge_y = 1000) + labs(title = 'Optimal number of cluster with Elbow Method')+ xlab('Number of Clusters k')+ ylab('Cost')+ theme_minimal() )
内容的提问来源于stack exchange,提问作者Ahmed JAÏEM
相关产品推荐
相关产品推荐

