Repository navigation
Expand file tree
/
Copy pathutil.py
More file actions
125 lines (100 loc) · 3.84 KB
/
Copy pathutil.py
File metadata and controls
125 lines (100 loc) · 3.84 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
from numpy import logical_and, sum as t_sum
import numpy as np
import os
import shutil
import urllib
import subprocess
from typing import List
from datasets import load_dataset
import random
from collections import defaultdict
from tqdm import tqdm
from torch import LongTensor
from typing import List, Dict
def accuracy(predicted_labels, true_labels):
"""
Accuracy is correct predictions / all predicitons
"""
correct_count = 0
for pred, label in zip(predicted_labels, true_labels):
correct_count += int(pred == label)
return correct_count/len(true_labels) if len(true_labels) > 0 else 0.
def precision(predicted_labels, true_labels, which_label=1):
"""
Precision is True Positives / All Positives Predictions
"""
pred_which = np.array([pred == which_label for pred in predicted_labels])
true_which = np.array([lab == which_label for lab in true_labels])
denominator = t_sum(pred_which)
if denominator:
return t_sum(logical_and(pred_which, true_which))/denominator
else:
return 0.
def recall(predicted_labels, true_labels, which_label=1):
"""
Recall is True Positives / All Positive Labels
"""
pred_which = np.array([pred == which_label for pred in predicted_labels])
true_which = np.array([lab == which_label for lab in true_labels])
denominator = t_sum(true_which)
if denominator:
return t_sum(logical_and(pred_which, true_which))/denominator
else:
return 0.
def f1_score(predicted_labels, true_labels, which_label=1):
"""
F1 score is the harmonic mean of precision and recall
"""
P = precision(predicted_labels, true_labels, which_label=which_label)
R = recall(predicted_labels, true_labels, which_label=which_label)
if P and R:
return 2*P*R/(P+R)
else:
return 0.
def avg_f1_score(predicted_labels: List[int], true_labels: List[int], classes: List[int]):
"""
Calculate the f1-score for each class and return the average of it
:return: float
"""
raise NotImplementedError("Calculate the f1-score for each class and return the average of it")
def download_zip(url: str, dir_path: str):
import zipfile
if url.endswith('zip'):
print('Downloading dataset file')
path_to_zip_file = 'downloaded_file.zip'
# Download the dataset zipped file
urllib.request.urlretrieve(url, path_to_zip_file)
# Unzip the dataset
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
zip_ref.extractall('./')
# Delete any existing sem eval folder
if os.path.exists(dir_path):
shutil.rmtree(dir_path)
# Remove zip file
if os.path.exists(path_to_zip_file):
os.remove(path_to_zip_file)
# Rename sem eval folder name
if os.path.exists(dir_path + '-master'):
shutil.move(dir_path + '-master', dir_path)
elif os.path.exists(dir_path + '-main'):
shutil.move(dir_path + '-main', dir_path)
print(f'Downloaded dataset to {dir_path}')
def git(*args):
return subprocess.check_call(['git'] + list(args))
def get_snli(train=10000, validation=1000, test=1000):
snli = load_dataset('snli')
train_dataset = get_even_datapoints(snli['train'], train)
validation_dataset = get_even_datapoints(snli['validation'], validation)
test_dataset = get_even_datapoints(snli['test'], test)
return train_dataset, validation_dataset, test_dataset
def get_even_datapoints(datapoints, n):
random.seed(42)
dp_by_label = defaultdict(list)
for dp in tqdm(datapoints, desc='Reading Datapoints'):
dp_by_label[dp['label']].append(dp)
unique_labels = [0, 1, 2]
split = n//len(unique_labels)
result_datapoints = []
for label in unique_labels:
result_datapoints.extend(random.sample(dp_by_label[label], split))
return result_datapoints