我正在使用TextBlob对python做一些关于tweet的情感分析。TextBlob中默认的分析器是PatternAnalyzer,它工作得很好,速度也非常快。
sent = TextBlob(tweet.decode('utf-8')).sentiment现在,我尝试切换到NaiveBayesAnalyzer,发现运行时对于我的需要是不切实际的。(每条推特接近5秒)
sent = TextBlob(tweet.decode('utf-8'), analyzer=NaiveBayesAnalyzer()).sentiment我以前使用过scikit学习实现朴素贝叶斯分类器,并没有发现它是如此缓慢,所以我想知道我是否正确地在这个例子中使用它。
我假设分析器是预先训练的,至少文献资料状态是“朴素的贝叶斯分析器,它是根据电影评论的数据集训练的。”但是它也有一个函数train(),它被描述为“在电影评论语料库上训练朴素贝叶斯分类器”。它是否在每次运行前对分析器进行内部培训?我真希望不是这样。
有谁知道加速这件事的方法吗?
发布于 2015-10-27 05:14:50
是的,Textblob会在每次运行之前训练分析器。您可以使用下面的代码,以避免每次训练分析器。
from textblob import Blobber
from textblob.sentiments import NaiveBayesAnalyzer
tb = Blobber(analyzer=NaiveBayesAnalyzer())
print tb("sentence you want to test")发布于 2021-01-22 18:11:48
添加到Alan的非常有用的答案中,如果数据中有表数据,并且希望使用textblob的NaiveBayesAnalyzer,那么这是可行的。只需为相关的字符串系列更改word_list即可。
import textblob
import pandas as pd
tb = textblob.Blobber(analyzer=NaiveBayesAnalyzer())
for index, row in df.iterrows():
sent = tb(row['word_list']).sentiment
df.loc[index, 'classification'] = sent[0]
df.loc[index, 'p_pos'] = sent[1]
df.loc[index, 'p_neg'] = sent[2]上面将sentiment返回的元组拆分为三个单独的系列。
如果这个系列都是字符串,但是如果它有混合的数据类型,这是可行的,因为object数据类型在熊猫中是个问题,那么您可能需要在它周围放置一个try/ put块来捕获异常。
在我的测试中,它可以在4.7秒内完成1000行。
希望这会有帮助。
发布于 2022-11-02 14:24:25
除了上述解决方案之外,我还尝试了上述解决方案,并遇到了错误,因此,如果有人发现了这个问题,我就解决了这些错误,并尝试使用以下代码中的PatternAnalyzer:
from textblob import Blobber
from textblob.sentiments import NaiveBayesAnalyzer, PatternAnalyzer
import nltk
nltk.download('punkt')
nltk.download('movie_reviews')
tb = Blobber(analyzer=NaiveBayesAnalyzer())
tb1 = Blobber(analyzer=PatternAnalyzer())
print(tb("sentence you want to test").sentiment)
print(tb1("sentence you want to test").sentiment)
print(tb("I love the book").sentiment)
print(tb1("I love the book").sentiment)https://stackoverflow.com/questions/33241842
复制相似问题