I'm trying to build a Tf-Idf model that can score bigrams as well as unigrams using gensim. To do this, I build a gensim dictionary and then use that dictionary to create bag-of-word representations of the corpus that I use to build the model.
The step to build the dictionary looks like this:
dict = gensim.corpora.Dictionary(tokens)
where token
is a list of unigrams and bigrams like this:
[('restore',),
('diversification',),
('made',),
('transport',),
('The',),
('grass',),
('But',),
('distinguished', 'newspaper'),
('came', 'well'),
('produced',),
('car',),
('decided',),
('sudden', 'movement'),
('looking', 'glasses'),
('shapes', 'replaced'),
('beauties',),
('put',),
('college', 'days'),
('January',),
('sometimes', 'gives')]
However, when I provide a list such as this to gensim.corpora.Dictionary()
, the algorithm reduces all tokens to bigrams, e.g.:
test = gensim.corpora.Dictionary([(('happy', 'dog'))])
[test[id] for id in test]
=> ['dog', 'happy']
Is there a way to generate a dictionary with gensim that includes bigrams?
from gensim.models import Phrases
from gensim.models.phrases import Phraser
from gensim import models
docs = ['new york is is united states', 'new york is most populated city in the world','i love to stay in new york']
token_ = [doc.split(" ") for doc in docs]
bigram = Phrases(token_, min_count=1, threshold=2,delimiter=b' ')
bigram_phraser = Phraser(bigram)
bigram_token = []
for sent in token_:
bigram_token.append(bigram_phraser[sent])
output will be : [['new york', 'is', 'is', 'united', 'states'],['new york', 'is', 'most', 'populated', 'city', 'in', 'the', 'world'],['i', 'love', 'to', 'stay', 'in', 'new york']]
#now you can make dictionary of bigram token
dict_ = gensim.corpora.Dictionary(bigram_token)
print(dict_.token2id)
#Convert the word into vector, and now you can use tfidf model from gensim
corpus = [dict_.doc2bow(text) for text in bigram_token]
tfidf_model = models.TfidfModel(corpus)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With