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 cosine_similarities, prep_tfidf_entries, read_tfidf_matrix, column_similarities
13 # outfile='test_similarities_500.feather';
15 # 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/users/nathante/subreddit_tfidf.parquet')
25 if included_subreddits is None:
26 rankdf = pd.read_csv("/gscratch/comdata/users/nathante/cdsc-reddit/subreddits_by_num_comments.csv")
27 included_subreddits = set(rankdf.loc[rankdf.comments_rank <= topN,'subreddit'].values)
30 included_subreddits = set(open(included_subreddits))
32 if exclude_phrases == True:
33 tfidf = tfidf.filter(~f.col(term).contains("_"))
35 print("creating temporary parquet with matrix indicies")
36 tempdir = prep_tfidf_entries(tfidf, 'term', min_df, included_subreddits)
37 tfidf = spark.read.parquet(tempdir.name)
38 subreddit_names = tfidf.select(['subreddit','subreddit_id_new']).distinct().toPandas()
39 subreddit_names = subreddit_names.sort_values("subreddit_id_new")
40 subreddit_names['subreddit_id_new'] = subreddit_names['subreddit_id_new'] - 1
43 print("loading matrix")
44 mat = read_tfidf_matrix(tempdir.name,'term')
45 print('computing similarities')
46 sims = column_similarities(mat)
49 sims = pd.DataFrame(sims.todense())
50 sims = sims.rename({i:sr for i, sr in enumerate(subreddit_names.subreddit.values)},axis=1)
51 sims['subreddit'] = subreddit_names.subreddit.values
55 output_feather = Path(str(p).replace("".join(p.suffixes), ".feather"))
56 output_csv = Path(str(p).replace("".join(p.suffixes), ".csv"))
57 output_parquet = Path(str(p).replace("".join(p.suffixes), ".parquet"))
59 sims.to_feather(outfile)
61 path = "term_tfidf_entriesaukjy5gv.parquet"
64 # outfile = '/gscratch/comdata/users/nathante/test_similarities_500.feather'; min_df = None; included_subreddits=None; similarity_threshold=0;
65 # def term_cosine_similarities(outfile, min_df = None, included_subreddits=None, similarity_threshold=0, topN=500, exclude_phrases=True):
67 # Compute similarities between subreddits based on tfi-idf vectors of comment texts
69 # included_subreddits : string
70 # Text file containing a list of subreddits to include (one per line) if included_subreddits is None then do the top 500 subreddits
72 # similarity_threshold : double (default = 0)
73 # set > 0 for large numbers of subreddits to get an approximate solution using the DIMSUM algorithm
74 # https://stanford.edu/~rezab/papers/dimsum.pdf. If similarity_threshold=0 we get an exact solution using an O(N^2) algorithm.
76 # min_df : int (default = 0.1 * (number of included_subreddits)
77 # exclude terms that appear in fewer than this number of documents.
80 # where to output csv and feather outputs
84 # print(exclude_phrases)
86 # tfidf = spark.read.parquet('/gscratch/comdata/users/nathante/subreddit_tfidf.parquet')
88 # if included_subreddits is None:
89 # included_subreddits = list(islice(open("/gscratch/comdata/users/nathante/cdsc-reddit/top_25000_subs_by_comments.txt"),topN))
90 # included_subreddits = {s.strip('\n') for s in included_subreddits}
93 # included_subreddits = set(open(included_subreddits))
95 # if exclude_phrases == True:
96 # tfidf = tfidf.filter(~f.col(term).contains("_"))
98 # sim_dist, tfidf = cosine_similarities(tfidf, 'term', min_df, included_subreddits, similarity_threshold)
102 # output_feather = Path(str(p).replace("".join(p.suffixes), ".feather"))
103 # output_csv = Path(str(p).replace("".join(p.suffixes), ".csv"))
104 # output_parquet = Path(str(p).replace("".join(p.suffixes), ".parquet"))
106 # sim_dist.entries.toDF().write.parquet(str(output_parquet),mode='overwrite',compression='snappy')
108 # #instead of toLocalMatrix() why not read as entries and put strait into numpy
109 # sim_entries = pd.read_parquet(output_parquet)
111 # df = tfidf.select('subreddit','subreddit_id_new').distinct().toPandas()
113 # df['subreddit_id_new'] = df['subreddit_id_new'] - 1
114 # df = df.sort_values('subreddit_id_new').reset_index(drop=True)
115 # df = df.set_index('subreddit_id_new')
117 # similarities = sim_entries.join(df, on='i')
118 # similarities = similarities.rename(columns={'subreddit':"subreddit_i"})
119 # similarities = similarities.join(df, on='j')
120 # similarities = similarities.rename(columns={'subreddit':"subreddit_j"})
122 # similarities.to_feather(output_feather)
123 # similarities.to_csv(output_csv)
124 # return similarities
126 if __name__ == '__main__':
127 fire.Fire(term_cosine_similarities)