代码之家  ›  专栏  ›  技术社区  ›  Marc Maxmeister

在使用nltk训练了我自己的分类器之后,如何将其加载到textblob中?

  •  3
  • Marc Maxmeister  · 技术社区  · 7 年前

    textblob中的内置分类器相当愚蠢。它接受过电影评论方面的培训,所以我在自己的背景下创建了一组巨大的例子(57000个故事,分为正面或负面),然后用 nltk. 我试着用textblob来训练它,但总是失败:

    with open('train.json', 'r') as fp:
        cl = NaiveBayesClassifier(fp, format="json")
    

    这将运行数小时,并最终导致内存错误。

    我查看了源代码,发现它只是使用NLTK并包装它,所以我用它来代替,并且它起作用了。

    NLTK训练集的结构需要是一个元组列表,第一部分是文本中的单词计数器和出现频率。Tuple的第二部分是“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
    

    现在怎么办?我看了一下源代码,它们都是类,但并不完全相同。

    3 回复  |  直到 6 年前
        1
  •  0
  •   unholy_me    7 年前

    检查错误消息时,似乎必须从抽象类继承分析器 BaseSentimentAnalyzer . 如文件所述 here ,这节课 必须 实施 analyze(text) 功能。但是,在检查NLTK实现的文档时,我在它的主文档中找不到这个方法。 here 或者它的父类 ClassifierI here . 因此,我相信这两种实现都不能组合,除非您可以实现一个新的 analyze 函数在NLTK的实现中使其与textBlob兼容。

        2
  •  0
  •   Marc Maxmeister    7 年前

    我不能确定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代码在句子中对否定语言进行了更多的分析,以否定肯定词。就像达斯维德所说的“缺乏信仰”,这会改变人们的情绪。

    我在这里解释了它,并举例说明了更好的结果: 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
    

    这个 nltk http://www.nltk.org/howto/sentiment.html

        3
  •  0
  •   Marc Maxmeister    6 年前

    textblob nltk https://spacy.io/usage/spacy-101#section-lightning-tour

    import spacy
    import random
    
    nlp = spacy.load('en') # loads the trained starter model here
    train_data = [("Uber blew through $1 million", {'entities': [(0, 4, 'ORG')]})] # better model stuff
    
    with nlp.disable_pipes(*[pipe for pipe in nlp.pipe_names if pipe != 'ner']):
        optimizer = nlp.begin_training()
        for i in range(10):
            random.shuffle(train_data)
            for text, annotations in train_data:
                nlp.update([text], [annotations], sgd=optimizer)
    nlp.to_disk('/model')