]> code.communitydata.science - cdsc_reddit.git/blob - similarities/weekly_cosine_similarities.py
bug fix in affinity clustering
[cdsc_reddit.git] / similarities / weekly_cosine_similarities.py
1 from pyspark.sql import functions as f
2 from pyspark.sql import SparkSession
3 from pyspark.sql import Window
4 import numpy as np
5 import pyarrow
6 import pyarrow.dataset as ds
7 import pandas as pd
8 import fire
9 from itertools import islice, chain
10 from pathlib import Path
11 from similarities_helper import *
12 from multiprocessing import Pool, cpu_count
13 from functools import partial
14
15
16 def _week_similarities(week, simfunc, tfidf_path, term_colname, min_df, max_df, included_subreddits, topN, outdir:Path):
17     term = term_colname
18     term_id = term + '_id'
19     term_id_new = term + '_id_new'
20     print(f"loading matrix: {week}")
21     entries, subreddit_names = reindex_tfidf(infile = tfidf_path,
22                                              term_colname=term_colname,
23                                              min_df=min_df,
24                                              max_df=max_df,
25                                              included_subreddits=included_subreddits,
26                                              topN=topN,
27                                              week=week)
28     mat = csr_matrix((entries[tfidf_colname],(entries[term_id_new], entries.subreddit_id_new)))
29     print('computing similarities')
30     sims = column_similarities(mat)
31     del mat
32     sims = pd.DataFrame(sims.todense())
33     sims = sims.rename({i: sr for i, sr in enumerate(subreddit_names.subreddit.values)}, axis=1)
34     sims['_subreddit'] = names.subreddit.values
35     outfile = str(Path(outdir) / str(week))
36     write_weekly_similarities(outfile, sims, week, names)
37
38 def pull_weeks(batch):
39     return set(batch.to_pandas()['week'])
40
41 #tfidf = spark.read.parquet('/gscratch/comdata/users/nathante/subreddit_tfidf_weekly.parquet')
42 def cosine_similarities_weekly(tfidf_path, outfile, term_colname, min_df = None, max_df=None, included_subreddits = None, topN = 500):
43     print(outfile)
44     tfidf_ds = ds.dataset(tfidf_path)
45     tfidf_ds = tfidf_ds.to_table(columns=["week"])
46     batches = tfidf_ds.to_batches()
47
48     with Pool(cpu_count()) as pool:
49         weeks = set(chain( * pool.imap_unordered(pull_weeks,batches)))
50
51     weeks = sorted(weeks)
52     # do this step in parallel if we have the memory for it.
53     # should be doable with pool.map
54
55     print(f"computing weekly similarities")
56     week_similarities_helper = partial(_week_similarities,simfunc=column_similarities, tfidf_path=tfidf_path, term_colname=term_colname, outdir=outfile, min_df=min_df,max_df=max_df,included_subreddits=included_subreddits,topN=topN)
57
58     with Pool(cpu_count()) as pool: # maybe it can be done with 40 cores on the huge machine?
59         list(pool.map(week_similarities_helper,weeks))
60
61 def author_cosine_similarities_weekly(outfile, min_df=2, max_df=None, included_subreddits=None, topN=500):
62     return cosine_similarities_weekly('/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_authors.parquet',
63                                       outfile,
64                                       'author',
65                                       min_df,
66                                       max_df,
67                                       included_subreddits,
68                                       topN)
69
70 def term_cosine_similarities_weekly(outfile, min_df=None, max_df=None, included_subreddits=None, topN=500):
71         return cosine_similarities_weekly('/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_terms.parquet',
72                                           outfile,
73                                           'term',
74                                           min_df,
75                                           max_df,
76                                           included_subreddits,
77                                           topN)
78
79 if __name__ == "__main__":
80     fire.Fire({'authors':author_cosine_similarities_weekly,
81                'terms':term_cosine_similarities_weekly})

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