1 from pyspark.sql import functions as f
2 from pyspark.sql import SparkSession
3 from pyspark.sql import Window
4 from pyspark.mllib.linalg.distributed import RowMatrix, CoordinateMatrix
9 from itertools import islice
10 from pathlib import Path
11 from similarities_helper import prep_tfidf_entries, read_tfidf_matrix, column_similarities, select_topN
14 # outfile='test_similarities_500.feather';
16 # included_subreddits=None; topN=100; exclude_phrases=True;
17 def term_cosine_similarities(outfile, min_df = None, included_subreddits=None, topN=500, exclude_phrases=False):
18 spark = SparkSession.builder.getOrCreate()
19 conf = spark.sparkContext.getConf()
21 print(exclude_phrases)
23 tfidf = spark.read.parquet('/gscratch/comdata/output/reddit_similarity/tfidf/subreddit_terms.parquet')
25 if included_subreddits is None:
26 included_subreddits = select_topN_subreddits(topN)
28 included_subreddits = set(open(included_subreddits))
30 if exclude_phrases == True:
31 tfidf = tfidf.filter(~f.col(term).contains("_"))
33 print("creating temporary parquet with matrix indicies")
34 tempdir = prep_tfidf_entries(tfidf, 'term', min_df, included_subreddits)
35 tfidf = spark.read.parquet(tempdir.name)
36 subreddit_names = tfidf.select(['subreddit','subreddit_id_new']).distinct().toPandas()
37 subreddit_names = subreddit_names.sort_values("subreddit_id_new")
38 subreddit_names['subreddit_id_new'] = subreddit_names['subreddit_id_new'] - 1
41 print("loading matrix")
42 mat = read_tfidf_matrix(tempdir.name,'term')
43 print('computing similarities')
44 sims = column_similarities(mat)
47 sims = pd.DataFrame(sims.todense())
48 sims = sims.rename({i:sr for i, sr in enumerate(subreddit_names.subreddit.values)},axis=1)
49 sims['subreddit'] = subreddit_names.subreddit.values
53 output_feather = Path(str(p).replace("".join(p.suffixes), ".feather"))
54 output_csv = Path(str(p).replace("".join(p.suffixes), ".csv"))
55 output_parquet = Path(str(p).replace("".join(p.suffixes), ".parquet"))
57 sims.to_feather(outfile)
60 if __name__ == '__main__':
61 fire.Fire(term_cosine_similarities)