Using wrappers for Scikit learn API

This tutorial is about using gensim models as a part of your scikit learn workflow with the help of wrappers found at gensim.sklearn_integration

The wrapper available (as of now) are :

  • LdaModel (gensim.sklearn_integration.sklearn_wrapper_gensim_ldaModel.SklearnWrapperLdaModel),which implements gensim's LdaModel in a scikit-learn interface

  • LsiModel (gensim.sklearn_integration.sklearn_wrapper_gensim_lsiModel.SklearnWrapperLsiModel),which implements gensim's LsiModel in a scikit-learn interface

LdaModel

To use LdaModel begin with importing LdaModel wrapper


In [1]:
from gensim.sklearn_integration.sklearn_wrapper_gensim_ldamodel import SklearnWrapperLdaModel

Next we will create a dummy set of texts and convert it into a corpus


In [2]:
from gensim.corpora import Dictionary
texts = [
    ['complier', 'system', 'computer'],
    ['eulerian', 'node', 'cycle', 'graph', 'tree', 'path'],
    ['graph', 'flow', 'network', 'graph'],
    ['loading', 'computer', 'system'],
    ['user', 'server', 'system'],
    ['tree', 'hamiltonian'],
    ['graph', 'trees'],
    ['computer', 'kernel', 'malfunction', 'computer'],
    ['server', 'system', 'computer']
]
dictionary = Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]

Then to run the LdaModel on it


In [3]:
model=SklearnWrapperLdaModel(num_topics=2, id2word=dictionary, iterations=20, random_state=1)
model.fit(corpus)
model.print_topics(2)
model.transform(corpus)


WARNING:gensim.models.ldamodel:too few updates, training might not converge; consider increasing the number of passes or iterations to improve accuracy
Out[3]:
array([[ 0.85275314,  0.14724686],
       [ 0.12390183,  0.87609817],
       [ 0.4612995 ,  0.5387005 ],
       [ 0.84924177,  0.15075823],
       [ 0.49180096,  0.50819904],
       [ 0.40086923,  0.59913077],
       [ 0.28454427,  0.71545573],
       [ 0.88776198,  0.11223802],
       [ 0.84210373,  0.15789627]])

Integration with Sklearn

To provide a better example of how it can be used with Sklearn, Let's use CountVectorizer method of sklearn. For this example we will use 20 Newsgroups data set. We will only use the categories rec.sport.baseball and sci.crypt and use it to generate topics.


In [4]:
import numpy as np
from gensim import matutils
from gensim.models.ldamodel import LdaModel
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
from gensim.sklearn_integration.sklearn_wrapper_gensim_ldamodel import SklearnWrapperLdaModel

In [5]:
rand = np.random.mtrand.RandomState(1) # set seed for getting same result
cats = ['rec.sport.baseball', 'sci.crypt']
data = fetch_20newsgroups(subset='train', categories=cats, shuffle=True)

Next, we use countvectorizer to convert the collection of text documents to a matrix of token counts.


In [6]:
vec = CountVectorizer(min_df=10, stop_words='english')

X = vec.fit_transform(data.data)
vocab = vec.get_feature_names()  # vocab to be converted to id2word 

id2word = dict([(i, s) for i, s in enumerate(vocab)])

Next, we just need to fit X and id2word to our Lda wrapper.


In [7]:
obj = SklearnWrapperLdaModel(id2word=id2word, num_topics=5, passes=20)
lda = obj.fit(X)
lda.print_topics()


Out[7]:
[(0,
  u'0.025*"456" + 0.021*"argue" + 0.016*"bitnet" + 0.015*"beastmaster" + 0.014*"cryptography" + 0.013*"false" + 0.012*"digex" + 0.011*"cover" + 0.011*"classified" + 0.010*"disk"'),
 (1,
  u'0.142*"abroad" + 0.113*"asking" + 0.088*"cryptography" + 0.044*"ciphertext" + 0.043*"arithmetic" + 0.032*"courtesy" + 0.030*"facts" + 0.021*"argue" + 0.019*"amolitor" + 0.018*"agree"'),
 (2,
  u'0.034*"certain" + 0.027*"69" + 0.025*"book" + 0.025*"demand" + 0.024*"87" + 0.024*"cracking" + 0.021*"farm" + 0.019*"fierkelab" + 0.015*"face" + 0.011*"abroad"'),
 (3,
  u'0.017*"decipher" + 0.017*"example" + 0.016*"cases" + 0.016*"follow" + 0.008*"considering" + 0.006*"forgot" + 0.006*"cellular" + 0.005*"evans" + 0.005*"computed" + 0.005*"cia"'),
 (4,
  u'0.022*"accurate" + 0.021*"corporate" + 0.013*"chance" + 0.012*"clark" + 0.009*"consideration" + 0.009*"candidates" + 0.008*"dawson" + 0.008*"authentication" + 0.008*"assess" + 0.008*"attempt"')]

In [8]:
from sklearn.model_selection  import GridSearchCV
from gensim.models.coherencemodel import CoherenceModel

In [9]:
def scorer(estimator, X, y=None):
    goodcm = CoherenceModel(model=estimator, texts= texts, dictionary=estimator.id2word, coherence='c_v')
    return goodcm.get_coherence()

In [10]:
obj = SklearnWrapperLdaModel(id2word=dictionary, num_topics=5, passes=20)
parameters = {'num_topics': (2, 3, 5, 10), 'iterations': (1, 20, 50)}
model = GridSearchCV(obj, parameters, scoring=scorer, cv=5)
model.fit(corpus)


Out[10]:
GridSearchCV(cv=5, error_score='raise',
       estimator=SklearnWrapperLdaModel(alpha='symmetric', chunksize=2000, corpus=None,
            decay=0.5, eta=None, eval_every=10, gamma_threshold=0.001,
            id2word=<gensim.corpora.dictionary.Dictionary object at 0x7f42ccbebd10>,
            iterations=50, minimum_probability=0.01, num_topics=5,
            offset=1.0, passes=20, random_state=None, update_every=1),
       fit_params={}, iid=True, n_jobs=1,
       param_grid={'num_topics': (2, 3, 5, 10), 'iterations': (1, 20, 50)},
       pre_dispatch='2*n_jobs', refit=True, return_train_score=True,
       scoring=<function scorer at 0x7f42cad12230>, verbose=0)

In [11]:
model.best_params_


Out[11]:
{'iterations': 20, 'num_topics': 3}

Example of Using Pipeline


In [12]:
from sklearn.pipeline import Pipeline
from sklearn import linear_model


def print_features_pipe(clf, vocab, n=10):
    ''' Better printing for sorted list '''
    coef = clf.named_steps['classifier'].coef_[0]
    print coef
    print 'Positive features: %s' % (' '.join(['%s:%.2f' % (vocab[j], coef[j]) for j in np.argsort(coef)[::-1][:n] if coef[j] > 0]))
    print 'Negative features: %s' % (' '.join(['%s:%.2f' % (vocab[j], coef[j]) for j in np.argsort(coef)[:n] if coef[j] < 0]))

In [13]:
id2word = Dictionary([_.split() for _ in data.data])
corpus = [id2word.doc2bow(i.split()) for i in data.data]

In [14]:
model = SklearnWrapperLdaModel(num_topics=15, id2word=id2word, iterations=50, random_state=37)
clf = linear_model.LogisticRegression(penalty='l2', C=0.1)  # l2 penalty used
pipe = Pipeline((('features', model,), ('classifier', clf)))
pipe.fit(corpus, data.target)
print_features_pipe(pipe, id2word.values())
print pipe.score(corpus, data.target)


WARNING:gensim.models.ldamodel:too few updates, training might not converge; consider increasing the number of passes or iterations to improve accuracy
[ -2.95020466e-01  -1.04115352e-01   5.19570267e-01   1.03817059e-01
   2.72881013e-02   1.35738501e-02   1.89246630e-13   1.89246630e-13
   1.89246630e-13   1.89246630e-13   1.89246630e-13   1.89246630e-13
   1.89246630e-13   1.89246630e-13   1.89246630e-13]
Positive features: Fame,:0.52 Keach:0.10 comp.org.eff.talk,:0.03 comp.org.eff.talk.:0.01 >Pat:0.00 dome.:0.00 internet...:0.00 trawling:0.00 hanging:0.00 red@redpoll.neoucom.edu:0.00
Negative features: Fame.:-0.30 considered,:-0.10
0.531040268456

LsiModel

To use LsiModel begin with importing LsiModel wrapper


In [15]:
from gensim.sklearn_integration.sklearn_wrapper_gensim_lsimodel import SklearnWrapperLsiModel

Example of Using Pipeline


In [16]:
model = SklearnWrapperLsiModel(num_topics=15, id2word=id2word)
clf = linear_model.LogisticRegression(penalty='l2', C=0.1)  # l2 penalty used
pipe = Pipeline((('features', model,), ('classifier', clf)))
pipe.fit(corpus, data.target)
print_features_pipe(pipe, id2word.values())
print pipe.score(corpus, data.target)


[ 0.13652819  0.00383696  0.02635504 -0.08454895 -0.02356143  0.60020084
  1.07026252 -0.04072257  0.43732847  0.54913549 -0.20242834 -0.21855402
 -1.30546283 -0.08690711  0.17606255]
Positive features: 01101001B:1.07 comp.org.eff.talk.:0.60 red@redpoll.neoucom.edu:0.55 circuitry:0.44 >Pat:0.18 Fame.:0.14 Fame,:0.03 considered,:0.00
Negative features: internet...:-1.31 trawling:-0.22 hanging:-0.20 dome.:-0.09 Keach:-0.08 *best*:-0.04 comp.org.eff.talk,:-0.02
0.865771812081