]> code.communitydata.science - cdsc_reddit.git/blob - similarities/weekly_cosine_similarities.py
Merge branch 'excise_reindex' of code:cdsc_reddit into excise_reindex
[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 pull_tfidf, column_similarities, write_weekly_similarities
12 from scipy.sparse import csr_matrix
13 from multiprocessing import Pool, cpu_count
14 from functools import partial
15
16 # infile = "/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_authors_test.parquet"
17 # tfidf_path = infile 
18 # min_df=None
19 # max_df = None
20 # topN=100
21 # term_colname='author'
22 # outfile = '/gscratch/comdata/output/reddit_similarity/weekly/comment_authors_test.parquet'
23 # included_subreddits=None
24
25 def _week_similarities(week, simfunc, tfidf_path, term_colname, min_df, max_df, included_subreddits, topN, outdir:Path, subreddit_names, nterms):
26     term = term_colname
27     term_id = term + '_id'
28     term_id_new = term + '_id_new'
29     print(f"loading matrix: {week}")
30
31     entries = pull_tfidf(infile = tfidf_path,
32                          term_colname=term_colname,
33                          min_df=min_df,
34                          max_df=max_df,
35                          included_subreddits=included_subreddits,
36                          topN=topN,
37                          week=week.isoformat(),
38                          rescale_idf=False)
39     
40     tfidf_colname='tf_idf'
41     # if the max subreddit id we found is less than the number of subreddit names then we have to fill in 0s
42     mat = csr_matrix((entries[tfidf_colname],(entries[term_id_new]-1, entries.subreddit_id_new-1)),shape=(nterms,subreddit_names.shape[0]))
43
44     print('computing similarities')
45     sims = simfunc(mat.T)
46     del mat
47     sims = pd.DataFrame(sims)
48     sims = sims.rename({i: sr for i, sr in enumerate(subreddit_names.subreddit.values)}, axis=1)
49     sims['_subreddit'] = subreddit_names.subreddit.values
50     outfile = str(Path(outdir) / str(week))
51     write_weekly_similarities(outfile, sims, week, subreddit_names)
52
53 def pull_weeks(batch):
54     return set(batch.to_pandas()['week'])
55
56 #tfidf = spark.read.parquet('/gscratch/comdata/users/nathante/subreddit_tfidf_weekly.parquet')
57 def cosine_similarities_weekly(tfidf_path, outfile, term_colname, min_df = None, max_df=None, included_subreddits = None, topN = 500):
58     print(outfile)
59     # do this step in parallel if we have the memory for it.
60     # should be doable with pool.map
61
62     spark = SparkSession.builder.getOrCreate()
63     df = spark.read.parquet(tfidf_path)
64     subreddit_names = df.select(['subreddit','subreddit_id']).distinct().toPandas()
65     subreddit_names = subreddit_names.sort_values("subreddit_id")
66     nterms = df.select(f.max(f.col(term_colname + "_id")).alias('max')).collect()[0].max
67     weeks = df.select(f.col("week")).distinct().toPandas().week.values
68     spark.stop()
69
70     print(f"computing weekly similarities")
71     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, subreddit_names=subreddit_names,nterms=nterms)
72
73     pool = Pool(cpu_count())
74     
75     list(pool.imap(week_similarities_helper,weeks))
76     pool.close()
77     #    with Pool(cpu_count()) as pool: # maybe it can be done with 40 cores on the huge machine?
78
79
80 def author_cosine_similarities_weekly(outfile, min_df=2, max_df=None, included_subreddits=None, topN=500):
81     return cosine_similarities_weekly('/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_authors_test.parquet',
82                                       outfile,
83                                       'author',
84                                       min_df,
85                                       max_df,
86                                       included_subreddits,
87                                       topN)
88
89 def term_cosine_similarities_weekly(outfile, min_df=None, max_df=None, included_subreddits=None, topN=500):
90         return cosine_similarities_weekly('/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_terms.parquet',
91                                           outfile,
92                                           'term',
93                                           min_df,
94                                           max_df,
95                                           included_subreddits,
96                                           topN)
97
98 if __name__ == "__main__":
99     fire.Fire({'authors':author_cosine_similarities_weekly,
100                'terms':term_cosine_similarities_weekly})

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