-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclassify.py
More file actions
executable file
·391 lines (340 loc) · 13.2 KB
/
classify.py
File metadata and controls
executable file
·391 lines (340 loc) · 13.2 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
"""Train and test several classifiers on a sample of tweets,
Reads text files containing a training sample and a test sample of
tweets, and runs them through Random Forest, K Neighbors, Logistic
Regression and SVC, using the tweet's first 15, 30, and 45 minutes
of history, to try to predict their final retweet amount by classifying
them into retweet buckets. Prints the score of the test classifications
along with the confusion matrix, precision and recall.
Created on 15/07/2014
@author: Jose Parada
"""
from __future__ import division
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from fim import eclat
import glob
NUMBER_OF_RT_BUCKETS = 4
TRAINING_DIR = 'Training/'
TEST_DIR = 'Test/'
TRAINING_SAMPLE = TRAINING_DIR + 'Training.sample'
TEST_SAMPLE = TEST_DIR + 'Test.sample'
cols = ('#followers', 'isDirect', 'isMention', 'hasExclamation', 'hasHashtag',
'hasEmoticonNegative', 'hasEmoticonPositive', 'hasQuestion', 'hasURL',
'Sentiment')
colsOneP = ('#followers', 'isDirect', 'isMention', 'hasExclamation', 'hasHashtag',
'hasEmoticonNegative', 'hasEmoticonPositive', 'hasQuestion', 'hasURL',
'SentimentNegative', 'SentimentNeutral', 'SentimentPositive', 'Retweets 1',
'RetweetsDif 1', 'Probability 1', 'ProbabilityDif 1', 'Views 1', 'ViewsDif 1',
'FollowerAvg 1', 'FollowerAvgDif 1', 'TopicBucket 1', 'TopicBucket 2',
'TopicBucket 3', 'TopicBucket 4');
colsTwoP = ('#followers', 'isDirect', 'isMention', 'hasExclamation', 'hasHashtag',
'hasEmoticonNegative', 'hasEmoticonPositive', 'hasQuestion', 'hasURL',
'SentimentNegative', 'SentimentNeutral', 'SentimentPositive', 'Retweets 1',
'Retweets 2', 'RetweetsDif 1', 'RetweetsDif 2', 'Probability 1',
'Probability 2', 'ProbabilityDif 1', 'ProbabilityDif 2', 'Views 1',
'Views 2', 'ViewsDif 1', 'ViewsDif 2', 'FollowerAvg 1', 'FollowerAvg 2',
'FollowerAvgDif 1', 'FollowerAvgDif 2', 'TopicBucket 1', 'TopicBucket 2',
'TopicBucket 3', 'TopicBucket 4');
colsThreeP = ('#followers', 'isDirect', 'isMention', 'hasExclamation', 'hasHashtag',
'hasEmoticonNegative', 'hasEmoticonPositive', 'hasQuestion', 'hasURL',
'SentimentNegative', 'SentimentNeutral', 'SentimentPositive', 'Retweets 1',
'Retweets 2', 'Retweets 3', 'RetweetsDif 1', 'RetweetsDif 2', 'RetweetsDif 3',
'Probability 1', 'Probability 2', 'Probability 3', 'ProbabilityDif 1',
'ProbabilityDif 2', 'ProbabilityDif 3', 'Views 1', 'Views 2', 'Views 3',
'ViewsDif 1', 'ViewsDif 2', 'ViewsDif 3', 'FollowerAvg 1', 'FollowerAvg 2',
'FollowerAvg 3', 'FollowerAvgDif 1', 'FollowerAvgDif 2', 'FollowerAvgDif 3',
'TopicBucket 1', 'TopicBucket 2', 'TopicBucket 3', 'TopicBucket 4');
tweetsPerBucket = [0, 0, 0, 0]
tweetsPerTopic = [{}, {}, {}, {}]
def replace_all(text, dic):
"""Replace all occurrences of the dictionary strings in the text."""
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
def get_sample(filePath, training, minimumPeriods=4):
"""Read a tweet sample from a sample file and return it as lists.
The sample variables are transformed into floats if they're numbers.
Some elements, like the retweet amounts, are transformed placed
into buckets. The sample is returned in the form of two lists, X for
the independent variables and Y for the dependent variable, which is
the retweet amount.
The elements of X are as follows:
0:AuthorsFollowers, 1:isDirect, 2:isMention, 3:isExclamation,
4:hasHashtag, 5:hasNegativeEmoticon, 6:hasPositiveEmoticon,
7:isQuestion, 8:hasUrl, 9-11:Sentiment OHE, 12+: History data,
-1 - -4: Topic ratios.
"""
sampleFile = open(filePath)
X = []
Y = []
line = sampleFile.readline()
while line != '':
row = line.split()
if int(row[-1]) >= minimumPeriods:
Y.append(float(row[0]))
topic = row[13]
if training:
if Y[-1] == 0:
group = 0
elif Y[-1] <= 10:
group = 1
elif Y[-1] <= 50:
group = 2
else:
group = 3
tweetsPerBucket[group] += 1
if topic in tweetsPerTopic[group]:
tweetsPerTopic[group][topic] += 1
else:
tweetsPerTopic[group][topic] = 1
add = [float(x) for x in row[3:12]]
ohe = OneHotEncoder()
ohe.fit([[0], [1], [2]]);
for e in ohe.transform([[row[12]]]).toarray()[0]:
add.append(float(e))
for _ in range(8):
row = sampleFile.readline().split()
for i in range(minimumPeriods - 1):
add.append(float(row[i]))
add.append(topic)
X.append(add)
else:
for _ in range(8):
sampleFile.readline()
line = sampleFile.readline()
for x in X:
topic = x[-1]
if topic in tweetsPerTopic[0]:
x[-1] = tweetsPerTopic[0][topic] / tweetsPerBucket[0]
else:
x[-1] = 0
for i in range(1, NUMBER_OF_RT_BUCKETS):
if topic in tweetsPerTopic[i]:
x.append(tweetsPerTopic[i][topic] / tweetsPerBucket[i])
else:
x.append(0)
sampleFile.close()
return X, Y
def get_sample_eclat(name):
"""Read a tweet sample from a sample file and return it in a format eclat
can process.
"""
sampleFile = open(name)
X = []
Y = []
line = sampleFile.readline()
while line != '':
row = line.split()
Y.append(int(row[0]))
x = []
if int(row[3]) < 50:
x.append('#followers: 0-49')
elif int(row[3]) < 100:
x.append('#followers: 50-99')
elif int(row[3]) < 500:
x.append('#followers: 100-499')
elif int(row[3]) < 1000:
x.append('#followers: 500-999')
elif int(row[3]) < 5000:
x.append('#followers: 1000-4999')
elif int(row[3]) < 10000:
x.append('#followers: 5000-9999')
else:
x.append('#followers: 10000+')
for i in range(4, 12):
if int(row[i]):
x.append(cols[i - 3])
if int(row[12]) == 0:
x.append('Sentiment: Negative')
elif int(row[12]) == 1:
x.append('Sentiment: Neutral')
else:
x.append('Sentiment: Positive')
x.append('Topic: ' + row[13])
X.append(x)
for _ in range(8):
sampleFile.readline()
line = sampleFile.readline()
return X, Y
def split_groups(Y):
"""Split the retweet amounts in Y into buckets.
Bucket 0 - 0 retweets.
Bucket 1 - 1 < retweets <= 10.
Bucket 2 - 11 < retweets <= 50.
Bucket 3 - More than 50 retweets.
"""
Ysplit = []
for y in Y:
if y == 0:
Ysplit.append(0)
elif y <= 10:
Ysplit.append(1)
elif y <= 50:
Ysplit.append(2)
else:
Ysplit.append(3)
return Ysplit
def classify(X, Y, Xstring, Y2, method, periods):
"""Trains and tests a sample against a classifier.
Two samples of tweets, one for training and one for testing, are run
through a classifier of the caller's choosing through the method
argument.
The possible values of the method argument are:
0 - Random Forest
1 - SVC
2 - Logistic Regression
3 - K Neighbors
The score, confusion matrix, precision and recall are printed.
"""
if method == 0:
clf = RandomForestClassifier(100)
print 'Random Forest'
elif method == 1:
clf = SVC()
print 'SVC'
elif method == 2:
clf = LogisticRegression()
print 'Logistic Regression'
else:
clf = KNeighborsClassifier(15)
print 'K Neighbors'
clf.fit(X, Y)
print 'Score: ' + str(clf.score(Xstring, Y2))
if method == 0:
print 'Importances: '
importances = clf.feature_importances_
for i in range(len(importances)):
if (periods == 1):
print " " + colsOneP[i] + ": " + str(importances[i])
elif (periods == 2):
print " " + colsTwoP[i] + ": " + str(importances[i])
else:
print " " + colsThreeP[i] + ": " + str(importances[i])
prediction = clf.predict(Xstring)
bucketTotals = []
for i in range(NUMBER_OF_RT_BUCKETS):
bucketTotals.append(Y2.count(i))
cm = confusion_matrix(Y2, prediction)
precision = []
recall = []
fscore = []
bucketDif = 0
for i in range(len(bucketTotals)):
if bucketTotals[i] == 0:
precision.append(1)
recall.append(1)
bucketDif += 1
else:
truePositive = cm[i - bucketDif, i - bucketDif]
testPositive = sum(cm[:, i - bucketDif])
conditionPositive = sum(cm[i - bucketDif, :])
if testPositive != 0:
precision.append(truePositive / testPositive)
else:
precision.append(1)
recall.append(truePositive / conditionPositive)
if (precision[-1] + recall[-1] == 0):
fscore.append(0)
else:
fscore.append(2 * ((precision[-1] * recall[-1]) / (precision[-1] + recall[-1])));
print 'Confusion matrix: '
print cm
print 'Precision: ' + str(precision)
print 'Recall: ' + str(recall)
print 'F-score: ' + str(fscore);
print
def combine_files():
"""Combines all sample files into two large training and test samples.
Replaces everything necessary for the classifiers and eclat to read the
samples properly.
"""
replacements = {'true':'1', 'false':'0', 'Human Interest':'Human_Interest',
'Social Issues':'Social_Issues', 'pos':'2', 'neu':'1', 'neg':'0'}
trainingDir = glob.glob(TRAINING_DIR + '*.txt')
testDir = glob.glob(TEST_DIR + '*.txt')
trainingFile = open(TRAINING_SAMPLE, 'w')
for fileName in trainingDir:
inFile = open(fileName)
for line in inFile:
trainingFile.write(replace_all(line, replacements))
inFile.close()
trainingFile.close()
testFile = open(TEST_SAMPLE, 'w')
for fileName in testDir:
inFile = open(fileName)
for line in inFile:
testFile.write(replace_all(line, replacements))
inFile.close()
testFile.close()
combine_files()
for periods in range(1, 4):
print 'Classifying with ' + str(periods) + ' periods'
minimumPeriods = periods + 1
X, Y = get_sample(TRAINING_SAMPLE, 1, minimumPeriods)
X2, Y2 = get_sample(TEST_SAMPLE, 0, minimumPeriods)
Ys = split_groups(Y)
Y2s = split_groups(Y2)
scalerY = StandardScaler().fit(Y)
scalerX = StandardScaler().fit(X)
bucketTotals = []
for i in range(NUMBER_OF_RT_BUCKETS):
bucketTotals.append(Y2s.count(i))
print 'Tweets per retweet bucket: ' + str(bucketTotals)
print
for i in range(4):
classify(scalerX.transform(X), Ys, scalerX.transform(X2), Y2s, i, periods)
print
print
X, Y = get_sample_eclat(TRAINING_SAMPLE)
X2, Y2 = get_sample_eclat(TEST_SAMPLE)
Ys = split_groups(Y)
Y2s = split_groups(Y2)
# Split and combine the samples according to retweet bucket.
x0 = []
x1 = []
x2 = []
x3 = []
for i in range(len(Ys)):
if Ys[i] == 0:
x0.append(X[i])
elif Ys[i] == 1:
x1.append(X[i])
elif Ys[i] == 2:
x2.append(X[i])
else:
x3.append(X[i])
for i in range(len(Y2s)):
if Y2s[i] == 0:
x0.append(X2[i])
elif Y2s[i] == 1:
x1.append(X2[i])
elif Y2s[i] == 2:
x2.append(X2[i])
else:
x3.append(X2[i])
for x in X2:
X.append(x)
s = 20
print 'eclat'
print 'Length = ' + str(len(X))
for r in eclat(X, target='m', report='sa', supp=s): print r
print
print 'RT = 0'
print 'Length = ' + str(len(x0))
for r in eclat(x0, target='m', report='sa', supp=s): print r
print
print 'RT <= 10'
print 'Length = ' + str(len(x1))
for r in eclat(x1, target='m', report='sa', supp=s): print r
print
print 'RT <= 50'
print 'Length = ' + str(len(x2))
for r in eclat(x2, target='m', report='sa', supp=s): print r
print
print 'RT > 50'
print 'Length = ' + str(len(x3))
for r in eclat(x3, target='m', report='sa', supp=s): print r