]> code.communitydata.science - cdsc_reddit.git/blob - similarities/similarities_helper.py
88c830cacf7d5971e6e885882b1771d0c864183b
[cdsc_reddit.git] / similarities / similarities_helper.py
1 from pyspark.sql import Window
2 from pyspark.sql import functions as f
3 from enum import Enum
4 from pyspark.mllib.linalg.distributed import CoordinateMatrix
5 from tempfile import TemporaryDirectory
6 import pyarrow
7 import pyarrow.dataset as ds
8 from scipy.sparse import csr_matrix
9 import pandas as pd
10 import numpy as np
11 import pathlib
12
13 class tf_weight(Enum):
14     MaxTF = 1
15     Norm05 = 2
16
17 def read_tfidf_matrix_weekly(path, term_colname, week):
18     term = term_colname
19     term_id = term + '_id'
20     term_id_new = term + '_id_new'
21
22     dataset = ds.dataset(path,format='parquet')
23     entries = dataset.to_table(columns=['tf_idf','subreddit_id_new',term_id_new],filter=ds.field('week')==week).to_pandas()
24     return(csr_matrix((entries.tf_idf,(entries[term_id_new]-1, entries.subreddit_id_new-1))))
25
26 def write_weekly_similarities(path, sims, week, names):
27     sims['week'] = week
28     p = pathlib.Path(path)
29     if not p.is_dir():
30         p.mkdir()
31         
32     # reformat as a pairwise list
33     sims = sims.melt(id_vars=['subreddit','week'],value_vars=names.subreddit.values)
34     sims.to_parquet(p / week.isoformat())
35
36
37
38 def read_tfidf_matrix(path,term_colname):
39     term = term_colname
40     term_id = term + '_id'
41     term_id_new = term + '_id_new'
42
43     dataset = ds.dataset(path,format='parquet')
44     entries = dataset.to_table(columns=['tf_idf','subreddit_id_new',term_id_new]).to_pandas()
45     return(csr_matrix((entries.tf_idf,(entries[term_id_new]-1, entries.subreddit_id_new-1))))
46     
47 def column_similarities(mat):
48     norm = np.matrix(np.power(mat.power(2).sum(axis=0),0.5,dtype=np.float32))
49     mat = mat.multiply(1/norm)
50     sims = mat.T @ mat
51     return(sims)
52
53
54 def prep_tfidf_entries_weekly(tfidf, term_colname, min_df, included_subreddits):
55     term = term_colname
56     term_id = term + '_id'
57     term_id_new = term + '_id_new'
58
59     if min_df is None:
60         min_df = 0.1 * len(included_subreddits)
61
62     tfidf = tfidf.filter(f.col("subreddit").isin(included_subreddits))
63
64     # we might not have the same terms or subreddits each week, so we need to make unique ids for each week.
65     sub_ids = tfidf.select(['subreddit_id','week']).distinct()
66     sub_ids = sub_ids.withColumn("subreddit_id_new",f.row_number().over(Window.partitionBy('week').orderBy("subreddit_id")))
67     tfidf = tfidf.join(sub_ids,['subreddit_id','week'])
68
69     # only use terms in at least min_df included subreddits in a given week
70     new_count = tfidf.groupBy([term_id,'week']).agg(f.count(term_id).alias('new_count'))
71     tfidf = tfidf.join(new_count,[term_id,'week'],how='inner')
72
73     # reset the term ids
74     term_ids = tfidf.select([term_id,'week']).distinct()
75     term_ids = term_ids.withColumn(term_id_new,f.row_number().over(Window.partitionBy('week').orderBy(term_id)))
76     tfidf = tfidf.join(term_ids,[term_id,'week'])
77
78     tfidf = tfidf.withColumnRenamed("tf_idf","tf_idf_old")
79     tfidf = tfidf.withColumn("tf_idf", (tfidf.relative_tf * tfidf.idf).cast('float'))
80
81     tempdir =TemporaryDirectory(suffix='.parquet',prefix='term_tfidf_entries',dir='.')
82
83     tfidf = tfidf.repartition('week')
84
85     tfidf.write.parquet(tempdir.name,mode='overwrite',compression='snappy')
86     return(tempdir)
87     
88
89 def prep_tfidf_entries(tfidf, term_colname, min_df, included_subreddits):
90     term = term_colname
91     term_id = term + '_id'
92     term_id_new = term + '_id_new'
93
94     if min_df is None:
95         min_df = 0.1 * len(included_subreddits)
96
97     tfidf = tfidf.filter(f.col("subreddit").isin(included_subreddits))
98
99     # reset the subreddit ids
100     sub_ids = tfidf.select('subreddit_id').distinct()
101     sub_ids = sub_ids.withColumn("subreddit_id_new",f.row_number().over(Window.orderBy("subreddit_id")))
102     tfidf = tfidf.join(sub_ids,'subreddit_id')
103
104     # only use terms in at least min_df included subreddits
105     new_count = tfidf.groupBy(term_id).agg(f.count(term_id).alias('new_count'))
106     tfidf = tfidf.join(new_count,term_id,how='inner')
107     
108     # reset the term ids
109     term_ids = tfidf.select([term_id]).distinct()
110     term_ids = term_ids.withColumn(term_id_new,f.row_number().over(Window.orderBy(term_id)))
111     tfidf = tfidf.join(term_ids,term_id)
112
113     tfidf = tfidf.withColumnRenamed("tf_idf","tf_idf_old")
114     tfidf = tfidf.withColumn("tf_idf", (tfidf.relative_tf * tfidf.idf).cast('float'))
115     
116     tempdir =TemporaryDirectory(suffix='.parquet',prefix='term_tfidf_entries',dir='.')
117     
118     tfidf.write.parquet(tempdir.name,mode='overwrite',compression='snappy')
119     return tempdir
120
121
122 # try computing cosine similarities using spark
123 def spark_cosine_similarities(tfidf, term_colname, min_df, included_subreddits, similarity_threshold):
124     term = term_colname
125     term_id = term + '_id'
126     term_id_new = term + '_id_new'
127
128     if min_df is None:
129         min_df = 0.1 * len(included_subreddits)
130
131     tfidf = tfidf.filter(f.col("subreddit").isin(included_subreddits))
132     tfidf = tfidf.cache()
133
134     # reset the subreddit ids
135     sub_ids = tfidf.select('subreddit_id').distinct()
136     sub_ids = sub_ids.withColumn("subreddit_id_new",f.row_number().over(Window.orderBy("subreddit_id")))
137     tfidf = tfidf.join(sub_ids,'subreddit_id')
138
139     # only use terms in at least min_df included subreddits
140     new_count = tfidf.groupBy(term_id).agg(f.count(term_id).alias('new_count'))
141     tfidf = tfidf.join(new_count,term_id,how='inner')
142     
143     # reset the term ids
144     term_ids = tfidf.select([term_id]).distinct()
145     term_ids = term_ids.withColumn(term_id_new,f.row_number().over(Window.orderBy(term_id)))
146     tfidf = tfidf.join(term_ids,term_id)
147
148     tfidf = tfidf.withColumnRenamed("tf_idf","tf_idf_old")
149     tfidf = tfidf.withColumn("tf_idf", tfidf.relative_tf * tfidf.idf)
150
151     # step 1 make an rdd of entires
152     # sorted by (dense) spark subreddit id
153     n_partitions = int(len(included_subreddits)*2 / 5)
154
155     entries = tfidf.select(f.col(term_id_new)-1,f.col("subreddit_id_new")-1,"tf_idf").rdd.repartition(n_partitions)
156
157     # put like 10 subredis in each partition
158
159     # step 2 make it into a distributed.RowMatrix
160     coordMat = CoordinateMatrix(entries)
161
162     coordMat = CoordinateMatrix(coordMat.entries.repartition(n_partitions))
163
164     # this needs to be an IndexedRowMatrix()
165     mat = coordMat.toRowMatrix()
166
167     #goal: build a matrix of subreddit columns and tf-idfs rows
168     sim_dist = mat.columnSimilarities(threshold=similarity_threshold)
169
170     return (sim_dist, tfidf)
171
172
173 def build_weekly_tfidf_dataset(df, include_subs, term_colname, tf_family=tf_weight.Norm05):
174     term = term_colname
175     term_id = term + '_id'
176
177     # aggregate counts by week. now subreddit-term is distinct
178     df = df.filter(df.subreddit.isin(include_subs))
179     df = df.groupBy(['subreddit',term,'week']).agg(f.sum('tf').alias('tf'))
180
181     max_subreddit_terms = df.groupby(['subreddit','week']).max('tf') # subreddits are unique
182     max_subreddit_terms = max_subreddit_terms.withColumnRenamed('max(tf)','sr_max_tf')
183     df = df.join(max_subreddit_terms, on=['subreddit','week'])
184     df = df.withColumn("relative_tf", df.tf / df.sr_max_tf)
185
186     # group by term. term is unique
187     idf = df.groupby([term,'week']).count()
188
189     N_docs = df.select(['subreddit','week']).distinct().groupby(['week']).agg(f.count("subreddit").alias("subreddits_in_week"))
190
191     idf = idf.join(N_docs, on=['week'])
192
193     # add a little smoothing to the idf
194     idf = idf.withColumn('idf',f.log(idf.subreddits_in_week) / (1+f.col('count'))+1)
195
196     # collect the dictionary to make a pydict of terms to indexes
197     terms = idf.select([term,'week']).distinct() # terms are distinct
198
199     terms = terms.withColumn(term_id,f.row_number().over(Window.partitionBy('week').orderBy(term))) # term ids are distinct
200
201     # make subreddit ids
202     subreddits = df.select(['subreddit','week']).distinct()
203     subreddits = subreddits.withColumn('subreddit_id',f.row_number().over(Window.partitionBy("week").orderBy("subreddit")))
204
205     df = df.join(subreddits,on=['subreddit','week'])
206
207     # map terms to indexes in the tfs and the idfs
208     df = df.join(terms,on=[term,'week']) # subreddit-term-id is unique
209
210     idf = idf.join(terms,on=[term,'week'])
211
212     # join on subreddit/term to create tf/dfs indexed by term
213     df = df.join(idf, on=[term_id, term,'week'])
214
215     # agg terms by subreddit to make sparse tf/df vectors
216     
217     if tf_family == tf_weight.MaxTF:
218         df = df.withColumn("tf_idf",  df.relative_tf * df.idf)
219     else: # tf_fam = tf_weight.Norm05
220         df = df.withColumn("tf_idf",  (0.5 + 0.5 * df.relative_tf) * df.idf)
221
222     return df
223
224
225
226 def build_tfidf_dataset(df, include_subs, term_colname, tf_family=tf_weight.Norm05):
227
228     term = term_colname
229     term_id = term + '_id'
230     # aggregate counts by week. now subreddit-term is distinct
231     df = df.filter(df.subreddit.isin(include_subs))
232     df = df.groupBy(['subreddit',term]).agg(f.sum('tf').alias('tf'))
233
234     max_subreddit_terms = df.groupby(['subreddit']).max('tf') # subreddits are unique
235     max_subreddit_terms = max_subreddit_terms.withColumnRenamed('max(tf)','sr_max_tf')
236
237     df = df.join(max_subreddit_terms, on='subreddit')
238
239     df = df.withColumn("relative_tf", df.tf / df.sr_max_tf)
240
241     # group by term. term is unique
242     idf = df.groupby([term]).count()
243
244     N_docs = df.select('subreddit').distinct().count()
245
246     # add a little smoothing to the idf
247     idf = idf.withColumn('idf',f.log(N_docs/(1+f.col('count')))+1)
248
249     # collect the dictionary to make a pydict of terms to indexes
250     terms = idf.select(term).distinct() # terms are distinct
251     terms = terms.withColumn(term_id,f.row_number().over(Window.orderBy(term))) # term ids are distinct
252
253     # make subreddit ids
254     subreddits = df.select(['subreddit']).distinct()
255     subreddits = subreddits.withColumn('subreddit_id',f.row_number().over(Window.orderBy("subreddit")))
256
257     df = df.join(subreddits,on='subreddit')
258
259     # map terms to indexes in the tfs and the idfs
260     df = df.join(terms,on=term) # subreddit-term-id is unique
261
262     idf = idf.join(terms,on=term)
263
264     # join on subreddit/term to create tf/dfs indexed by term
265     df = df.join(idf, on=[term_id, term])
266
267     # agg terms by subreddit to make sparse tf/df vectors
268     if tf_family == tf_weight.MaxTF:
269         df = df.withColumn("tf_idf",  df.relative_tf * df.idf)
270     else: # tf_fam = tf_weight.Norm05
271         df = df.withColumn("tf_idf",  (0.5 + 0.5 * df.relative_tf) * df.idf)
272
273     return df
274
275 def select_topN_subreddits(topN, path="/gscratch/comdata/output/reddit_similarity/subreddits_by_num_comments.csv"):
276     rankdf = pd.read_csv(path)
277     included_subreddits = set(rankdf.loc[rankdf.comments_rank <= topN,'subreddit'].values)
278     return included_subreddits

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