]> code.communitydata.science - cdsc_reddit.git/blob - idf_comments.py
d29be80d9dcf4ec832eebaec09ad12f4c61d57e1
[cdsc_reddit.git] / idf_comments.py
1 from pyspark.sql import functions as f
2 from pyspark.sql import SparkSession
3
4 spark = SparkSession.builder.getOrCreate()
5 df = spark.read.parquet("/gscratch/comdata/users/nathante/reddit_tfidf_test.parquet_temp")
6
7 max_subreddit_week_terms = df.groupby(['subreddit','week']).max('tf')
8 max_subreddit_week_terms = max_subreddit_week_terms.withColumnRenamed('max(tf)','sr_week_max_tf')
9
10 df = df.join(max_subreddit_week_terms, ['subreddit','week'])
11
12 df = df.withColumn("relative_tf", df.tf / df.sr_week_max_tf)
13
14 # group by term / week
15 idf = df.groupby(['term','week']).count()
16
17 idf = idf.withColumnRenamed('count','idf')
18
19 # output: term | week | df
20 #idf.write.parquet("/gscratch/comdata/users/nathante/reddit_tfidf_test_sorted_tf.parquet_temp",mode='overwrite',compression='snappy')
21
22 # collect the dictionary to make a pydict of terms to indexes
23 terms = idf.select('term').distinct()
24 terms = terms.withColumn('term_id',f.monotonically_increasing_id())
25
26
27 # print('collected terms')
28
29 # terms = [t.term for t in terms]
30 # NTerms = len(terms)
31 # term_id_map = {term:i for i,term in enumerate(sorted(terms))}
32
33 # term_id_map = spark.sparkContext.broadcast(term_id_map)
34
35 # print('term_id_map is broadcasted')
36
37 # def map_term(x):
38 #     return term_id_map.value[x]
39
40 # map_term_udf = f.udf(map_term)
41
42 # map terms to indexes in the tfs and the idfs
43 df = df.join(terms,on='term')
44
45 idf = idf.join(terms,on='term')
46
47 # join on subreddit/term/week to create tf/dfs indexed by term
48 df = df.join(idf, on=['term_id','week','term'])
49
50 # agg terms by subreddit to make sparse tf/df vectors
51 df = df.withColumn("tf_idf",df.relative_tf / df.sr_week_max_tf)
52
53 df = df.groupby(['subreddit','week']).agg(f.collect_list(f.struct('term_id','tf_idf')).alias('tfidf_maps'))
54  
55 df = df.withColumn('tfidf_vec', f.map_from_entries('tfidf_maps'))
56
57 # output: subreddit | week | tf/df
58 df.write.parquet('/gscratch/comdata/users/nathante/test_tfidf.parquet',mode='overwrite',compression='snappy')

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