]> code.communitydata.science - cdsc_reddit.git/blob - clustering/clustering.py
Refactor and reorganze.
[cdsc_reddit.git] / clustering / clustering.py
1 import pandas as pd
2 import numpy as np
3 from sklearn.cluster import AffinityPropagation
4 import fire
5
6 def affinity_clustering(similarities, output, damping=0.5, max_iter=100000, convergence_iter=30, preference_quantile=0.5, random_state=1968):
7     '''
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.
10     '''
11
12     df = pd.read_feather(similarities)
13     n = df.shape[0]
14     mat = np.array(df.drop('subreddit',1))
15     mat[range(n),range(n)] = 1
16
17     preference = np.quantile(mat,preference_quantile)
18
19     print("data loaded")
20
21     clustering = AffinityPropagation(damping=damping,
22                                      max_iter=max_iter,
23                                      convergence_iter=convergence_iter,
24                                      copy=False,
25                                      preference=preference,
26                                      affinity='precomputed',
27                                      random_state=random_state).fit(mat)
28
29
30     print(f"clustering took {clustering.n_iter_} iterations")
31     clusters = clustering.labels_
32
33     print(f"found {len(set(clusters))} clusters")
34
35     cluster_data = pd.DataFrame({'subreddit': df.subreddit,'cluster':clustering.labels_})
36
37     cluster_sizes = cluster_data.groupby("cluster").count()
38     print(f"the largest cluster has {cluster_sizes.subreddit.max()} members")
39
40     print(f"the median cluster has {cluster_sizes.subreddit.median()} members")
41
42     print(f"{(cluster_sizes.subreddit==1).sum()} clusters have 1 member")
43
44     cluster_data.to_feather(output)
45
46 if __name__ == "__main__":
47     fire.Fire(affinity_clustering)

Community Data Science Collective || Want to submit a patch?