中文微博情感分类之calibrated label ranking

readExcel.py

# -*- coding: utf-8 -*-
"""
Created on Sat Aug  5 10:03:17 2017

@author: Sean Chang
"""

import xlrd



emodic = {"PA":6,"PE":6,"PD":0,"PH":0,"PG":0,"PB":0,"PK":0,"NA":3,"NB":5,"NJ":5 \
          ,"NH":5,"PF":5,"NI":1,"NC":1,"NG":1,"NE":2,"ND":2,"NN":2,"NK":2,"NL":2,"PC":4}

def EmoLexicon(filename):
    data = xlrd.open_workbook(filename)
    table = data.sheets()[0]
    nrows = table.nrows
    emolist = []
    emoindex = []
    for i in range(1,nrows):
        emolist.append(table.row_values(i)[0])
        emoindex.append(emodic[table.row_values(i)[4].strip()])
    
    return emolist,emoindex

if __name__ == "__main__":
    emolist,emoindex = EmoLexicon('emotion ontology.xlsx')

rankNB.py

# -*- coding: utf-8 -*-
"""
Created on Mon Aug  7 06:41:17 2017

@author: Sean Chang
"""

import xml.dom.minidom
import jieba
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer

stop_words = ["的", "一", "不", "在", "人", "有", "是", "为", "以", "于", "上", "他", "而",
            "后", "之", "来", "及", "了", "因", "下", "可", "到", "由", "这", "与", "也",
            "此", "但", "并", "个", "其", "已", "无", "小", "我", "们", "起", "最", "再",
            "今", "去", "好", "只", "又", "或", "很", "亦", "某", "把", "那", "你", "乃",
            "它","要", "将", "应", "位", "新", "两", "中", "更", "我们", "自己", "没有", "“", "”",
            ",", "(", ")", " ",'[',']',' ','~','。','!']


emo = ['like','fear','disgust','anger','surprise','sadness','happiness']

def readXML(filename):
        # 使用minidom解析器打开 XML 文档
    DOMTree = xml.dom.minidom.parse(filename)
    collection = DOMTree.documentElement
    
    
    weibos = collection.getElementsByTagName("weibo")
    
    Ncount = 0 #count of all the class
    sen_lst = []
    for weibo in weibos:
       sentence = weibo.getElementsByTagName('sentence')
       for e in sentence:
           lst = []
           if e.getAttribute('opinionated')=='Y':
               lst.append(e.childNodes[0].data)
               emotion1 = e.getAttribute('emotion-1-type')
               Ncount = Ncount + 1
               emotion2 = e.getAttribute('emotion-2-type')
               if emotion2 != 'none':
                   Ncount = Ncount + 1
               lst.append([emotion1,emotion2])
               sen_lst.append(lst)
    
    
    emotionlist = [[],[],[],[],[],[],[]]
    
    for e in sen_lst:
        if 'like' in e[1]:
            emotionlist[0].append(e[0])
        if 'fear' in e[1]:
            emotionlist[1].append(e[0])
        if 'disgust' in e[1]:
            emotionlist[2].append(e[0])
        if 'anger' in e[1]:
            emotionlist[3].append(e[0])
        if 'surprise' in e[1]:
            emotionlist[4].append(e[0])
        if 'sadness' in e[1]:
            emotionlist[5].append(e[0])
        if 'happiness' in e[1]:
            emotionlist[6].append(e[0])
    
    
    return emotionlist,Ncount


def readTestXML(filename):
    testdata = []
    testlabel = []
    DOMTree = xml.dom.minidom.parse(filename)
    collection = DOMTree.documentElement
    weibos = collection.getElementsByTagName("weibo")
    for weibo in weibos:
        emotion1 = weibo.getAttribute("emotion-type1")
        emotion2 = weibo.getAttribute("emotion-type2")
        sen = ""
        if emotion1 in emo:
            sentence = weibo.getElementsByTagName('sentence')
            for e in sentence:
                sen += e.childNodes[0].data
            testdata.append(sen)
            label1 = emo.index(emotion1)
            if emotion2 in emo:
                label2 = emo.index(emotion2)
            else:
                label2 = -1
            testlabel.append([label1,label2])
    return testdata,testlabel

def lcm(x,y): # very fast
    s = x*y
    while y: x, y = y, x%y
    return s/x

#solve the bias distribution problem
def adjustData(emotionlist):
    l = []
    for e in emotionlist:
        l.append(len(e))
    m = max(l)
    maxindex = l.index(m)
    Ncount= 0
    for i in range(len(emotionlist)):
        if maxindex == i:
            #emotionlist[i] *= 2
            Ncount += l[i]
        else:
            
            emotionlist[i] *= (m//l[i])
            Ncount += l[i]*(m//l[i])
    
    return emotionlist,Ncount  
        

def createData(emotionlist,Ncount):
    data = []
    label = []
    for i in range(len(emotionlist)):
        for e in emotionlist[i]:
            data.append(e)
            label.append(i)
    return data,label

def segmentWord(cont):
    c = []
    for i in cont:
        a = list(jieba.cut(i))
        b = " ".join(a)
        c.append(b)
    return c

def showresult(rst):
    c = ['like','fear','disgust','anger','surprise','sadness','happiness']
    rs = sorted(rst)
    max1 = rst.index(rs[-1])
    max2 = rst.index(rs[-2])
    return c[max1],c[max2]


def rank(lst):
    sortl = sorted(lst,reverse=False)
    r = []
    for e in lst:
        r.append(sortl.index(e))
    return r
            
def train(data,label):
    vectorizer = CountVectorizer()
    content = segmentWord(data)
    opinion = label
    tfidf = vectorizer.fit_transform(content)  
    clf = MultinomialNB()
    clf.fit(tfidf, opinion)
    return clf,vectorizer

def test(sentence,clf,vectorizer):
    docs = [" ".join(list(jieba.cut(sentence)))]
    new_tfidf = vectorizer.transform(docs)
    predicted = clf.predict_log_proba(new_tfidf)
    return predicted[0]

if __name__ == "__main__":
    '''
    emotionlist,Ncount = readXML("NLPCC.xml")
    emotionlist,Ncount = adjustData(emotionlist)
    
    data,label = createData(emotionlist,Ncount)
    clf,vectorizer = train(data,label)
    print(rank(test("老鼠怕猫?",clf,vectorizer)))
    '''
    testdata,testlabel = readTestXML("NLPtest.xml")

        

binaryNB.py

# -*- coding: utf-8 -*-
"""
Created on Wed Aug  2 19:23:04 2017

@author: Sean Chang
"""

from xml.dom.minidom import parse
import xml.dom.minidom
import jieba
from sklearn.naive_bayes import MultinomialNB
import rankNB
from sklearn.feature_extraction.text import CountVectorizer

stop_words = ["的", "一", "不", "在", "人", "有", "是", "为", "以", "于", "上", "他", "而",
            "后", "之", "来", "及", "了", "因", "下", "可", "到", "由", "这", "与", "也",
            "此", "但", "并", "个", "其", "已", "无", "小", "我", "们", "起", "最", "再",
            "今", "去", "好", "只", "又", "或", "很", "亦", "某", "把", "那", "你", "乃",
            "它","要", "将", "应", "位", "新", "两", "中", "更", "我们", "自己", "没有", "“", "”",
            ",", "(", ")", " ",'[',']',' ','~','。','!']


emo = ['like','fear','disgust','anger','surprise','sadness','happiness']

def readXML(filename):
        # 使用minidom解析器打开 XML 文档
    DOMTree = xml.dom.minidom.parse(filename)
    collection = DOMTree.documentElement
    
    # 在集合中获取所有电影
    weibos = collection.getElementsByTagName("weibo")
    
    Ncount = 0 #count of all the class
    sen_lst = []
    for weibo in weibos:
       sentence = weibo.getElementsByTagName('sentence')
       for e in sentence:
           lst = []
           if e.getAttribute('opinionated')=='Y':
               lst.append(e.childNodes[0].data)
               emotion1 = e.getAttribute('emotion-1-type')
               Ncount = Ncount + 1
               emotion2 = e.getAttribute('emotion-2-type')
               if emotion2 != 'none':
                   Ncount = Ncount + 1
               lst.append([emotion1,emotion2])
               sen_lst.append(lst)
    
    
    emotionlist = [[],[],[],[],[],[],[]]
    
    for e in sen_lst:
        if 'like' in e[1]:
            emotionlist[0].append(e[0])
        if 'fear' in e[1]:
            emotionlist[1].append(e[0])
        if 'disgust' in e[1]:
            emotionlist[2].append(e[0])
        if 'anger' in e[1]:
            emotionlist[3].append(e[0])
        if 'surprise' in e[1]:
            emotionlist[4].append(e[0])
        if 'sadness' in e[1]:
            emotionlist[5].append(e[0])
        if 'happiness' in e[1]:
            emotionlist[6].append(e[0])
    
    
    return emotionlist,Ncount






def create7Data(emotionlist,Ncount):
    rst = []
    for i in range(7):
        data = []
        label = []
        data = [e for e in emotionlist[i]]
        for j in range(7):
            if j!=i:
                data += [e for e in emotionlist[j]]
        label = [1]*len(emotionlist[i])
        label += [-1]*(Ncount - len(emotionlist[i]))
        rst.append([data,label])
    
    return rst
                
def segmentWord(cont):
    c = []
    for i in cont:
        a = list(jieba.cut(i))
        b = " ".join(a)
        c.append(b)
    return c

def testSentence(rsti,docs):
    vectorizer = CountVectorizer()
    content = segmentWord(rsti[0])
    opinion = rsti[1]
    tfidf = vectorizer.fit_transform(content)  
    clf = MultinomialNB()
    clf.fit(tfidf, opinion)
    new_tfidf = vectorizer.transform(docs)
    predicted = clf.predict(new_tfidf)
    return predicted[0]

if __name__ == "__main__":
    
    emotionlist,Ncount = readXML("NLPCC.xml")
    '''
    likedata,likelabel = createLike(emotionlist,Ncount)
    
    
    emotionlist,Ncount = parseXML.adjustData(emotionlist)
    rst = create7Data(emotionlist,Ncount)
    like_data_feature,word_feature = prepareForTraining(rst[0][0])
    print(testSentence(like_data_feature,word_feature,rst[0][1],"今天真的好开心"))
    '''
    emotionlist,Ncount = rankNB.adjustData(emotionlist)
    rst = create7Data(emotionlist,Ncount)
    docs = [" ".join(list(jieba.cut("好怀念 [泪] 我记得这照片好像是@Christine_HJ 是CC拍的")))]
    print(testSentence(rst[5],docs))

main.py

# -*- coding: utf-8 -*-
"""
Created on Sat Aug  5 06:28:52 2017

@author: Sean Chang
"""

import binaryNB
import rankNB
import jieba
import readExcel
import random 



if __name__ == "__main__":
    emo = ['like','fear','disgust','anger','surprise','sadness','happiness']
    #read the train document
    emotionlist,Ncount = rankNB.readXML("NLPCC.xml")
    #emotionlist,Ncount = rankNB.adjustData(emotionlist)
    #adjust the train data for average distribution
    #emotionlist,Ncount = parseXML.adjustData(emotionlist)
    #load emotion lexicon
    print("load emotion lexicon")
    emolist,emoindex = readExcel.EmoLexicon('emotion ontology.xlsx')
    
    data,label = rankNB.createData(emotionlist,Ncount)
    #train the data for first ranking
    clf,vectorizer = rankNB.train(data,label)
    
        
    #merge the 7 binary classification train data
    rst7data = binaryNB.create7Data(emotionlist,Ncount)
    
    '''
    testdata,testlabel = rankNB.readTestXML("NLPtest.xml")
    
    
    #randomly choose 20 sentence for testing
    randomlen = testdata.__len__()  
    indexList = range(randomlen)  
    randomIndex = random.sample(indexList, 100)  
    
    test_data = []
    test_label = []
    for i in randomIndex:  
        test_data.append(testdata[i])
        test_label.append(testlabel[i])
    '''
    #sen_counter :the ith sentence
    sen_counter = 0
    #correct number
    correct = 0   
    
    test_data=['生气生气生气吃惊吃惊吃惊!']
    test_label = [[3,4]]
    
    for string in test_data:
        print("calculating sentence",sen_counter+1)
        print(string)
        docs = [" ".join(list(jieba.cut(string)))]
        #merge the first rank list by testing
        r = rankNB.rank(rankNB.test(string,clf,vectorizer))
        print(r)
        
        #updating ranking 
        print("updating ranking")
        #7 binary classification for updating
        for i in range(7):
            r[i] += binaryNB.testSentence(rst7data[i],docs)
            print(r)
        
        #cut the test sentence
        word_list = jieba.cut(string,cut_all=True)
        #update the corresponding index in rank []
        for word in word_list:
            if word in emolist:
                i = emolist.index(word)
                r[emoindex[i]] += 1
        print(r)
        
        # find the top 2 emotion:
        copyr = [e for e in r]
        m1 = max(copyr)
        index1 = r.index(m1)
        del copyr[index1]
        m2 = max(copyr)
      
        if m1 != m2:
            index2 = r.index(m2)
        else:
            r[index1] += 1
            index2 = r.index(m2)
            r[index1] -= 1
        l = test_label[sen_counter]
        if -1 not in l:
            if (index1 in l) and (index2 in l):
                correct += 1
        else:
            if (index1 in l) or (index2 in l):
                correct += 1
        sen_counter += 1
        print("now correct:",correct)
    
    print("precision is:",correct/len(test_data))
        
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,386评论 6 479
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,939评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,851评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,953评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,971评论 5 369
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,784评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,126评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,765评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,148评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,744评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,858评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,479评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,080评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,053评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,278评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,245评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,590评论 2 343

推荐阅读更多精彩内容