基于TextBlob简单文本情感分析

这里写图片描述

如果已经安装TextBlob,需要更新则需要运行:

$ pip install -U textblob nltk

如果第一次安装TextBlob,你可能需要下载必要的NLTK语料库。命令:

$ curl https://raw.github.com/sloria/TextBlob/master/download_corpora.py | python

使用此命令下载语料库:

$ >python -m textblob.download_corpora
  
  

    第1部分:一个Tweet情感分析器(简单分类)

    我们的第一个分类器将是一个简单的情感分析器训练的一个小数据集的假tweet。

    首先,我们将导入textblob.classifiers并创建一些训练和测试数据。

    from textblob.classifiers import NaiveBayesClassifier
    
    train = [
        ('I love this sandwich.', 'pos'),
        ('This is an amazing place!', 'pos'),
        ('I feel very good about these beers.', 'pos'),
        ('This is my best work.', 'pos'),
        ("What an awesome view", 'pos'),
        ('I do not like this restaurant', 'neg'),
        ('I am tired of this stuff.', 'neg'),
        ("I can't deal with this", 'neg'),
        ('He is my sworn enemy!', 'neg'),
        ('My boss is horrible.', 'neg')
    ]
    test = [
        ('The beer was good.', 'pos'),
        ('I do not enjoy my job', 'neg'),
        ("I ain't feeling dandy today.", 'neg'),
        ("I feel amazing!", 'pos'),
        ('Gary is a friend of mine.', 'pos'),
        ("I can't believe I'm doing this.", 'neg')
    ]
    
    

    我们通过将训练数据传递给NaiveBayesClassifier的构造函数来创建一个新的分类器。

    cl = NaiveBayesClassifier(train)

    我们现在可以使用NaiveBayesClassifier.classify(text)方法对任意文本进行分类。

    cl.classify("Their burgers are amazing")  # "pos"
    cl.classify("I don't like their pizza.")  # "neg"

    分类文本字符串的另一种方法是使用TextBlob对象。 您可以将分类器传递到TextBlob的构造函数中。

    from textblob import TextBlob
    blob = TextBlob("The beer was amazing. "
                    "But the hangover was horrible. My boss was not happy.",
                    classifier=cl)

    然后,可以在blob上调用classify()方法。

    blob.classify()  # "neg"

    还可以利用TextBlob句子标记化和单独分类每个句子。

    for sentence in blob.sentences:
        print(sentence)
        print(sentence.classify())
     "pos", "neg", "neg"

    检查测试集的准确性。

    cl.accuracy(test)
    # 0.83
      
      

      我们还可以找到最丰富的功能:

      cl.show_informative_features(5)
      # Most Informative Features
      #             contains(my) = True              neg : pos    =      1.7 : 1.0
      #             contains(an) = False             neg : pos    =      1.6 : 1.0
      #             contains(my) = False             pos : neg    =      1.3 : 1.0
      #          contains(place) = False             neg : pos    =      1.2 : 1.0
      #             contains(of) = False             pos : neg    =      1.2 : 1.0

      第2部分:从NLTK添加更多数据

      我们可以通过添加更多的训练和测试数据来改进我们的分类器。 在这里,我们将添加从NLTK下载的电影评论语料库的数据。

      import random
      from nltk.corpus import movie_reviews
      
      reviews = [(list(movie_reviews.words(fileid)), category)
                    for category in movie_reviews.categories()
                    for fileid in movie_reviews.fileids(category)]
      new_train, new_test = reviews[0:100], reviews[101:200]

      现在看看这些文档中的各个部分是什么含义。

      print(new_train[0])

      输出:

      (['kolya', 'is', 'one', 'of', 'the', 'richest', 'films', 'i', "'", 've', 'seen', 'in', 'some', 'time'
      , '.', 'zdenek', 'sverak', 'plays', 'a', 'confirmed', 'old', 'bachelor', '(', 'who', "'", 's', 'likel
      y', 'to', 'remain', 'so', ')', ',', 'who', 'finds', 'his', 'life', 'as', 'a', 'czech', 'cellist', 'in
      creasingly', 'impacted', 'by', 'the', 'five', '-', 'year', 'old', 'boy', 'that', 'he', "'", 's', 'tak
      ing', 'care', 'of', '.', 'though', 'it', 'ends', 'rather', 'abruptly', '--', 'and', 'i', "'", 'm', 'w
      hining', ',', "'", 'cause', 'i', 'wanted', 'to', 'spend', 'more', 'time', 'with', 'these', 'character
      s', '--', 'the', 'acting', ',', 'writing', ',', 'and', 'production', 'values', 'are', 'as', 'high', '
      as', ',', 'if', 'not', 'higher', 'than', ',', 'comparable', 'american', 'dramas', '.', 'this', 'fathe
      r', '-', 'and', '-', 'son', 'delight', '--', 'sverak', 'also', 'wrote', 'the', 'script', ',', 'while'
      , 'his', 'son', ',', 'jan', ',', 'directed', '--', 'won', 'a', 'golden', 'globe', 'for', 'best', 'for
      eign', 'language', 'film', 'and', ',', 'a', 'couple', 'days', 'after', 'i', 'saw', 'it', ',', 'walked
      ', 'away', 'an', 'oscar', '.', 'in', 'czech', 'and', 'russian', ',', 'with', 'english', 'subtitles',
      '.'], 'pos')

      请注意,与第1部分中的数据不同,文本以单词列表的形式出现,而不是单个字符串。 TextBlob是非常好的; 它将按预期处理这两种形式的数据。

      我们现在可以使用update(new_data)方法使用新的训练数据更新我们的分类器,以及使用更大的测试数据集进行测试。

      cl.update(new_train)
      accuracy = cl.accuracy(test + new_test)

      第3部分:语言检测器(自定义特征提取)

      我还没有提到的一个重要方面是如何从文本中提取要素。

      对于给定的文档和训练集训练,TextBlob的默认行为是计算列车中存在哪些单词。 例如,句子“这只是一个肉体的伤口。 可能有功能contains(flesh):True,contains(wound):True,并且包含(knight):False。

      当然,这个简单的特征提取器可能不适合于所有问题。 在这里,我们将为语言检测器创建一个自定义特征提取器。

      这里是训练和测试数据。

      train = [
          ("amor", "spanish"),
          ("perro", "spanish"),
          ("playa", "spanish"),
          ("sal", "spanish"),
          ("oceano", "spanish"),
          ("love", "english"),
          ("dog", "english"),
          ("beach", "english"),
          ("salt", "english"),
          ("ocean", "english")
      ]
      test = [
          ("ropa", "spanish"),
          ("comprar", "spanish"),
          ("camisa", "spanish"),
          ("agua", "spanish"),
          ("telefono", "spanish"),
          ("clothes", "english"),
          ("buy", "english"),
          ("shirt", "english"),
          ("water", "english"),
          ("telephone", "english")
      ]

      243/5000
      特征提取器只是一个函数,它接受参数文本(从中提取特征的文本)并返回特征字典。

      让我们创建一个非常简单的提取器,它使用给定单词的最后一个字母作为其唯一的特征。

      def extractor(word):
          feats = {}
          last_letter = word[-1]
          feats["last_letter({0})".format(last_letter)] = True
          return feats
      
      print(extractor("python"))  # {'last_letter(n)': True}

      我们可以将此特征提取器作为NaiveBayesClassifier的构造函数的第二个参数。

      lang_detector = NaiveBayesClassifier(train, feature_extractor=extractor)

      计算结果:

      lang_detector.accuracy(test)  # 0.7
      lang_detector.show_informative_features(5)
      # Most Informative Features
      #           last_letter(o) = None           englis : spanis =      1.6 : 1.0
      #           last_letter(l) = None           englis : spanis =      1.2 : 1.0
      #           last_letter(n) = None           spanis : englis =      1.2 : 1.0
      #           last_letter(h) = None           spanis : englis =      1.2 : 1.0
      #           last_letter(e) = None           spanis : englis =      1.2 : 1.0

      毫无疑问,不以字母“o”结尾的单词往往是英语。

      结论

      TextBlob使得创建自己的自定义文本分类器变得容易。 永远记住,机器学习不是那么容易,每一个问题都需要大量的实验。

      猜你喜欢

      转载自blog.csdn.net/Octal_H/article/details/83933377