In[12]:defcalculate_distance(centroid,player_value):
root_distance=0
forxinrange(0,len(centroid)):
difference=centroid[x]-player_value[x]
squared_difference=difference**2
root_distance+=squared_difference
euclid_distance=(root_distance)
returneuclid_distance
定义函数用来计算每个点到中心的距离,并把它分配到距离最近的中心所在的那个簇。
In[13]:defassign_to_cluster(row):
player=[row['ppg'],row['atr']]
lowest_dist=-1
clus_id=-1
forclu_id,centroidincentroids_dict.items():
distance=calculate_distance(centroid,player)
iflowest_dist==-1:
lowest_dist=distance
clus_id=clu_id
elifdistance0:
centroids_dict=centroids_dict_new
nba['cluster']=(assign_to_cluster,axis=1)
centroids_dict_new=recalculate_centroids(nba)
centr_change=centroids_change(centroids_dict,
centroids_dict_new)
In[27]:visualize_clusters(nba,cluster_num)
图5-7
上述过程完整地实现了k-平均聚类的算法。前面已经提到过这种聚类方法的结果与初始中心的选取有关,只进行一次这样的聚类,聚类结果会有一定的偏差。Python的sklearn库针对简单的k-平均聚类做了优化。例如,通过多次选取初始中心,参考多次聚类的结果输出最终的聚类结果,从而改善聚类效果。通过调用sklearn库来实现k-平均聚类只需要设置聚类的个数,数行代码就可以完成聚类工作。代码和相应的输出结果如图5-8所示。
In[1]:
In[2]:importpandasaspd
In[3]:
In[4]:defvisualize_clusters(df,cluster_num):
colors=['b','g','r','c','m','y','k']
foriinrange(cluster_num):
clustered_df=df[df['cluster']==i]
(clustered_df['ppg'],clustered_df
['atr'],c=colors[i])
('PointsPerGame',fontsize=12)
('AssistTurnoverRatio',fontsize=12)
()
In[5]:cluster_num=5