-
Notifications
You must be signed in to change notification settings - Fork 0
/
topicinfo.py
347 lines (254 loc) · 9.1 KB
/
topicinfo.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
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
# Isaac Julien
# Get labeled topic information
import csv
import pylab
import numpy as np
from datetime import datetime
from time import strptime
# Get labeled topic percentages for each turn, along with start and end times of each turn:
def read_data(filename, topics):
file = open(filename, 'r')
file.readline() # First line is field names.
SPEAKER_IDX = 2
TOPIC_IDX = 5
START_IDX = 0
STOP_IDX = 1
current_speaker = None
start_time = None
stop_time = None
num_topics = len(topics)
# Last feature is majority topic
features = np.zeros(num_topics + 1)
turn_features = [] # features for each turn
turn_info = [] # (start time, end time) for each turn
contents = csv.reader(file, delimiter=',', quotechar='"')
speaker = None
for n, row in enumerate(contents):
speaker = row[SPEAKER_IDX]
if len(speaker) < 1:
continue
topic = row[TOPIC_IDX]
if topic == '9':
continue
if current_speaker is None:
current_speaker = speaker
time = row[START_IDX].split(".")[0] # Strip ms
start_time = datetime(*strptime(time, "%H:%M:%S")[0:6])
if speaker != current_speaker:
current_speaker = speaker
# Calculate feature percentages:
fsum = 0.0
max = -1
max_feature = None
for f in features:
fsum += f
for i in range(len(features)):
if features[i] > max:
max = features[i]
max_feature = i
features[i] /= fsum
# Calculate and save majority topic:
majority_topic = topics[max_feature]
features[-1] = majority_topic
# Save information
turn_features.append(features)
turn_info.append((start_time, stop_time, speaker))
# Reset start time:
time = row[START_IDX].split(".")[0] # Strip ms
start_time = datetime(*strptime(time, "%H:%M:%S")[0:6])
features = np.zeros(num_topics + 1)
topic_index = topics.index(topic)
features[topic_index] += float(1)
time = row[STOP_IDX].split(".")[0] # Strip ms
stop_time = datetime(*strptime(time, "%H:%M:%S")[0:6])
topic_index = topics.index(topic)
features[topic_index] += float(1)
# Append final info:
turn_features.append(features)
turn_info.append((start_time, stop_time, speaker))
return turn_features, turn_info
# Topic information:
def topic_info(filename):
file = open(filename, 'r')
file.readline()
TOPIC_IDX = 5
topics = {}
contents = csv.reader(file, delimiter=',', quotechar='"')
for n, row in enumerate(contents):
topic = row[TOPIC_IDX]
if topic not in topics.keys():
topics[topic] = 1
else:
topics[topic] += 1
return topics.keys()
'''
counts = []
for k in topics.keys():
counts.append(topics[k])
counts = sorted(counts)
counts.reverse()
pylab.scatter(range(len(counts)), counts)
pylab.ylabel("Frequency")
pylab.xlabel("Topic")
pylab.xlim([-1, 25])
pylab.ylim([-10, 500])
pylab.title("Topic Frequency")
pylab.show()
'''
# Return list of (reactions, times):
def rxns(rfile):
file = open(rfile, 'r')
file.readline()
TIME_IDX = 2
RXN_IDX = 1
VOTE_INDEX = 25 # who the user would vote for if he or she had to vote before the debate
reactions_Obama = []
reactions_Romney = []
contents = csv.reader(file, delimiter=',', quotechar='"')
for n, row in enumerate(contents):
time = row[TIME_IDX]
time = time.split(".")[0] # Strip ms
time = time.split(" ")[1] # Strip date
time = datetime(*strptime(time, "%H:%M:%S")[0:6])
reaction = row[RXN_IDX]
would_vote_for = row[VOTE_INDEX]
if would_vote_for == "obama":
reactions_Obama.append((reaction, time))
elif would_vote_for == "romney":
reactions_Romney.append((reaction, time))
return reactions_Obama, reactions_Romney
def plot_reaction_counts(counts):
counts = sorted(counts)
counts.reverse()
pylab.scatter(range(0,len(counts)), counts)
pylab.axis([-10, len(counts)+10, min(counts)-100, max(counts)+1000])
pylab.xlabel('Turn')
pylab.ylabel('Number of Reactions')
pylab.title('Number of Reactions per Turn')
pylab.show()
# LABELING METHODS #####################################################################################################
def reaction_rates(turn_times, reactions):
counts = []
for i in range(len(turn_times)):
count = 0
start = turn_times[i][0]
stop = turn_times[i][1]
for j in range(len(reactions)):
reaction_time = reactions[j][1]
if stop > reaction_time > start:
count += 1
# Reaction rate:
total_time = stop - start
total_time = total_time.total_seconds()
count /= total_time + 1.0
counts.append(count)
return counts
# Label = low (0) / medium (1) / high (2) number of reactions:
def LABEL_by_count(times, reactions):
counts = reaction_rates(times, reactions)
mean = np.median(counts)
labels = []
for i in range(len(counts)):
count = counts[i]
if count < mean:
labels.append(0)
else:
labels.append(1)
return labels
# Label = majority agree with current speaker (1), majority disagree (-1), neutral (0)
def LABEL_by_agreement(times, reactions):
labels = []
speaker_map = {'0':"moderator", '1':"romney", '2':"obama"}
for i in range(len(times)):
start = times[i][0]
stop = times[i][1]
speaker = speaker_map[times[i][2]]
count_for = 0
count_against = 0
for j in range(len(reactions)):
reaction_time = reactions[j][1]
if stop > reaction_time > start:
reaction = reactions[j][0].split(":")
target = reaction[0].lower()
value = reaction[1].lower()
if speaker == target:
if value == "agree":
count_for += 1
elif value == "disagree":
count_against += 1
#print count_for, count_against
if count_for > count_against:
labels.append(1)
elif count_against > count_for:
labels.append(-1)
else:
labels.append(0)
print labels
return labels
# Label =
def LABEL_by_spin_dodge(times, reactions):
counts = []
labels = []
speaker_map = {'0':"moderator", '1':"romney", '2':"obama"}
for i in range(len(times)):
start = times[i][0]
stop = times[i][1]
speaker = speaker_map[times[i][2]]
spin_dodge = 0
for j in range(len(reactions)):
reaction_time = reactions[j][1]
if stop > reaction_time > start:
reaction = reactions[j][0].split(":")
target = reaction[0].lower()
value = reaction[1].lower()
if speaker == target:
if value == "dodge" or value == "spin":
spin_dodge += 1
# Reaction rate:
total_time = stop - start
total_time = total_time.total_seconds()
spin_dodge /= total_time + 1.0
counts.append(spin_dodge)
mean = np.mean(counts)
for i in range(len(counts)):
count = counts[i]
if count > mean:
labels.append(1)
else: labels.append(0)
#print counts
#print labels
return labels
####### TODO Get more features ################
#todo - combine user info with topic info as features
def FEATURES_user_questions():
pass
def FEATURES_all(turn_info, reactions):
for j in range(len(reactions)):
reaction_time = reactions[j][1]
# Label = majority reaction (ex, "Romney:disagree")
def LABEL_by_everything(times, reactions):
pass # TODO - not enough data for this one
########################################################################################################################
def main():
rfile = 'resources/data/reactions_oct3_4project.csv'
reactions_Obama, reactions_Romney = rxns(rfile)
path = "resources/corpora/"
filename = path + "oct3_coded_transcript_sync.csv"
topics = topic_info(filename)
turn_features, turn_info = read_data(filename, topics)
#plot_reaction_counts(counts)
# TODO : SET TO EITHER reactions_Obama OR reactions_Romney:
labels = LABEL_by_spin_dodge(turn_info, reactions_Romney)
# Write features to file:
out = open("topicinfo.csv", 'w')
for i in range(len(turn_features)):
out.write(str(labels[i]) + "\t")
features = turn_features[i]
for j in range(len(features)-1):
# Use topic ID as feature name:
out.write(str(topics[j]) + ":" + str(features[j]) + "\t")
#out.write(str("majority") + ":" + '"' + str(features[-1]) + '"')
out.write('\n')
out.close()
if __name__ == "__main__":
main()