-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
105 lines (68 loc) · 2.62 KB
/
main.py
File metadata and controls
105 lines (68 loc) · 2.62 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
from lib.feedforward.Feedforward import Feedforward
from lib.transformers.Transformers import Transformers
from optparse import OptionParser
import regex as re
import random
DATASET = "imdb/dataset.csv"
MODES = ["bag_of_words", "tf_idf", "transformers"]
def main():
options = read_commands()
# Get an unbiased sample of the data
data = random.sample(options.data, options.sample)
train, valid, test = split(data)
# Feedforward
if len(data) <= 50:
leave_one_out(data, options)
elif options.mode == "transformers":
transformers = Transformers(data)
transformers.train(train, valid, options.epochs, 100)
else:
network = Feedforward(data, options.mode)
print("Test-set's F1-score before training: %.3f" % network.eval(test))
network.train(train, valid, options.epochs, 1, verbose=True)
print("Test-set's F1-score after training: %.3f" % network.eval(test))
def read_commands():
parser = OptionParser("%prog -d <dataset>")
parser.add_option("-d", dest="dataset", help="Dataset to analyze")
parser.add_option("-e", type="int", default=10, dest="epochs", help="Number of epochs")
parser.add_option("-s", type="int", default=5000, dest="sample", help="Number of entries to use")
parser.add_option("-m", type="int", default=0, dest="mode", help="Bag of words (0), Tf-idf (1)")
options, args = parser.parse_args()
try:
options.mode = MODES[options.mode]
except:
print("Incorrect mode")
exit(0)
with open(options.dataset or DATASET) as dataset:
options.data = parse(dataset.read().splitlines())
return options
def parse(dataset):
data = []
for entry in dataset:
text = re.findall('\p{L}+', entry.lower())
data.append((" ".join(text), int(entry[-1])))
return data
def split(data):
chunk = len(data) // 5
train = data[:3 * chunk]
valid = data[3 * chunk:4 * chunk]
test = data[4 * chunk:]
return train, valid, test
def leave_one_out(data, options):
scores = []
for n in range(5):
score = 0
for i in range(len(data)):
train = data[:i] + data[i+1:]
valid = [data[i]]
if options.mode == "transformers":
network = Transformers(data)
else:
network = Feedforward(data, options.mode)
score += network.train(train, valid, options.epochs, 10)[0]
score /= len(data)
scores.append(score)
print("[%d]\t%.4f" % (n + 1, score))
print("Average score: %.4f" % (sum(scores) / 5))
if __name__ == "__main__":
main()