-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathclassify.py
186 lines (155 loc) · 6.16 KB
/
classify.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
"""
classify.py
"""
import re
import pickle
import configparser
from collections import Counter, defaultdict
from itertools import chain, combinations
import glob
import numpy as np
import os
from scipy.sparse import csr_matrix
from sklearn.cross_validation import KFold
from sklearn.linear_model import LogisticRegression
def get_unique_tweets(filename):
print("getting unique tweets from pickle file")
readtweets = open(filename, 'rb')
tweets = pickle.load(readtweets)
readtweets.close()
utlist = set()
for t in tweets:
utlist.add(t['text'].encode('utf8').decode('unicode_escape').encode('ascii','ignore').decode("utf-8"))
print("found %d unique tweets from file" % len(utlist))
return list(utlist)
def get_afinn_sentiment(affin_filename):
print("forming pos and neg word list from affin sentiment file")
pos = []
neg = []
with open(affin_filename) as f:
for line in f:
tl = re.split(r'\t+', line.rstrip('\t'))
if int(tl[1]) > 0:
pos.append(tl[0].encode('ascii','ignore').decode("utf-8"))
elif int(tl[1]) < 0:
neg.append(tl[0].encode('ascii','ignore').decode("utf-8"))
return pos,neg
def dsum(*dicts):
ret = defaultdict(int)
for d in dicts:
for k, v in d.items():
ret[k] += v
return dict(ret)
def read_data(path):
fnames = sorted([f for f in glob.glob(os.path.join(path, 'pos', '*.txt'))])
data = [(1, open(f).readlines()[0]) for f in sorted(fnames[:1000])]
fnames = sorted([f for f in glob.glob(os.path.join(path, 'neg', '*.txt'))])
data += [(0, open(f).readlines()[0]) for f in sorted(fnames[:1000])]
data = sorted(data, key=lambda x: x[1])
return np.array([d[1] for d in data]), np.array([d[0] for d in data])
def tokenize(doc):
tnp = []
for x in doc.lower().split():
tnp.append(re.sub('^\W+', '',re.sub('\W+$', '',x)))
#return tnp
return np.array(tnp)
def token_features(tokens, feats,pos,neg):
feats.update(dsum(dict(Counter(Counter(["token=" + s for s in tokens]))),feats))
def token_pair_features(tokens,feats,pos,neg):
k=3
for i in range(len(tokens)-k+1):
for e in list(combinations(list(tokens[i:k+i]), 2)):
feats['token_pair='+e[0]+'__'+e[1]] += 1
def lexicon_features(tokens,feats,pos_words,neg_words):
feats.update(dsum(dict(Counter({'pos_words': len([x for x in list(s.lower() for s in tokens) if x in pos_words]) , 'neg_words' : len([x for x in list(s.lower() for s in tokens) if x in neg_words]) })),feats))
def featurize(tokens,feature_fns,pos,neg):
feats = defaultdict(lambda : 0)
for fn in feature_fns:
fn(tokens,feats,pos,neg)
return sorted(list(feats.items()), key=lambda x: (x[0]))
def vectorize(tokens_list,pos,neg,vocab=None):
feature_fns = [token_pair_features,lexicon_features]
#feature_fns = [token_pair_features,lexicon_features,token_features]
min_freq = 2
vf = []
vocabSec = {}
for t in tokens_list:
vf.append(list(featurize(t,feature_fns,pos,neg)))
if vocab is None:
vocabSec = {i:x for x,i in enumerate(sorted(list([k for k,v in dict(Counter(list([e[0] for e in list(chain(*vf)) if e[1]>0]))).items() if v >=min_freq])))}
else:
vocabSec = vocab
column=[]
data=[]
rows=[]
row=0
for f in vf:
for e in f:
if e[0] in vocabSec:
rows.append(row)
column.append(vocabSec[e[0]])
data.append(e[1])
row+=1
data=np.array(data,dtype='int64')
rows=np.array(rows,dtype='int64')
column=np.array(column,dtype='int64')
X=csr_matrix((data, (rows,column)), shape=(len(tokens_list), len(vocabSec)))
#print (X.toarray())
#print (sorted(vocabSec.items(), key=lambda x: x[1]))
# for x in vocabSec:
# x1 = re.sub('token=', '', x)
# line = re.sub('token_pair=', '', x1)
# print(line.encode('ascii','ignore').decode("utf-8"))
return X,vocabSec
def fit_train_classifier(docs, labels,pos,neg):
tokens_list = [ tokenize(d) for d in docs ]
X,vocab = vectorize(tokens_list,pos,neg)
model = LogisticRegression()
model.fit(X,labels)
return model,vocab
def parse_test_data(tweets,vocab,pos,neg):
tokenslist = [ tokenize(d) for d in tweets ]
X_test,vocb=vectorize(tokenslist,pos,neg,vocab)
return X_test
def print_classification(tweets,X_test,clf):
predicted = clf.predict(X_test)
saveclassifydata = {}
print("Number of pos and neg tweets: "+str(Counter(predicted)))
for idx,t in enumerate(tweets[:10]):
label = ''
if predicted[idx] == 1:
label = "Positive"
saveclassifydata['positivetweet'] = t
elif predicted[idx] == 0:
label = "Negative"
saveclassifydata['negativetweet'] = t
print("Classified as : %s Tweet Text: %s " % (label,t))
saveclassifydata['pos'] = dict(Counter(predicted))[1]
saveclassifydata['neg'] = dict(Counter(predicted))[0]
outputfile = open('dataclassify.pkl', 'wb')
pickle.dump(saveclassifydata, outputfile)
outputfile.close()
def main():
config = configparser.ConfigParser()
config.read('twitter.cfg')
internalData = str(config.get('twitter', 'useDataFile'))
affin_filename = 'data/affin/AFINN-111.txt'
filename = ''
if internalData == "True":
print("As internalData is set to True we will use tweets in file mytweets.pkl")
filename = 'data/mydownloadeddata/mytweets.pkl'
elif internalData == "False":
print("As internalData is set to False we will use new tweets file newmytweets.pkl")
filename = 'newmytweets.pkl'
tweets = get_unique_tweets(filename)
pos,neg = get_afinn_sentiment(affin_filename)
print("Total pos words are %d" % int(len(pos)))
print("Total neg words are %d" % int(len(neg)))
print("Reading and fitting train data")
docs, labels = read_data(os.path.join('data', 'train'))
clf, vocab = fit_train_classifier(docs,labels,pos,neg)
print ("Length of vocab is %d" % int(len(vocab)))
X_test = parse_test_data(tweets,vocab,pos,neg)
print_classification(tweets,X_test,clf)
if __name__ == '__main__':
main()