-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathword2vec.py
74 lines (58 loc) · 2.04 KB
/
word2vec.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
__author__ = 'hanhanw'
import sys
from pyspark import SparkConf, SparkContext
from pyspark.sql.context import SQLContext
from pyspark.mllib.feature import Word2Vec
import nltk
import string
import json
conf = SparkConf().setAppName("733 A2 Q4")
sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)
assert sc.version >= '1.5.1'
inputs = sys.argv[1]
model_output = sys.argv[2]
similar_words_output = sys.argv[3]
def clean_review(review_line):
pyline = json.loads(review_line)
review_text = str(pyline['reviewText'])
replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))
review_text = review_text.translate(replace_punctuation).split()
review_words = [w.lower() for w in review_text]
return review_words
def generate_word2vec_model(doc):
return Word2Vec().setVectorSize(10).setSeed(42).fit(doc)
def get_similar_words(model, word, output_num):
st = model.findSynonyms(word, output_num)
outstr = 'similiar words for ' + word + ': '
for i in range(len(st)):
outstr += '(' + str(st[i][0]) + ', ' + str(st[i][1]) + '), '
return outstr
def main():
text = sc.textFile(inputs)
nltk_data_path = "[change to your nltk_data location]" # maybe changed to the sfu server path
nltk.data.path.append(nltk_data_path)
cleaned_review = text.map(clean_review)
model = generate_word2vec_model(cleaned_review)
mv = model.getVectors()
# find similar words
similar_words = []
test_words = ['dog', 'happy']
outnum = 2
for w in test_words:
outstr = get_similar_words(model, w, outnum)
similar_words.append(outstr)
# save the model
results = []
for k,v in mv.items():
tmp_str = str(k) + ',['
for f in v:
tmp_str += str(f) + ', '
tmp_str += ']'
results.append(tmp_str)
outmodel = sc.parallelize(results)
out_similarwords = sc.parallelize(similar_words)
outmodel.saveAsTextFile(model_output)
out_similarwords.saveAsTextFile(similar_words_output)
if __name__ == '__main__':
main()