3 from sklearn.cluster import AffinityPropagation
6 def affinity_clustering(similarities, output, damping=0.5, max_iter=100000, convergence_iter=30, preference_quantile=0.5, random_state=1968):
8 similarities: feather file with a dataframe of similarity scores
9 preference_quantile: parameter controlling how many clusters to make. higher values = more clusters. 0.85 is a good value with 3000 subreddits.
12 df = pd.read_feather(similarities)
14 mat = np.array(df.drop('subreddit',1))
15 mat[range(n),range(n)] = 1
17 preference = np.quantile(mat,preference_quantile)
21 clustering = AffinityPropagation(damping=damping,
23 convergence_iter=convergence_iter,
25 preference=preference,
26 affinity='precomputed',
27 random_state=random_state).fit(mat)
30 print(f"clustering took {clustering.n_iter_} iterations")
31 clusters = clustering.labels_
33 print(f"found {len(set(clusters))} clusters")
35 cluster_data = pd.DataFrame({'subreddit': df.subreddit,'cluster':clustering.labels_})
37 cluster_sizes = cluster_data.groupby("cluster").count()
38 print(f"the largest cluster has {cluster_sizes.subreddit.max()} members")
40 print(f"the median cluster has {cluster_sizes.subreddit.median()} members")
42 print(f"{(cluster_sizes.subreddit==1).sum()} clusters have 1 member")
44 cluster_data.to_feather(output)
46 if __name__ == "__main__":
47 fire.Fire(affinity_clustering)