forked from ginesiametlle/semtagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_stats.py
195 lines (167 loc) · 7.29 KB
/
data_stats.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
#!/usr/bin/python3
# this script produces graphical visualizations
import sys
import os
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot as plt
from collections import Counter
import pygal
import cairosvg
import seaborn as sns
from sklearn.metrics import confusion_matrix
def plot_dist_tags(sents, vocab, outimg, outfile, padwords=[]):
"""
Plot the amount of IV and OOV words per tag in a dataset
Inputs:
- sents: list of sentences represented as a list of (word, tag, sym) items
- vocab: set containing words in the vocabulary
- outimg: output image
- outfile: output text file
- padwords: set of words to be ignored
"""
# compute the number of IV and OOV words per tag
count = {}
for sent in sents:
if sent:
for word, tag, sym in sent:
if word not in padwords:
if tag not in count:
count[tag] = [0,0]
count[tag][0] += 1
if sym not in vocab:
count[tag][1] += 1
# output in svg format
xdata = sorted(count.keys(), key=lambda x: count[x][0], reverse=True)
ydata_oov = list([count[x][1] for x in xdata])
ydata_rest = list([count[x][0] - count[x][1] for x in xdata])
line_chart = pygal.StackedBar(width=1300, height=800, x_label_rotation=-45,
y_title='Number of words')
line_chart.x_labels = xdata
line_chart.add('OOVs', ydata_oov)
line_chart.add('IVs + OOVs', ydata_rest)
# circumvent potential svg styling problems
line_chart.render_to_file(outimg)
cairosvg.svg2svg(url=outimg, write_to=outimg)
# output in text format
with open(outfile, 'w') as tfile:
tfile.write("tag\t#OOVs\t#IVs\t#words\tratio\n")
for i in range(len(xdata)):
tfile.write(str(xdata[i]) + '\t')
tfile.write(str(ydata_oov[i]) + '\t')
tfile.write(str(ydata_rest[i]) + '\t')
tfile.write(str(ydata_oov[i] + ydata_rest[i]) + '\t')
tfile.write(str(ydata_oov[i] / (ydata_oov[i] + ydata_rest[i])) + '\n')
def plot_dist_lengths(lengths, length_limit, x_step, max_x, y_step, max_y, outimg):
"""
Plot a length distribution over sentences
Inputs:
- lengths: list of numerical lenghts
- length_limit: maximum allowed length
- x_step: step in the horizontal axis
- max_x: maximum value in the horizontal axis
- y_step: step in the vertical axis
- max_y: maximum value in the vertical axis
- outimg: output image
"""
# count number of occurrences for each length value
c = Counter(lengths)
max_val = min(max_x, max(max_x, max(c.keys())))
# output in svg format
xdata = list(range(1, max_val + x_step + 1))
ydata_used = [c[k] if k in c and k <= length_limit else 0 for k in xdata]
ydata_unused = [c[k] if k in c and k > length_limit else 0 for k in xdata]
line_chart = pygal.StackedBar(width=1300, height=800, x_label_rotation=-45,
x_title='Number of words', y_title='Number of sentences',
show_minor_x_labels=False)
line_chart.x_labels = xdata
line_chart.x_labels_major = list(set([x // x_step * x_step for x in xdata]))
line_chart.y_labels = range(0, max_y + 1, y_step)
line_chart.add('Truncated data', ydata_unused)
line_chart.add('Unchanged data', ydata_used)
# circumvent potential svg styling problems
line_chart.render_to_file(outimg)
cairosvg.svg2svg(url=outimg, write_to=outimg)
def plot_accuracy(history, keys, labels, test_acc, outimg, outfile):
"""
Plot the obtained accuracy scores against training epochs
Inputs:
- history: object obtained from calling Keras fit() function
- keys: key values to access the metrics in history
- labels: names of the metrics which match `keys`
- test_acc: accuracy obtained on the test set
- outimg: output image
- outfile: output text file
"""
# build chart
hist = pd.DataFrame(history.history)
chart = pygal.Line(width=1300, height=800, x_label_rotation=0,
x_title='Number of training epochs', y_title='Sem-tagging accuracy')
xdata = [x + 1 for x in range(len(hist[keys[0]]))]
chart.x_labels = xdata
# plot all metrics
for i in range(len(keys)):
key = keys[i]
label = labels[i]
chart.add(label, hist[key], show_dots=False,
stroke_style={'width': 4, 'dasharray': '3, 8', 'linecap': 'round', 'linejoin': 'round'})
# plot a horizontal line representing accuracy on the test set
if test_acc > 0:
ytest=[test_acc] * len(xdata)
chart.add(None, ytest, show_dots=False, stroke_style={'width': 2})
# output in svg format
chart.render_to_file(outimg)
cairosvg.svg2svg(url=outimg, write_to=outimg)
# output in text format
with open(outfile, 'w') as tfile:
header = str(keys[0]) + ''.join(["\t" + str(key) for key in keys[1:]])
tfile.write(header + '\n')
for i in range(len(hist[keys[0]])):
tfile.write(str(hist[keys[0]][i]))
for key in keys[1:]:
tfile.write("\t" + str(hist[key][i]))
tfile.write("\n")
def plot_confusion_matrix(act, pred, classes, ignore_class, ymap, outfile, vocab=[], normalize=True):
"""
Plot a confusion matrix
Inputs:
- act: array of actual numerical vectors
- pred: array of predicted numerical vectors
- classes: set containing all output classes to consider
- ignore_class: numerical value to be ignored
- outfile: output file
- ymap: map to class numerical values
- vocab: set containing all words in the vocabulary
- normalize: normalize confusion matrix
"""
# turn class numerical values into readable strings using the mapping provided
y_true = act
y_pred = pred
if ymap:
y_pred = []
y_true = []
for i in range(len(act)):
for j in range(len(act[i])):
if act[i][j] != ignore_class:
y_pred += [ymap[pred[i][j]]]
y_true += [ymap[act[i][j]]]
# compute confusion matrix
cm = confusion_matrix(y_true, y_pred, labels=classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("[INFO] Normalized confusion matrix")
else:
print('[INFO] Confusion matrix without normalization')
cm = pd.DataFrame(cm, index=classes, columns=classes)
# transform confusion matrix to a heatmap and output
fig, ax = plt.subplots(figsize=(25, 25))
sns.set(font_scale=2)
b = sns.heatmap(cm, fmt='', ax=ax, cmap="BuPu", square=True, xticklabels=True, yticklabels=True)
b.set_xlabel("Predicted sem-tags", fontsize=28)
b.set_ylabel("Actual sem-tags", fontsize=28)
b.set_xticklabels(b.get_yticklabels(), fontsize=13)
b.set_yticklabels(b.get_yticklabels(), fontsize=13)
plt.draw()
plt.savefig(outfile)