]> code.communitydata.science - cdsc_reddit.git/blob - similarities/similarities_helper.py
9e33c9d105c4c4190ce47c84cf56be3b753326b0
[cdsc_reddit.git] / similarities / similarities_helper.py
1 from pyspark.sql import SparkSession
2 from pyspark.sql import Window
3 from pyspark.sql import functions as f
4 from enum import Enum
5 from pyspark.mllib.linalg.distributed import CoordinateMatrix
6 from tempfile import TemporaryDirectory
7 import pyarrow
8 import pyarrow.dataset as ds
9 from scipy.sparse import csr_matrix, issparse
10 import pandas as pd
11 import numpy as np
12 import pathlib
13 from datetime import datetime
14 from pathlib import Path
15
16 class tf_weight(Enum):
17     MaxTF = 1
18     Norm05 = 2
19
20 infile = "/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_authors.parquet"
21
22 def reindex_tfidf_time_interval(infile, term_colname, min_df=None, max_df=None, included_subreddits=None, topN=500, exclude_phrases=False, from_date=None, to_date=None):
23     term = term_colname
24     term_id = term + '_id'
25     term_id_new = term + '_id_new'
26
27     spark = SparkSession.builder.getOrCreate()
28     conf = spark.sparkContext.getConf()
29     print(exclude_phrases)
30     tfidf_weekly = spark.read.parquet(infile)
31
32     # create the time interval
33     if from_date is not None:
34         if type(from_date) is str:
35             from_date = datetime.fromisoformat(from_date)
36
37         tfidf_weekly = tfidf_weekly.filter(tfidf_weekly.week >= from_date)
38         
39     if to_date is not None:
40         if type(to_date) is str:
41             to_date = datetime.fromisoformat(to_date)
42         tfidf_weekly = tfidf_weekly.filter(tfidf_weekly.week < to_date)
43
44     tfidf = tfidf_weekly.groupBy(["subreddit","week", term_id, term]).agg(f.sum("tf").alias("tf"))
45     tfidf = _calc_tfidf(tfidf, term_colname, tf_weight.Norm05)
46     tempdir = prep_tfidf_entries(tfidf, term_colname, min_df, max_df, included_subreddits)
47     tfidf = spark.read_parquet(tempdir.name)
48     subreddit_names = tfidf.select(['subreddit','subreddit_id_new']).distinct().toPandas()
49     subreddit_names = subreddit_names.sort_values("subreddit_id_new")
50     subreddit_names['subreddit_id_new'] = subreddit_names['subreddit_id_new'] - 1
51     return(tempdir, subreddit_names)
52
53 def reindex_tfidf(infile, term_colname, min_df=None, max_df=None, included_subreddits=None, topN=500, exclude_phrases=False):
54     spark = SparkSession.builder.getOrCreate()
55     conf = spark.sparkContext.getConf()
56     print(exclude_phrases)
57
58     tfidf = spark.read.parquet(infile)
59
60     if included_subreddits is None:
61         included_subreddits = select_topN_subreddits(topN)
62     else:
63         included_subreddits = set(open(included_subreddits))
64
65     if exclude_phrases == True:
66         tfidf = tfidf.filter(~f.col(term_colname).contains("_"))
67
68     print("creating temporary parquet with matrix indicies")
69     tempdir = prep_tfidf_entries(tfidf, term_colname, min_df, max_df, included_subreddits)
70
71     tfidf = spark.read.parquet(tempdir.name)
72     subreddit_names = tfidf.select(['subreddit','subreddit_id_new']).distinct().toPandas()
73     subreddit_names = subreddit_names.sort_values("subreddit_id_new")
74     subreddit_names['subreddit_id_new'] = subreddit_names['subreddit_id_new'] - 1
75     spark.stop()
76     return (tempdir, subreddit_names)
77
78
79 def similarities(infile, simfunc, term_colname, outfile, min_df=None, max_df=None, included_subreddits=None, topN=500, exclude_phrases=False, from_date=None, to_date=None, tfidf_colname='tf_idf'):
80     '''
81     tfidf_colname: set to 'relative_tf' to use normalized term frequency instead of tf-idf, which can be useful for author-based similarities.
82     '''
83     if from_date is not None or to_date is not None:
84         tempdir, subreddit_names = reindex_tfidf_time_interval(infile, term_colname=term_colname, min_df=min_df, max_df=max_df, included_subreddits=included_subreddits, topN=topN, exclude_phrases=False, from_date=from_date, to_date=to_date)
85         
86     else:
87         tempdir, subreddit_names = reindex_tfidf(infile, term_colname=term_colname, min_df=min_df, max_df=max_df, included_subreddits=included_subreddits, topN=topN, exclude_phrases=False)
88
89     print("loading matrix")
90     #    mat = read_tfidf_matrix("term_tfidf_entries7ejhvnvl.parquet", term_colname)
91     mat = read_tfidf_matrix(tempdir.name, term_colname, tfidf_colname)
92     print('computing similarities')
93     sims = simfunc(mat)
94     del mat
95
96     if issparse(sims):
97         sims = sims.todense()
98
99     print(f"shape of sims:{sims.shape}")
100     print(f"len(subreddit_names.subreddit.values):{len(subreddit_names.subreddit.values)}")
101     sims = pd.DataFrame(sims)
102     sims = sims.rename({i:sr for i, sr in enumerate(subreddit_names.subreddit.values)}, axis=1)
103     sims['subreddit'] = subreddit_names.subreddit.values
104
105     p = Path(outfile)
106
107     output_feather =  Path(str(p).replace("".join(p.suffixes), ".feather"))
108     output_csv =  Path(str(p).replace("".join(p.suffixes), ".csv"))
109     output_parquet =  Path(str(p).replace("".join(p.suffixes), ".parquet"))
110
111     sims.to_feather(outfile)
112     tempdir.cleanup()
113
114 def read_tfidf_matrix_weekly(path, term_colname, week, tfidf_colname='tf_idf'):
115     term = term_colname
116     term_id = term + '_id'
117     term_id_new = term + '_id_new'
118
119     dataset = ds.dataset(path,format='parquet')
120     entries = dataset.to_table(columns=[tfidf_colname,'subreddit_id_new', term_id_new],filter=ds.field('week')==week).to_pandas()
121     return(csr_matrix((entries[tfidf_colname], (entries[term_id_new]-1, entries.subreddit_id_new-1))))
122
123 def read_tfidf_matrix(path, term_colname, tfidf_colname='tf_idf'):
124     term = term_colname
125     term_id = term + '_id'
126     term_id_new = term + '_id_new'
127     dataset = ds.dataset(path,format='parquet')
128     print(f"tfidf_colname:{tfidf_colname}")
129     entries = dataset.to_table(columns=[tfidf_colname, 'subreddit_id_new',term_id_new]).to_pandas()
130     return(csr_matrix((entries[tfidf_colname],(entries[term_id_new]-1, entries.subreddit_id_new-1))))
131     
132
133 def write_weekly_similarities(path, sims, week, names):
134     sims['week'] = week
135     p = pathlib.Path(path)
136     if not p.is_dir():
137         p.mkdir()
138         
139     # reformat as a pairwise list
140     sims = sims.melt(id_vars=['subreddit','week'],value_vars=names.subreddit.values)
141     sims.to_parquet(p / week.isoformat())
142
143 def column_overlaps(mat):
144     non_zeros = (mat != 0).astype('double')
145     
146     intersection = non_zeros.T @ non_zeros
147     card1 = non_zeros.sum(axis=0)
148     den = np.add.outer(card1,card1) - intersection
149
150     return intersection / den
151     
152 def column_similarities(mat):
153     norm = np.matrix(np.power(mat.power(2).sum(axis=0),0.5,dtype=np.float32))
154     mat = mat.multiply(1/norm)
155     sims = mat.T @ mat
156     return(sims)
157
158
159 def prep_tfidf_entries_weekly(tfidf, term_colname, min_df, max_df, included_subreddits):
160     term = term_colname
161     term_id = term + '_id'
162     term_id_new = term + '_id_new'
163
164     if min_df is None:
165         min_df = 0.1 * len(included_subreddits)
166         tfidf = tfidf.filter(f.col('count') >= min_df)
167     if max_df is not None:
168         tfidf = tfidf.filter(f.col('count') <= max_df)
169
170     tfidf = tfidf.filter(f.col("subreddit").isin(included_subreddits))
171
172     # we might not have the same terms or subreddits each week, so we need to make unique ids for each week.
173     sub_ids = tfidf.select(['subreddit_id','week']).distinct()
174     sub_ids = sub_ids.withColumn("subreddit_id_new",f.row_number().over(Window.partitionBy('week').orderBy("subreddit_id")))
175     tfidf = tfidf.join(sub_ids,['subreddit_id','week'])
176
177     # only use terms in at least min_df included subreddits in a given week
178     new_count = tfidf.groupBy([term_id,'week']).agg(f.count(term_id).alias('new_count'))
179     tfidf = tfidf.join(new_count,[term_id,'week'],how='inner')
180
181     # reset the term ids
182     term_ids = tfidf.select([term_id,'week']).distinct()
183     term_ids = term_ids.withColumn(term_id_new,f.row_number().over(Window.partitionBy('week').orderBy(term_id)))
184     tfidf = tfidf.join(term_ids,[term_id,'week'])
185
186     tfidf = tfidf.withColumnRenamed("tf_idf","tf_idf_old")
187     tfidf = tfidf.withColumn("tf_idf", (tfidf.relative_tf * tfidf.idf).cast('float'))
188
189     tempdir =TemporaryDirectory(suffix='.parquet',prefix='term_tfidf_entries',dir='.')
190
191     tfidf = tfidf.repartition('week')
192
193     tfidf.write.parquet(tempdir.name,mode='overwrite',compression='snappy')
194     return(tempdir)
195     
196
197 def prep_tfidf_entries(tfidf, term_colname, min_df, max_df, included_subreddits):
198     term = term_colname
199     term_id = term + '_id'
200     term_id_new = term + '_id_new'
201
202     if min_df is None:
203         min_df = 0.1 * len(included_subreddits)
204         tfidf = tfidf.filter(f.col('count') >= min_df)
205     if max_df is not None:
206         tfidf = tfidf.filter(f.col('count') <= max_df)
207
208     tfidf = tfidf.filter(f.col("subreddit").isin(included_subreddits))
209
210     # reset the subreddit ids
211     sub_ids = tfidf.select('subreddit_id').distinct()
212     sub_ids = sub_ids.withColumn("subreddit_id_new", f.row_number().over(Window.orderBy("subreddit_id")))
213     tfidf = tfidf.join(sub_ids,'subreddit_id')
214
215     # only use terms in at least min_df included subreddits
216     new_count = tfidf.groupBy(term_id).agg(f.count(term_id).alias('new_count'))
217     tfidf = tfidf.join(new_count,term_id,how='inner')
218     
219     # reset the term ids
220     term_ids = tfidf.select([term_id]).distinct()
221     term_ids = term_ids.withColumn(term_id_new,f.row_number().over(Window.orderBy(term_id)))
222     tfidf = tfidf.join(term_ids,term_id)
223
224     tfidf = tfidf.withColumnRenamed("tf_idf","tf_idf_old")
225     tfidf = tfidf.withColumn("tf_idf", (tfidf.relative_tf * tfidf.idf).cast('float'))
226     
227     tempdir =TemporaryDirectory(suffix='.parquet',prefix='term_tfidf_entries',dir='.')
228     
229     tfidf.write.parquet(tempdir.name,mode='overwrite',compression='snappy')
230     return tempdir
231
232
233 # try computing cosine similarities using spark
234 def spark_cosine_similarities(tfidf, term_colname, min_df, included_subreddits, similarity_threshold):
235     term = term_colname
236     term_id = term + '_id'
237     term_id_new = term + '_id_new'
238
239     if min_df is None:
240         min_df = 0.1 * len(included_subreddits)
241
242     tfidf = tfidf.filter(f.col("subreddit").isin(included_subreddits))
243     tfidf = tfidf.cache()
244
245     # reset the subreddit ids
246     sub_ids = tfidf.select('subreddit_id').distinct()
247     sub_ids = sub_ids.withColumn("subreddit_id_new",f.row_number().over(Window.orderBy("subreddit_id")))
248     tfidf = tfidf.join(sub_ids,'subreddit_id')
249
250     # only use terms in at least min_df included subreddits
251     new_count = tfidf.groupBy(term_id).agg(f.count(term_id).alias('new_count'))
252     tfidf = tfidf.join(new_count,term_id,how='inner')
253     
254     # reset the term ids
255     term_ids = tfidf.select([term_id]).distinct()
256     term_ids = term_ids.withColumn(term_id_new,f.row_number().over(Window.orderBy(term_id)))
257     tfidf = tfidf.join(term_ids,term_id)
258
259     tfidf = tfidf.withColumnRenamed("tf_idf","tf_idf_old")
260     tfidf = tfidf.withColumn("tf_idf", tfidf.relative_tf * tfidf.idf)
261
262     # step 1 make an rdd of entires
263     # sorted by (dense) spark subreddit id
264     n_partitions = int(len(included_subreddits)*2 / 5)
265
266     entries = tfidf.select(f.col(term_id_new)-1,f.col("subreddit_id_new")-1,"tf_idf").rdd.repartition(n_partitions)
267
268     # put like 10 subredis in each partition
269
270     # step 2 make it into a distributed.RowMatrix
271     coordMat = CoordinateMatrix(entries)
272
273     coordMat = CoordinateMatrix(coordMat.entries.repartition(n_partitions))
274
275     # this needs to be an IndexedRowMatrix()
276     mat = coordMat.toRowMatrix()
277
278     #goal: build a matrix of subreddit columns and tf-idfs rows
279     sim_dist = mat.columnSimilarities(threshold=similarity_threshold)
280
281     return (sim_dist, tfidf)
282
283
284 def build_weekly_tfidf_dataset(df, include_subs, term_colname, tf_family=tf_weight.Norm05):
285     term = term_colname
286     term_id = term + '_id'
287
288     # aggregate counts by week. now subreddit-term is distinct
289     df = df.filter(df.subreddit.isin(include_subs))
290     df = df.groupBy(['subreddit',term,'week']).agg(f.sum('tf').alias('tf'))
291
292     max_subreddit_terms = df.groupby(['subreddit','week']).max('tf') # subreddits are unique
293     max_subreddit_terms = max_subreddit_terms.withColumnRenamed('max(tf)','sr_max_tf')
294     df = df.join(max_subreddit_terms, on=['subreddit','week'])
295     df = df.withColumn("relative_tf", df.tf / df.sr_max_tf)
296
297     # group by term. term is unique
298     idf = df.groupby([term,'week']).count()
299
300     N_docs = df.select(['subreddit','week']).distinct().groupby(['week']).agg(f.count("subreddit").alias("subreddits_in_week"))
301
302     idf = idf.join(N_docs, on=['week'])
303
304     # add a little smoothing to the idf
305     idf = idf.withColumn('idf',f.log(idf.subreddits_in_week) / (1+f.col('count'))+1)
306
307     # collect the dictionary to make a pydict of terms to indexes
308     terms = idf.select([term,'week']).distinct() # terms are distinct
309
310     terms = terms.withColumn(term_id,f.row_number().over(Window.partitionBy('week').orderBy(term))) # term ids are distinct
311
312     # make subreddit ids
313     subreddits = df.select(['subreddit','week']).distinct()
314     subreddits = subreddits.withColumn('subreddit_id',f.row_number().over(Window.partitionBy("week").orderBy("subreddit")))
315
316     df = df.join(subreddits,on=['subreddit','week'])
317
318     # map terms to indexes in the tfs and the idfs
319     df = df.join(terms,on=[term,'week']) # subreddit-term-id is unique
320
321     idf = idf.join(terms,on=[term,'week'])
322
323     # join on subreddit/term to create tf/dfs indexed by term
324     df = df.join(idf, on=[term_id, term,'week'])
325
326     # agg terms by subreddit to make sparse tf/df vectors
327     
328     if tf_family == tf_weight.MaxTF:
329         df = df.withColumn("tf_idf",  df.relative_tf * df.idf)
330     else: # tf_fam = tf_weight.Norm05
331         df = df.withColumn("tf_idf",  (0.5 + 0.5 * df.relative_tf) * df.idf)
332
333     return df
334
335 def _calc_tfidf(df, term_colname, tf_family):
336     term = term_colname
337     term_id = term + '_id'
338
339     max_subreddit_terms = df.groupby(['subreddit']).max('tf') # subreddits are unique
340     max_subreddit_terms = max_subreddit_terms.withColumnRenamed('max(tf)','sr_max_tf')
341
342     df = df.join(max_subreddit_terms, on='subreddit')
343
344     df = df.withColumn("relative_tf", df.tf / df.sr_max_tf)
345
346     # group by term. term is unique
347     idf = df.groupby([term]).count()
348     N_docs = df.select('subreddit').distinct().count()
349     # add a little smoothing to the idf
350     idf = idf.withColumn('idf',f.log(N_docs/(1+f.col('count')))+1)
351
352     # collect the dictionary to make a pydict of terms to indexes
353     terms = idf.select(term).distinct() # terms are distinct
354     terms = terms.withColumn(term_id,f.row_number().over(Window.orderBy(term))) # term ids are distinct
355
356     # make subreddit ids
357     subreddits = df.select(['subreddit']).distinct()
358     subreddits = subreddits.withColumn('subreddit_id',f.row_number().over(Window.orderBy("subreddit")))
359
360     df = df.join(subreddits,on='subreddit')
361
362     # map terms to indexes in the tfs and the idfs
363     df = df.join(terms,on=term) # subreddit-term-id is unique
364
365     idf = idf.join(terms,on=term)
366
367     # join on subreddit/term to create tf/dfs indexed by term
368     df = df.join(idf, on=[term_id, term])
369
370     # agg terms by subreddit to make sparse tf/df vectors
371     if tf_family == tf_weight.MaxTF:
372         df = df.withColumn("tf_idf",  df.relative_tf * df.idf)
373     else: # tf_fam = tf_weight.Norm05
374         df = df.withColumn("tf_idf",  (0.5 + 0.5 * df.relative_tf) * df.idf)
375
376     return df
377     
378
379 def build_tfidf_dataset(df, include_subs, term_colname, tf_family=tf_weight.Norm05):
380     term = term_colname
381     term_id = term + '_id'
382     # aggregate counts by week. now subreddit-term is distinct
383     df = df.filter(df.subreddit.isin(include_subs))
384     df = df.groupBy(['subreddit',term]).agg(f.sum('tf').alias('tf'))
385
386     df = _calc_tfidf(df, term_colname, tf_family)
387
388     return df
389
390 def select_topN_subreddits(topN, path="/gscratch/comdata/output/reddit_similarity/subreddits_by_num_comments_nonswf.csv"):
391     rankdf = pd.read_csv(path)
392     included_subreddits = set(rankdf.loc[rankdf.comments_rank <= topN,'subreddit'].values)
393     return included_subreddits

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