]> code.communitydata.science - cdsc_reddit.git/blob - similarities_helper.py
c69983f7f9b027d0e08903731052673fe23489d5
[cdsc_reddit.git] / 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
6 class tf_weight(Enum):
7     MaxTF = 1
8     Norm05 = 2
9
10
11 def cosine_similarities(tfidf, term_colname, min_df, included_subreddits, similarity_threshold):
12     term = term_colname
13     term_id = term + '_id'
14     term_id_new = term + '_id_new'
15
16     if min_df is None:
17         min_df = 0.1 * len(included_subreddits)
18
19     tfidf = tfidf.filter(f.col("subreddit").isin(included_subreddits))
20     tfidf = tfidf.cache()
21
22     # reset the subreddit ids
23     sub_ids = tfidf.select('subreddit_id').distinct()
24     sub_ids = sub_ids.withColumn("subreddit_id_new",f.row_number().over(Window.orderBy("subreddit_id")))
25     tfidf = tfidf.join(sub_ids,'subreddit_id')
26
27     # only use terms in at least min_df included subreddits
28     new_count = tfidf.groupBy(term_id).agg(f.count(term_id).alias('new_count'))
29 #    new_count = new_count.filter(f.col('new_count') >= min_df)
30     tfidf = tfidf.join(new_count,term_id,how='inner')
31     
32     # reset the term ids
33     term_ids = tfidf.select([term_id]).distinct()
34     term_ids = term_ids.withColumn(term_id_new,f.row_number().over(Window.orderBy(term_id)))
35     tfidf = tfidf.join(term_ids,term_id)
36
37     tfidf = tfidf.withColumnRenamed("tf_idf","tf_idf_old")
38     # tfidf = tfidf.withColumnRenamed("idf","idf_old")
39     # tfidf = tfidf.withColumn("idf",f.log(25000/f.col("count")))
40     tfidf = tfidf.withColumn("tf_idf", tfidf.relative_tf * tfidf.idf)
41
42     # step 1 make an rdd of entires
43     # sorted by (dense) spark subreddit id
44     #    entries = tfidf.filter((f.col('subreddit') == 'asoiaf') | (f.col('subreddit') == 'gameofthrones') | (f.col('subreddit') == 'christianity')).select(f.col("term_id_new")-1,f.col("subreddit_id_new")-1,"tf_idf").rdd
45  
46     n_partitions = int(len(included_subreddits)*2 / 5)
47
48     entries = tfidf.select(f.col(term_id_new)-1,f.col("subreddit_id_new")-1,"tf_idf").rdd.repartition(n_partitions)
49
50     # put like 10 subredis in each partition
51
52     # step 2 make it into a distributed.RowMatrix
53     coordMat = CoordinateMatrix(entries)
54
55     coordMat = CoordinateMatrix(coordMat.entries.repartition(n_partitions))
56
57     # this needs to be an IndexedRowMatrix()
58     mat = coordMat.toRowMatrix()
59
60     #goal: build a matrix of subreddit columns and tf-idfs rows
61     sim_dist = mat.columnSimilarities(threshold=similarity_threshold)
62
63     return (sim_dist, tfidf)
64
65
66 def build_tfidf_dataset(df, include_subs, term_colname, tf_family=tf_weight.Norm05):
67
68     term = term_colname
69     term_id = term + '_id'
70     # aggregate counts by week. now subreddit-term is distinct
71     df = df.filter(df.subreddit.isin(include_subs))
72     df = df.groupBy(['subreddit',term]).agg(f.sum('tf').alias('tf'))
73
74     max_subreddit_terms = df.groupby(['subreddit']).max('tf') # subreddits are unique
75     max_subreddit_terms = max_subreddit_terms.withColumnRenamed('max(tf)','sr_max_tf')
76
77     df = df.join(max_subreddit_terms, on='subreddit')
78
79     df = df.withColumn("relative_tf", df.tf / df.sr_max_tf)
80
81     # group by term. term is unique
82     idf = df.groupby([term]).count()
83
84     N_docs = df.select('subreddit').distinct().count()
85
86     # add a little smoothing to the idf
87     idf = idf.withColumn('idf',f.log(N_docs/(1+f.col('count')))+1)
88
89     # collect the dictionary to make a pydict of terms to indexes
90     terms = idf.select(term).distinct() # terms are distinct
91     terms = terms.withColumn(term_id,f.row_number().over(Window.orderBy(term))) # term ids are distinct
92
93     # make subreddit ids
94     subreddits = df.select(['subreddit']).distinct()
95     subreddits = subreddits.withColumn('subreddit_id',f.row_number().over(Window.orderBy("subreddit")))
96
97     df = df.join(subreddits,on='subreddit')
98
99     # map terms to indexes in the tfs and the idfs
100     df = df.join(terms,on=term) # subreddit-term-id is unique
101
102     idf = idf.join(terms,on=term)
103
104     # join on subreddit/term to create tf/dfs indexed by term
105     df = df.join(idf, on=[term_id, term])
106
107     # agg terms by subreddit to make sparse tf/df vectors
108     
109     if tf_family == tf_weight.MaxTF:
110         df = df.withColumn("tf_idf",  df.relative_tf * df.idf)
111     else: # tf_fam = tf_weight.Norm05
112         df = df.withColumn("tf_idf",  (0.5 + 0.5 * df.relative_tf) * df.idf)
113
114     return df
115
116

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