-
Notifications
You must be signed in to change notification settings - Fork 0
/
SentimentWordFrequencyModel.py
233 lines (186 loc) · 9.23 KB
/
SentimentWordFrequencyModel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 20 20:25:00 2014
@author: Shay
"""
from enum import Enum
from nltk.corpus import sentiwordnet as swn
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
class WordNetKey(Enum):
a = 'a' #adjective
n = 'n' #noun
r = 'r' #rambocsious
v = 'v' #verb
class SentimentWordFrequencyModel:
def __init__(self):
self.totalInstancesProccessed = 0
self.totalPosInstances = 0
self.totalNegInstances = 0
self.totalPosWordsInDomain = 0 #total number of positive words in positive instance in the entire domain
self.totalNegWordsInDomain = 0 #total number of negative words in negative instance in the entire domain
self.totalObjWordsInDomain = 0 #total number of objective words in all instance in the entire domain
#Frequencies of sentimentful words in positive/negative instances
self.totalPosFreq = {}
self.totalNegFreq = {}
#Frequencies of objective words in all sentences
self.totalObjFreq = {}
#Line length distributions for positive and negative sentences
self.posLineLengthDict = {}
self.negLineLengthDict = {}
#sentiment-full word percentage for positive and negative sentences
self.sentWordPercentageInPos = 0
self.sentWordPercentageInNeg = 0
def getSentimentOfWord(self, word):
try:
sentSet = list(swn.senti_synsets(word))
except:
#print("swn.senti_synsets(word) threw an error")
return 0
#if not found, assume objective word
if len(sentSet) == 0:
#print('empty sentSet for word '+word)
return 0
#else:
#print('non empty sentSet for word '+word)
totalPos = 0
totalNeg = 0
totalObj = 0
for sentiword in sentSet:
totalPos += sentiword.pos_score()
totalNeg += sentiword.neg_score()
totalObj += sentiword.obj_score()
totalPos = totalPos / len(sentSet)
totalNeg = totalNeg / len(sentSet)
totalObj = totalObj / len(sentSet)
#determine sentiment
if (totalPos >= totalObj) and (totalPos >= totalNeg):
return 1
if (totalNeg >= totalObj) and (totalNeg >= totalPos):
return -1
if (totalObj >= totalPos) and (totalObj >= totalNeg):
return 0
def processPositiveLine(self, line):
if len(line) in self.posLineLengthDict:
self.posLineLengthDict[len(line)] += 1
else:
self.posLineLengthDict[len(line)] = 1
totalPosInThisLine = 0
for key in line:
wordSent = self.getSentimentOfWord(key)
if wordSent != -1: #if this word is not negative
if wordSent == 0: #if this is an objective word
freq = self.totalObjFreq
self.totalObjWordsInDomain += line[key]
if wordSent == 1: #if this is a positive word
freq = self.totalPosFreq
self.totalPosWordsInDomain += line[key]
totalPosInThisLine += line[key]
if key in freq:
freq[key] = freq[key] + line[key]
else:
freq[key] = line[key]
posPercentage = totalPosInThisLine / len(line)
self.sentWordPercentageInPos += posPercentage
def processNegativeLine(self, line):
if len(line) in self.negLineLengthDict:
self.negLineLengthDict[len(line)] += 1
else:
self.negLineLengthDict[len(line)] = 1
totalNegInThisLine = 0
for key in line:
wordSent = self.getSentimentOfWord(key)
if wordSent != 1: #if this word is not positive
if wordSent == 0: #if this is an objective word
freq = self.totalObjFreq
self.totalObjWordsInDomain += line[key]
if wordSent == -1: #if this is a negative word
freq = self.totalNegFreq
self.totalNegWordsInDomain += line[key]
totalNegInThisLine += line[key]
if key in freq:
freq[key] = freq[key] + line[key]
else:
freq[key] = line[key]
negPercentage = totalNegInThisLine / len(line)
self.sentWordPercentageInNeg += negPercentage
def processLine(self, line, isPositiveLine):
if isPositiveLine:
self.totalPosInstances += 1
self.processPositiveLine(line)
else:
self.totalNegInstances += 1
self.processNegativeLine(line)
self.totalInstancesProccessed += 1
def processDomain(self, X, Y):
for i in range(len(X)):
self.processLine(X[i],Y[i]==1)
self.sentWordPercentageInPos = self.sentWordPercentageInPos / self.totalPosInstances
self.sentWordPercentageInNeg = self.sentWordPercentageInNeg / self.totalNegInstances
#build word distribution for positive words
for word in self.totalPosFreq :
self.totalPosFreq[word] = self.totalPosFreq[word] / self.totalPosWordsInDomain
self.posTokenizer = dict(zip(list(range(len(self.totalPosFreq.keys()))), list(self.totalPosFreq.keys())))
self.posDist = stats.rv_discrete(name='positiveDist', values=(list(range(len(self.totalPosFreq.keys()))), list(self.totalPosFreq.values())))
#build word distribution for negative words
for word in self.totalNegFreq :
self.totalNegFreq[word] = self.totalNegFreq[word] / self.totalNegWordsInDomain
self.negTokenizer = dict(zip(list(range(len(self.totalNegFreq.keys()))), list(self.totalNegFreq.keys())))
self.negDist = stats.rv_discrete(name='negativeDist', values=(list(range(len(self.totalNegFreq.keys()))), list(self.totalNegFreq.values())))
#build word distribution for objective words
for word in self.totalObjFreq :
self.totalObjFreq[word] = self.totalObjFreq[word] / self.totalObjWordsInDomain
self.objTokenizer = dict(zip(list(range(len(self.totalObjFreq.keys()))), list(self.totalObjFreq.keys())))
self.objDist = stats.rv_discrete(name='objectiveDist', values=(list(range(len(self.totalObjFreq.keys()))), list(self.totalObjFreq.values())))
#build positive line length distribution
for length in self.posLineLengthDict:
self.posLineLengthDict[length] = self.posLineLengthDict[length] / self.totalPosInstances
self.posLineLengthDist = stats.rv_discrete(name='posLineLengthDist', values=(list(self.posLineLengthDict.keys()), list(self.posLineLengthDict.values())))
#build negative line length distribution
for length in self.negLineLengthDict:
self.negLineLengthDict[length] = self.negLineLengthDict[length] / self.totalNegInstances
self.negLineLengthDist = stats.rv_discrete(name='negLineLengthDist', values=(list(self.negLineLengthDict.keys()), list(self.negLineLengthDict.values())))
#labelIsPositive = 0 for Negative label, 1 for Positive label, 2 for random
def generateInstance(self, labelIsPositive = 2):
if labelIsPositive == 2:
labelIsPositive = np.random.randint(0, 2, size=1)
if labelIsPositive:
instLength = self.posLineLengthDist.rvs(size=1)[0]
numOfSent = int(round(self.sentWordPercentageInPos * instLength))
else:
instLength = self.negLineLengthDist.rvs(size=1)[0]
numOfSent = int(round(self.sentWordPercentageInNeg * instLength))
numOfObj = instLength - numOfSent
newInst = {}
for i in range(numOfSent):
if labelIsPositive:
randomToken = self.posDist.rvs(size=1)[0]
randomWord = self.posTokenizer[randomToken]
else:
randomToken = self.negDist.rvs(size=1)[0]
randomWord = self.negTokenizer[randomToken]
if randomWord in newInst:
newInst[randomWord] += 1
else:
newInst[randomWord] = 1
for i in range(numOfObj):
randomToken = self.objDist.rvs(size=1)[0]
randomWord = self.objTokenizer[randomToken]
if randomWord in newInst:
newInst[randomWord] += 1
else:
newInst[randomWord] = 1
return [newInst, labelIsPositive]
def generateDataset(self, size, positivePercentage = 0.5):
posNum = round(size * positivePercentage)
negNum = size - posNum
X = []
Y = []
for i in range(posNum):
X.append(self.generateInstance(1)[0])
Y.append(1)
for i in range(negNum):
X.append(self.generateInstance(0)[0])
Y.append(0)
return [X,Y]