Word2vec when run on large text corpus, automatically captures relationships and similarities in text data. For example, if you ask Germany capital, it will say Berlin. Word2vec generates vectors for each word and a simple cosine of the vector, shows how close two words are.
I will be using hillary emails text corpus from kaggle as input and we will observe some interesting results. I will use the native c code of word2vec for speed. First we clean the raw data and remove some common english stop words.
Hillary data comes in sqllite and from this command we dump rawtext field from database into a file.
sqlite3 -header -csv database.sqlite "select RawText from Emails;" > rawtext.csv
We clean up text and only allow certain alpha numeric characters using sed (much faster).
tr -c "A-Za-z0-9@-._ \n" " " < rawtext.txt > rawfiltered.txt
Here we translate all uppercase to lowercase
tr '[:upper:]' '[:lower:]' < rawfiltered.txt > data.txt
This perl script will remove common english stopwords from the text corpus
./remove.pl stopwords.txt sample.txt
Once all is ready we run word2vec to generate word vectors in commandline
./word2vec -train data.phrase -output hillary-vectors.bin -cbow 1 -size 300 -window 10 -negative 25 -hs 0 -sample 1e-5 -threads 20 -binary 1 -iter 15
This will generate only word vectors, not efficient for phrases. To generate vectors for phrases use this other approach.
./word2phrase -train data.cleaned -output data.phrase0 -threshold 200 -debug 2 ./word2phrase -train data.cleaned -output data.phrase1 -threshold 100 -debug 2 ./word2vec -train data.phrase1 -output hillary-vectors-phrase.bin -cbow 1 -size 200 -window 10 -negative 25 -hs 0 -sample 1e-5 -threads 20 -binary 1 -iter 15
This will take few minutes, after that use the cosine distance tool to play with it. ./distance vectors-phrase.bin
Let us see the results..
|Position in vocabulary: 255|
|Word Cosine distance\|
|Observations: Top 3 results are truly spectacular since the the vectors automatically capture the relationships from the corpus. Rodham is i suppose middle name and clinton last name when asked about hillary. The secretary is also captured in top results. Her blackberry email is also on top results. Hillary must love her blackberry a lot :J\|
Let us see how clustering works on the vectors. We will cluster 5 topics from the dataset..
./word2vec -train data.cleaned -output hillary-classes.txt -cbow 1 -size 200 -window 8 -negative 25 -hs 0 -sample 1e-4 -threads 20 -iter 15 -classes 20
sort hillary-classes.txt -k 2 -n > hillary.sorted.txt
You will see words grouped into clusters.
Founder of Corpocrat Magazine and World’s leading expert in citizenship and residence by investment schemes assisting wealthy individuals and families. He is the founder Best Citizenships (BC), CIP Journal and World Citizenship Council (WCC) .
Other interests include Linux servers, Machine learning, Blockchain and Cryptocurrencies.