-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmp6.py
68 lines (59 loc) · 2.56 KB
/
mp6.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
# mp6.py
# ---------------
# Licensing Information: You are free to use or extend this projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to the University of Illinois at Urbana-Champaign
#
# Created by Justin Lizama ([email protected]) on 10/27/2018
import sys
import argparse
import configparser
import copy
import numpy as np
import reader
import neuralnet_part1 as p1
import neuralnet_part2 as p2
import torch
"""
This file contains the main application that is run for this MP.
"""
def compute_accuracies(predicted_labels,dev_set,dev_labels):
yhats = predicted_labels
if len(yhats) != len(dev_labels):
print("Lengths of predicted labels don't match length of actual labels", len(yhats),len(dev_labels))
return 0.,0.,0.,0.
accuracy = np.mean(yhats == dev_labels)
tp = np.sum([yhats[i] == dev_labels[i] and yhats[i] == 1 for i in range(len(dev_labels))])
precision = tp / np.sum([yhats[i]==1 for i in range(len(dev_labels))])
recall = tp / (np.sum([yhats[i] != dev_labels[i] and yhats[i] == 0 for i in range(len(dev_labels))]) + tp)
f1 = 2 * (precision * recall) / (precision + recall)
return accuracy,f1,precision,recall
def main(args):
train_set, train_labels, dev_set,dev_labels = reader.load_dataset(args.dataset_file)
if args.part == 1:
p = p1
else:
p = p2
print(train_set)
print("length of train set",len(train_set))
train_set = torch.tensor(train_set,dtype=torch.float32)
train_labels = torch.tensor(train_labels,dtype=torch.int64)
dev_set = torch.tensor(dev_set,dtype=torch.float32)
_,predicted_labels,net = p.fit(train_set,train_labels, dev_set,args.max_iter)
accuracy,f1,precision,recall = compute_accuracies(predicted_labels,dev_set,dev_labels)
print("Accuracy:",accuracy)
print("F1-Score:",f1)
print("Precision:",precision)
print("Recall:",recall)
torch.save(net, "net.model")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='CS440 MP6 Neural Net')
parser.add_argument('--dataset', dest='dataset_file', type=str, default = '../data/mp6_data',
help='the directory of the training data')
parser.add_argument('--max_iter',dest="max_iter", type=int, default = 500,
help='Maximum iterations - default 500')
parser.add_argument('--part', dest="part", type=int, default=1,
help='Part 1 or Part 2')
args = parser.parse_args()
main(args)