textblob 中的内置分类器非常愚蠢。它是根据电影评论进行训练的,因此我在我的上下文中创建了大量示例(57,000 个故事,分为正面或负面),然后使用 nltk 对其进行训练。
我尝试使用 textblob 来训练它,但它总是失败:
with open('train.json', 'r') as fp:
cl = NaiveBayesClassifier(fp, format="json")
这将运行几个小时并以内存错误结束。
我查看了源代码,发现它只是使用 nltk 并对其进行包装,因此我使用了它,并且它有效。
nltk 训练集的结构需要是一个元组列表,第一部分是文本中单词和出现频率的计数器。元组的第二部分是表示情绪的“pos”或“neg”。
>>> train_set = [(Counter(i["text"].split()),i["label"]) for i in data[200:]]
>>> test_set = [(Counter(i["text"].split()),i["label"]) for i in data[:200]] # withholding 200 examples for testing later
>>> cl = nltk.NaiveBayesClassifier.train(train_set) # <-- this is the same thing textblob was using
>>> print("Classifier accuracy percent:",(nltk.classify.accuracy(cl, test_set))*100)
('Classifier accuracy percent:', 66.5)
>>>>cl.show_most_informative_features(75)
然后我腌制它。
with open('storybayes.pickle','wb') as f:
pickle.dump(cl,f)
现在...我拿起这个腌制文件,重新打开它以获取 nltk.classifier 'nltk.classify.naivebayes.NaiveBayesClassifier'> - 并尝试将其输入到 textblob 中。而不是
from textblob.classifiers import NaiveBayesClassifier
blob = TextBlob("I love this library", analyzer=NaiveBayesAnalyzer())
我尝试过:
blob = TextBlob("I love this library", analyzer=myclassifier)
Traceback (most recent call last):
File "<pyshell#116>", line 1, in <module>
blob = TextBlob("I love this library", analyzer=cl4)
File "C:\python\lib\site-packages\textblob\blob.py", line 369, in __init__
parser, classifier)
File "C:\python\lib\site-packages\textblob\blob.py", line 323, in
_initialize_models
BaseSentimentAnalyzer, BaseBlob.analyzer)
File "C:\python\lib\site-packages\textblob\blob.py", line 305, in
_validated_param
.format(name=name, cls=base_class_name))
ValueError: analyzer must be an instance of BaseSentimentAnalyzer
现在怎么办?我查看了源代码,两者都是类,但并不完全相同。
最佳答案
我无法确定 nltk 语料库不能与 textblob 一起使用,这会让我感到惊讶,因为 textblob 在其源代码中导入了所有 nltk 函数,并且基本上是一个包装器。
但经过多个小时的测试后我得出的结论是,nltk 提供了一个更好的内置情感语料库,称为“vader”,它的性能优于我所有训练过的模型。
import nltk
nltk.download('vader_lexicon') # do this once: grab the trained model from the web
from nltk.sentiment.vader import SentimentIntensityAnalyzer
Analyzer = SentimentIntensityAnalyzer()
Analyzer.polarity_scores("I find your lack of faith disturbing.")
{'neg': 0.491, 'neu': 0.263, 'pos': 0.246, 'compound': -0.4215}
CONCLUSION: NEGATIVE
vader_lexicon
和 nltk 代码对句子中的否定语言进行更多解析,以否定肯定词。就像达斯·维德(Darth Vader)说“缺乏信仰”时,将情绪转向相反的方向一样。
我在这里解释了它,并举例说明了更好的结果: https://chewychunks.wordpress.com/2018/06/19/sentiment-analysis-discovering-the-best-way-to-sort-positive-and-negative-feedback/
它取代了这个 textblob 实现:
from textblob import TextBlob
from textblob.sentiments import NaiveBayesAnalyzer
TextBlob("I find your lack of faith disturbing.", analyzer=NaiveBayesAnalyzer())
{'neg': 0.182, 'pos': 0.817, 'combined': 0.635}
CONCLUSION: POSITIVE
vader nltk
分类器这里还有关于使用它进行情感分析的附加文档:http://www.nltk.org/howto/sentiment.html
textBlob 总是因为只有 5000 个示例而导致我的计算机崩溃。
关于python - 使用 nltk 训练我自己的分类器后,如何将其加载到 textblob 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50828262/