[735bb5]: / src / evaluation / plots / linecharts.py

Download this file

272 lines (227 with data), 7.6 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
# Base Dependencies
# -----------------
import numpy as np
from typing import Optional, Dict
from pathlib import Path
from os.path import join as pjoin
# Local Dependencies
# ------------------
from evaluation.io import (
collect_al_series,
collect_pl_series_ddi,
collect_pl_series_n2c2,
collect_step_times_series,
)
# 3rd-Party Dependencies
# ----------------------
import matplotlib.pyplot as plt
import seaborn as sns
# Constants
# ---------
from constants import METHODS_NAMES, N2C2_REL_TYPES
COLOR_PALETTE = "Set2"
def _iter_time_linechart_with_error_bands(
results: Dict,
legend: bool = True,
title: Optional[str] = None,
legend_title: Optional[str] = None,
output_file: Optional[Path] = None,
):
ALPHA = 0.1
DDI_TRAIN_SIZE = 27705
sns.set()
sns.set_style("ticks") # grid style
colors = sns.color_palette(COLOR_PALETTE)
markers = ["x", "v", "o", "P"]
linestyles = [
"solid",
"dotted",
"dashed",
"dashdot",
]
# plot active learning performance
N = 0
for x in results.keys():
if len(results[x]["mean"]) > N:
N = len(results[x]["mean"])
x = np.linspace(2.5, 50, num=N)
for i, q_strategy in enumerate(results.keys()):
mean = results[q_strategy]["mean"]
std = results[q_strategy]["std"]
plt.plot(
x,
mean,
linestyle=linestyles[i],
color=colors[i],
marker=markers[i],
label=q_strategy,
)
plt.fill_between(x, mean - std, mean + std, color=colors[i], alpha=ALPHA)
sns.despine() # remove top and right axis
plt.ylabel("Step Time (minutes)")
plt.xlabel("# of annotated samples (out of 27,705)")
# set axis to 0%, 10%, 20% 30%, 40%, 50% of annotated dtaset
xticks = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
xlabels = [f"{str(int(round(x * DDI_TRAIN_SIZE / 100)))} ({x}%)" for x in xticks]
plt.xticks(
xticks,
labels=xlabels,
rotation=45,
)
plt.legend(title=legend_title, loc="best")
if title:
plt.title(title)
if output_file:
plt.savefig(output_file, bbox_inches="tight")
else:
plt.show()
plt.clf()
def _al_linechart_with_error_bands(
al_results: Dict,
pl_results: Dict,
y_label: str = "F1 Score",
legend: bool = True,
title: Optional[str] = None,
output_file: Optional[Path] = None,
):
"""Plots a line chart with error bands
Args:
results (Dict): dicitonary containing the results for each query strategy
output_file (Optional[str], optional): path of the output file. Defaults to None.
"""
ALPHA = 0.1
sns.set()
sns.set_style("white") # grid style
colors = sns.color_palette(COLOR_PALETTE)
markers = ["x", "v", "P", ]
linestyles = [
"-",
"--",
"-.",
]
# plot active learning performance
N = 0
for x in al_results.keys():
if len(al_results[x]["mean"]) > N:
N = len(al_results[x]["mean"])
x = np.linspace(2.5, 50, num=N)
for i, q_strategy in enumerate(al_results.keys()):
mean = al_results[q_strategy]["mean"]
std = al_results[q_strategy]["std"]
plt.plot(
x,
mean,
linestyle=linestyles[i],
color=colors[i],
marker=markers[i],
label=q_strategy,
)
plt.fill_between(x, mean - std, mean + std, color=colors[i], alpha=ALPHA)
# plot passive learning performance
plt.axhline(
y=pl_results["mean"], color="black", linestyle="dashed", label="100% Data"
)
sns.despine() # remove top and right axis
plt.ylabel(y_label)
plt.xlabel("% annotated dataset")
# set axis to 0%, 10%, 20% 30%, 40%, 50% of annotated dtaset
plt.xticks(
[0, 10, 20, 30, 40, 50],
labels=["0", "10", "20", "30", "40", "50"],
)
plt.legend(loc="lower right")
if title:
plt.title(title)
if output_file:
plt.savefig(output_file, bbox_inches="tight")
else:
plt.show()
plt.clf()
# Main Functions
# --------------
def al_linecharts_n2c2():
"""Plots the line charts for the N2C2 corpus"""
corpus = "n2c2"
for method in METHODS_NAMES.keys():
# load passive learning results
pl_results = collect_pl_series_n2c2(
Path(pjoin("results", corpus, "all", method))
)
# for each relation type
for rel_type in N2C2_REL_TYPES:
output_file = Path(
pjoin("results", corpus, rel_type, f"al_{method}_n2c2_{rel_type}.png")
)
title = f"Relation = {rel_type}, Method = {METHODS_NAMES[method]}"
# load AL results
al_results = collect_al_series(
Path(pjoin("results", corpus, rel_type, method)), metric="f1"
)
# plot results
_al_linechart_with_error_bands(
al_results=al_results,
pl_results=pl_results[rel_type],
title=title,
output_file=output_file,
)
# micro average
# load AL results
al_results = collect_al_series(
Path(pjoin("results", corpus, "all", method)), metric="Micro_f1"
)
output_file = Path(pjoin("results", corpus, "all", f"al_{method}_n2c2.png"))
title = f"Method = {METHODS_NAMES[method]}"
# plot results
_al_linechart_with_error_bands(
al_results=al_results,
pl_results=pl_results["Micro"],
title=title,
y_label="Micro F1 Score",
output_file=output_file,
)
def al_linecharts_ddi():
"""Plots the line charts for the DDI Extraction corpus"""
corpus = "ddi"
for method in METHODS_NAMES.keys():
title = f"Method = {METHODS_NAMES[method]}"
results_path = Path(pjoin("results", corpus, method))
output_file = Path(pjoin("results", corpus, f"al_{method}_ddi.png"))
# load results
al_results = collect_al_series(results_path, metric="Micro_f1")
pl_results = collect_pl_series_ddi(results_path)
# plot results
_al_linechart_with_error_bands(
al_results=al_results,
pl_results=pl_results,
y_label="Micro F1 Score",
legend=(method == "bert"),
title=title,
output_file=output_file,
)
def iter_time_linecharts():
results = collect_step_times_series(Path(pjoin("results", "ddi")))
for method in METHODS_NAMES.keys():
# all strtategies with one method
output_file = Path(
pjoin("results", "ddi", method, f"iter_time_{method}_ddi.png")
)
_iter_time_linechart_with_error_bands(
results[method],
title=f"Method = {METHODS_NAMES[method]}",
legend_title="Strategy",
output_file=output_file,
)
for strategy in ["random", "LC", "BatchBALD"]:
# LC strategy with all methods
output_file = Path(pjoin("results", "ddi", f"iter_time_{strategy}_ddi.png"))
lc_results = {}
for method in METHODS_NAMES.keys():
if strategy == "BatchBALD" and method == "rf":
continue
lc_results[method] = results[method][strategy]
_iter_time_linechart_with_error_bands(
lc_results,
title=f"Query Strategy = {strategy}",
legend_title="Method",
output_file=output_file,
)