5 from sklearn.cluster import AffinityPropagation
8 def affinity_clustering(similarities, output, damping=0.9, max_iter=100000, convergence_iter=30, preference_quantile=0.5, random_state=1968, verbose=True):
10 similarities: feather file with a dataframe of similarity scores
11 preference_quantile: parameter controlling how many clusters to make. higher values = more clusters. 0.85 is a good value with 3000 subreddits.
12 damping: parameter controlling how iterations are merged. Higher values make convergence faster and more dependable. 0.85 is a good value for the 10000 subreddits by author.
15 df = pd.read_feather(similarities)
17 mat = np.array(df.drop('_subreddit',1))
18 mat[range(n),range(n)] = 1
19 assert(all(np.diag(mat)==1))
21 preference = np.quantile(mat,preference_quantile)
23 print(f"preference is {preference}")
27 clustering = AffinityPropagation(damping=damping,
29 convergence_iter=convergence_iter,
31 preference=preference,
32 affinity='precomputed',
34 random_state=random_state).fit(mat)
37 print(f"clustering took {clustering.n_iter_} iterations")
38 clusters = clustering.labels_
40 print(f"found {len(set(clusters))} clusters")
42 cluster_data = pd.DataFrame({'subreddit': df.subreddit,'cluster':clustering.labels_})
44 cluster_sizes = cluster_data.groupby("cluster").count()
45 print(f"the largest cluster has {cluster_sizes.subreddit.max()} members")
47 print(f"the median cluster has {cluster_sizes.subreddit.median()} members")
49 print(f"{(cluster_sizes.subreddit==1).sum()} clusters have 1 member")
51 cluster_data.to_feather(output)
53 if __name__ == "__main__":
54 fire.Fire(affinity_clustering)