sklearn:如何加速矢量化器(例如Tfidfvectorizer)

时间:2014-10-04 18:12:35

标签: python scikit-learn nltk

在仔细分析了我的程序之后,我已经能够确定它被矢量化程序放慢了速度。

我正在处理文本数据,两行简单的tfidf unigram矢量化占用了代码执行总时间的99.2%。

这是一个可运行的示例(这会将3mb培训文件下载到您的磁盘上,省略在您自己的样本上运行的urllib部分):

#####################################
# Loading Data
#####################################
import urllib
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk.stem  
raw = urllib.urlopen("https://s3.amazonaws.com/hr-testcases/597/assets/trainingdata.txt").read()
file = open("to_delete.txt","w").write(raw)
###
def extract_training():
    f = open("to_delete.txt")
    N = int(f.readline())
    X = []
    y = []
    for i in xrange(N):
        line  = f.readline()
        label,text =  int(line[0]), line[2:]
        X.append(text)
        y.append(label)
    return X,y
X_train, y_train =  extract_training()    
#############################################
# Extending Tfidf to have only stemmed features
#############################################
english_stemmer = nltk.stem.SnowballStemmer('english')

class StemmedTfidfVectorizer(TfidfVectorizer):
    def build_analyzer(self):
        analyzer = super(TfidfVectorizer, self).build_analyzer()
        return lambda doc: (english_stemmer.stem(w) for w in analyzer(doc))

tfidf = StemmedTfidfVectorizer(min_df=1, stop_words='english', analyzer='word', ngram_range=(1,1))
#############################################
# Line below takes 6-7 seconds on my machine
#############################################
Xv = tfidf.fit_transform(X_train) 

我尝试将列表X_train转换为np.array,但性能没有差异。

1 个答案:

答案 0 :(得分:15)

不出所料,它的NLTK很慢:

>>> tfidf = StemmedTfidfVectorizer(min_df=1, stop_words='english', analyzer='word', ngram_range=(1,1))
>>> %timeit tfidf.fit_transform(X_train)
1 loops, best of 3: 4.89 s per loop
>>> tfidf = TfidfVectorizer(min_df=1, stop_words='english', analyzer='word', ngram_range=(1,1))
>>> %timeit tfidf.fit_transform(X_train)
1 loops, best of 3: 415 ms per loop

您可以通过使用更智能的Snowball词干分析器来加快速度,例如PyStemmer

>>> import Stemmer
>>> english_stemmer = Stemmer.Stemmer('en')
>>> class StemmedTfidfVectorizer(TfidfVectorizer):
...     def build_analyzer(self):
...         analyzer = super(TfidfVectorizer, self).build_analyzer()
...         return lambda doc: english_stemmer.stemWords(analyzer(doc))
...     
>>> tfidf = StemmedTfidfVectorizer(min_df=1, stop_words='english', analyzer='word', ngram_range=(1,1))
>>> %timeit tfidf.fit_transform(X_train)
1 loops, best of 3: 650 ms per loop

NLTK是一个教学工具包。它的设计很慢,因为它的可读性已得到优化。