1 from pyspark.sql import Window
2 from pyspark.sql import functions as f
4 from pyspark.mllib.linalg.distributed import CoordinateMatrix
5 from tempfile import TemporaryDirectory
7 import pyarrow.dataset as ds
8 from scipy.sparse import csr_matrix
13 class tf_weight(Enum):
17 def read_tfidf_matrix_weekly(path, term_colname, week):
19 term_id = term + '_id'
20 term_id_new = term + '_id_new'
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))))
26 def write_weekly_similarities(path, sims, week, names):
28 p = pathlib.Path(path)
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())
38 def read_tfidf_matrix(path,term_colname):
40 term_id = term + '_id'
41 term_id_new = term + '_id_new'
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))))
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)
54 def prep_tfidf_entries_weekly(tfidf, term_colname, min_df, included_subreddits):
56 term_id = term + '_id'
57 term_id_new = term + '_id_new'
60 min_df = 0.1 * len(included_subreddits)
62 tfidf = tfidf.filter(f.col("subreddit").isin(included_subreddits))
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'])
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')
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'])
78 tfidf = tfidf.withColumnRenamed("tf_idf","tf_idf_old")
79 tfidf = tfidf.withColumn("tf_idf", (tfidf.relative_tf * tfidf.idf).cast('float'))
81 tempdir =TemporaryDirectory(suffix='.parquet',prefix='term_tfidf_entries',dir='.')
83 tfidf = tfidf.repartition('week')
85 tfidf.write.parquet(tempdir.name,mode='overwrite',compression='snappy')
89 def prep_tfidf_entries(tfidf, term_colname, min_df, included_subreddits):
91 term_id = term + '_id'
92 term_id_new = term + '_id_new'
95 min_df = 0.1 * len(included_subreddits)
97 tfidf = tfidf.filter(f.col("subreddit").isin(included_subreddits))
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')
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')
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)
113 tfidf = tfidf.withColumnRenamed("tf_idf","tf_idf_old")
114 tfidf = tfidf.withColumn("tf_idf", (tfidf.relative_tf * tfidf.idf).cast('float'))
116 tempdir =TemporaryDirectory(suffix='.parquet',prefix='term_tfidf_entries',dir='.')
118 tfidf.write.parquet(tempdir.name,mode='overwrite',compression='snappy')
122 # try computing cosine similarities using spark
123 def spark_cosine_similarities(tfidf, term_colname, min_df, included_subreddits, similarity_threshold):
125 term_id = term + '_id'
126 term_id_new = term + '_id_new'
129 min_df = 0.1 * len(included_subreddits)
131 tfidf = tfidf.filter(f.col("subreddit").isin(included_subreddits))
132 tfidf = tfidf.cache()
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')
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')
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)
148 tfidf = tfidf.withColumnRenamed("tf_idf","tf_idf_old")
149 tfidf = tfidf.withColumn("tf_idf", tfidf.relative_tf * tfidf.idf)
151 # step 1 make an rdd of entires
152 # sorted by (dense) spark subreddit id
153 n_partitions = int(len(included_subreddits)*2 / 5)
155 entries = tfidf.select(f.col(term_id_new)-1,f.col("subreddit_id_new")-1,"tf_idf").rdd.repartition(n_partitions)
157 # put like 10 subredis in each partition
159 # step 2 make it into a distributed.RowMatrix
160 coordMat = CoordinateMatrix(entries)
162 coordMat = CoordinateMatrix(coordMat.entries.repartition(n_partitions))
164 # this needs to be an IndexedRowMatrix()
165 mat = coordMat.toRowMatrix()
167 #goal: build a matrix of subreddit columns and tf-idfs rows
168 sim_dist = mat.columnSimilarities(threshold=similarity_threshold)
170 return (sim_dist, tfidf)
173 def build_weekly_tfidf_dataset(df, include_subs, term_colname, tf_family=tf_weight.Norm05):
175 term_id = term + '_id'
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'))
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)
186 # group by term. term is unique
187 idf = df.groupby([term,'week']).count()
189 N_docs = df.select(['subreddit','week']).distinct().groupby(['week']).agg(f.count("subreddit").alias("subreddits_in_week"))
191 idf = idf.join(N_docs, on=['week'])
193 # add a little smoothing to the idf
194 idf = idf.withColumn('idf',f.log(idf.subreddits_in_week) / (1+f.col('count'))+1)
196 # collect the dictionary to make a pydict of terms to indexes
197 terms = idf.select([term,'week']).distinct() # terms are distinct
199 terms = terms.withColumn(term_id,f.row_number().over(Window.partitionBy('week').orderBy(term))) # term ids are distinct
202 subreddits = df.select(['subreddit','week']).distinct()
203 subreddits = subreddits.withColumn('subreddit_id',f.row_number().over(Window.partitionBy("week").orderBy("subreddit")))
205 df = df.join(subreddits,on=['subreddit','week'])
207 # map terms to indexes in the tfs and the idfs
208 df = df.join(terms,on=[term,'week']) # subreddit-term-id is unique
210 idf = idf.join(terms,on=[term,'week'])
212 # join on subreddit/term to create tf/dfs indexed by term
213 df = df.join(idf, on=[term_id, term,'week'])
215 # agg terms by subreddit to make sparse tf/df vectors
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)
226 def build_tfidf_dataset(df, include_subs, term_colname, tf_family=tf_weight.Norm05):
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'))
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')
237 df = df.join(max_subreddit_terms, on='subreddit')
239 df = df.withColumn("relative_tf", df.tf / df.sr_max_tf)
241 # group by term. term is unique
242 idf = df.groupby([term]).count()
244 N_docs = df.select('subreddit').distinct().count()
246 # add a little smoothing to the idf
247 idf = idf.withColumn('idf',f.log(N_docs/(1+f.col('count')))+1)
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
254 subreddits = df.select(['subreddit']).distinct()
255 subreddits = subreddits.withColumn('subreddit_id',f.row_number().over(Window.orderBy("subreddit")))
257 df = df.join(subreddits,on='subreddit')
259 # map terms to indexes in the tfs and the idfs
260 df = df.join(terms,on=term) # subreddit-term-id is unique
262 idf = idf.join(terms,on=term)
264 # join on subreddit/term to create tf/dfs indexed by term
265 df = df.join(idf, on=[term_id, term])
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)
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