情感分析——深入snownlp原理和实践

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/google19890102/article/details/80091502

一、snownlp简介

snownlp是什么?

SnowNLP是一个python写的类库,可以方便的处理中文文本内容,是受到了TextBlob的启发而写的,由于现在大部分的自然语言处理库基本都是针对英文的,于是写了一个方便处理中文的类库,并且和TextBlob不同的是,这里没有用NLTK,所有的算法都是自己实现的,并且自带了一些训练好的字典。注意本程序都是处理的unicode编码,所以使用时请自行decode成unicode。

以上是官方对snownlp的描述,简单地说,snownlp是一个中文的自然语言处理的Python库,支持的中文自然语言操作包括:

  • 中文分词
  • 词性标注
  • 情感分析
  • 文本分类
  • 转换成拼音
  • 繁体转简体
  • 提取文本关键词
  • 提取文本摘要
  • tf,idf
  • Tokenization
  • 文本相似

在本文中,将重点介绍snownlp中的情感分析(Sentiment Analysis)。

二、snownlp情感分析模块的使用

2.1、snownlp库的安装

snownlp的安装方法如下:

pip install snownlp

2.2、使用snownlp情感分析

利用snownlp进行情感分析的代码如下所示:

#coding:UTF-8
import sys
from snownlp import SnowNLP

def read_and_analysis(input_file, output_file):
  f = open(input_file)
  fw = open(output_file, "w")
  while True:
    line = f.readline()
    if not line:
      break
    lines = line.strip().split("\t")
    if len(lines) < 2:
      continue

    s = SnowNLP(lines[1].decode('utf-8'))
    # s.words 查询分词结果
    seg_words = ""
    for x in s.words:
      seg_words += "_"
      seg_words += x
    # s.sentiments 查询最终的情感分析的得分
    fw.write(lines[0] + "\t" + lines[1] + "\t" + seg_words.encode('utf-8') + "\t" + str(s.sentiments) + "\n")
  fw.close()
  f.close()

if __name__ == "__main__":
  input_file = sys.argv[1]
  output_file = sys.argv[2]
  read_and_analysis(input_file, output_file)

上述代码会从文件中读取每一行的文本,并对其进行情感分析并输出最终的结果。

注:库中已经训练好的模型是基于商品的评论数据,因此,在实际使用的过程中,需要根据自己的情况,重新训练模型。

2.3、利用新的数据训练情感分析模型

在实际的项目中,需要根据实际的数据重新训练情感分析的模型,大致分为如下的几个步骤:

  • 准备正负样本,并分别保存,如正样本保存到pos.txt,负样本保存到neg.txt
  • 利用snownlp训练新的模型
  • 保存好新的模型

重新训练情感分析的代码如下所示:

#coding:UTF-8

from snownlp import sentiment

if __name__ == "__main__":
  # 重新训练模型
  sentiment.train('./neg.txt', './pos.txt')
  # 保存好新训练的模型
  sentiment.save('sentiment.marshal')

注意:若是想要利用新训练的模型进行情感分析,需要修改代码中的调用模型的位置。

data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'sentiment.marshal')

三、snownlp情感分析的源码解析

snownlp中支持情感分析的模块在sentiment文件夹中,其核心代码为__init__.py

如下是Sentiment类的代码:

class Sentiment(object):

    def __init__(self):
        self.classifier = Bayes() # 使用的是Bayes的模型

    def save(self, fname, iszip=True):
        self.classifier.save(fname, iszip) # 保存最终的模型

    def load(self, fname=data_path, iszip=True):
        self.classifier.load(fname, iszip) # 加载贝叶斯模型

    # 分词以及去停用词的操作    
    def handle(self, doc):
        words = seg.seg(doc) # 分词
        words = normal.filter_stop(words) # 去停用词
        return words # 返回分词后的结果

    def train(self, neg_docs, pos_docs):
        data = []
        # 读入负样本
        for sent in neg_docs:
            data.append([self.handle(sent), 'neg'])
        # 读入正样本
        for sent in pos_docs:
            data.append([self.handle(sent), 'pos'])
        # 调用的是Bayes模型的训练方法
        self.classifier.train(data)

    def classify(self, sent):
        # 1、调用sentiment类中的handle方法
        # 2、调用Bayes类中的classify方法
        ret, prob = self.classifier.classify(self.handle(sent)) # 调用贝叶斯中的classify方法
        if ret == 'pos':
            return prob
        return 1-probclass Sentiment(object):

    def __init__(self):
        self.classifier = Bayes() # 使用的是Bayes的模型

    def save(self, fname, iszip=True):
        self.classifier.save(fname, iszip) # 保存最终的模型

    def load(self, fname=data_path, iszip=True):
        self.classifier.load(fname, iszip) # 加载贝叶斯模型

    # 分词以及去停用词的操作    
    def handle(self, doc):
        words = seg.seg(doc) # 分词
        words = normal.filter_stop(words) # 去停用词
        return words # 返回分词后的结果

    def train(self, neg_docs, pos_docs):
        data = []
        # 读入负样本
        for sent in neg_docs:
            data.append([self.handle(sent), 'neg'])
        # 读入正样本
        for sent in pos_docs:
            data.append([self.handle(sent), 'pos'])
        # 调用的是Bayes模型的训练方法
        self.classifier.train(data)

    def classify(self, sent):
        # 1、调用sentiment类中的handle方法
        # 2、调用Bayes类中的classify方法
        ret, prob = self.classifier.classify(self.handle(sent)) # 调用贝叶斯中的classify方法
        if ret == 'pos':
            return prob
        return 1-prob

从上述的代码中,classify函数和train函数是两个核心的函数,其中,train函数用于训练一个情感分类器,classify函数用于预测。在这两个函数中,都同时使用到的handle函数,handle函数的主要工作为:

  1. 对输入文本分词
  2. 去停用词

情感分类的基本模型是贝叶斯模型Bayes,对于贝叶斯模型,可以参见文章简单易学的机器学习算法——朴素贝叶斯。对于有两个类别 c 1 c 2 的分类问题来说,其特征为 w 1 , , w n ,特征之间是相互独立的,属于类别 c 1 的贝叶斯模型的基本过程为:

P ( c 1 w 1 , , w n ) = P ( w 1 , , w n c 1 ) P ( c 1 ) P ( w 1 , , w n )

其中:

P ( w 1 , , w n ) = P ( w 1 , , w n c 1 ) P ( c 1 ) + P ( w 1 , , w n c 2 ) P ( c 2 )

3.1、贝叶斯模型的训练

贝叶斯模型的训练过程实质上是在统计每一个特征出现的频次,其核心代码如下:

def train(self, data):
    # data 中既包含正样本,也包含负样本
    for d in data: # data中是list
        # d[0]:分词的结果,list
        # d[1]:正/负样本的标记
        c = d[1]
        if c not in self.d:
            self.d[c] = AddOneProb() # 类的初始化
        for word in d[0]: # 分词结果中的每一个词
            self.d[c].add(word, 1)
    # 返回的是正类和负类之和
    self.total = sum(map(lambda x: self.d[x].getsum(), self.d.keys())) # 取得所有的d中的sum之和

这使用到了AddOneProb类,AddOneProb类如下所示:

class AddOneProb(BaseProb):

    def __init__(self):
        self.d = {}
        self.total = 0.0
        self.none = 1 # 默认所有的none为1
    # 这里如果value也等于1,则当key不存在时,累加的是2
    def add(self, key, value):
        self.total += value
        # 不存在该key时,需新建key
        if not self.exists(key):
            self.d[key] = 1
            self.total += 1
        self.d[key] += value

注意:

  1. none的默认值为1
  2. 当key不存在时,total和对应的d[key]累加的是1+value,这在后面预测时需要用到

AddOneProb类中的total表示的是正类或者负类中的所有值;train函数中的total表示的是正负类的total之和。

当统计好了训练样本中的total和每一个特征key的d[key]后,训练过程就构建完成了。

3.2、贝叶斯模型的预测

预测的过程使用到了上述的公式,即:

P ( c 1 w 1 , , w n ) = P ( w 1 , , w n c 1 ) P ( c 1 ) P ( w 1 , , w n c 1 ) P ( c 1 ) + P ( w 1 , , w n c 2 ) P ( c 2 )

对上述的公式简化:

P ( c 1 w 1 , , w n ) = P ( w 1 , , w n c 1 ) P ( c 1 ) P ( w 1 , , w n c 1 ) P ( c 1 ) + P ( w 1 , , w n c 2 ) P ( c 2 ) = 1 1 + P ( w 1 , , w n c 2 ) P ( c 2 ) P ( w 1 , , w n c 1 ) P ( c 1 ) = 1 1 + e x p [ l o g ( P ( w 1 , , w n c 2 ) P ( c 2 ) P ( w 1 , , w n c 1 ) P ( c 1 ) ) ] = 1 1 + e x p [ l o g ( P ( w 1 , , w n c 2 ) P ( c 2 ) ) l o g ( P ( w 1 , , w n c 1 ) P ( c 1 ) ) ]

其中,分母中的1可以改写为:

1 = e x p [ l o g ( P ( w 1 , , w n c 1 ) P ( c 1 ) ) l o g ( P ( w 1 , , w n c 1 ) P ( c 1 ) ) ]

上述过程对应的代码如下所示:

def classify(self, x):
    tmp = {}
    for k in self.d: # 正类和负类
        tmp[k] = log(self.d[k].getsum()) - log(self.total) # 正类/负类的和的log函数-所有之和的log函数
        for word in x:
            tmp[k] += log(self.d[k].freq(word)) # 词频,不存在就为0
    ret, prob = 0, 0
    for k in self.d:
        now = 0
        try:
            for otherk in self.d:
                now += exp(tmp[otherk]-tmp[k])
            now = 1/now
        except OverflowError:
            now = 0
        if now > prob:
            ret, prob = k, now
    return (ret, prob)

其中,第一个for循环中的tmp[k]对应了公式中的 l o g ( P ( c k ) ) ,第二个for循环中的tmp[k]对应了公式中的 l o g ( P ( w 1 , , w n c k ) P ( c k ) )

参考文献

  1. snownlp github
  2. 自然语言处理库之snowNLP

猜你喜欢

转载自blog.csdn.net/google19890102/article/details/80091502