【发布时间】:2010-06-20 21:42:43
【问题描述】:
我正在尝试创建我发现的文本分类代码的多处理版本here(以及其他很酷的东西)。我在下面附加了完整的代码。
我已经尝试了几件事 - 首先尝试了一个 lambda 函数,但它抱怨无法序列化(!?),所以尝试了原始代码的精简版本:
negids = movie_reviews.fileids('neg')
posids = movie_reviews.fileids('pos')
p = Pool(2)
negfeats =[]
posfeats =[]
for f in negids:
words = movie_reviews.words(fileids=[f])
negfeats = p.map(featx, words) #not same form as below - using for debugging
print len(negfeats)
不幸的是,即使这也不起作用 - 我得到以下跟踪:
File "/usr/lib/python2.6/multiprocessing/pool.py", line 148, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/lib/python2.6/multiprocessing/pool.py", line 422, in get
raise self._value
ZeroDivisionError: float division
知道我可能做错了什么吗?我应该改用pool.apply_async 吗(这本身似乎也不能解决问题 - 但也许我在叫错树)?
import collections
import nltk.classify.util, nltk.metrics
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import movie_reviews
def evaluate_classifier(featx):
negids = movie_reviews.fileids('neg')
posids = movie_reviews.fileids('pos')
negfeats = [(featx(movie_reviews.words(fileids=[f])), 'neg') for f in negids]
posfeats = [(featx(movie_reviews.words(fileids=[f])), 'pos') for f in posids]
negcutoff = len(negfeats)*3/4
poscutoff = len(posfeats)*3/4
trainfeats = negfeats[:negcutoff] + posfeats[:poscutoff]
testfeats = negfeats[negcutoff:] + posfeats[poscutoff:]
classifier = NaiveBayesClassifier.train(trainfeats)
refsets = collections.defaultdict(set)
testsets = collections.defaultdict(set)
for i, (feats, label) in enumerate(testfeats):
refsets[label].add(i)
observed = classifier.classify(feats)
testsets[observed].add(i)
print 'accuracy:', nltk.classify.util.accuracy(classifier, testfeats)
print 'pos precision:', nltk.metrics.precision(refsets['pos'], testsets['pos'])
print 'pos recall:', nltk.metrics.recall(refsets['pos'], testsets['pos'])
print 'neg precision:', nltk.metrics.precision(refsets['neg'], testsets['neg'])
print 'neg recall:', nltk.metrics.recall(refsets['neg'], testsets['neg'])
classifier.show_most_informative_features()
【问题讨论】:
标签: python multithreading multicore