-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainShutterModel.py
93 lines (72 loc) · 2.39 KB
/
trainShutterModel.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
import getopt
import os
import re
import sys
import numpy as np
from scipy.misc.pilutil import imread
from sklearn import svm
from sklearn.externals import joblib
from sklearn.model_selection import train_test_split
def flatten(filename):
img = imread(filename)
return img.flatten()
def target(filename, regex):
m = regex.match(filename)
if m is not None:
return m.group()
else:
return "NA"
def trainInfo(path, regex):
flat = []
targ = []
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
flat.append(flatten(os.path.join(dirpath, filename)))
targ.append(target(filename, regex))
return flat, targ
def readArgs():
path = ''
try:
opts, args = getopt.getopt(sys.argv[1:], "hp:", ["path="])
except getopt.GetoptError:
print sys.argv[0], '-h (for help)'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print sys.argv[0], '-p <path>'
sys.exit()
elif opt in ("-p", "--path"):
path = arg
return path
if __name__ == '__main__':
# read command line options
path = readArgs()
random_state = np.random.RandomState(0)
regex = re.compile("(closed|open)")
flat, targ = trainInfo(path, regex)
X_train, X_test, y_train, y_test = train_test_split(flat, targ, test_size = 0.3, random_state = random_state)
clf = svm.SVC(kernel='linear', C=1)
clf.fit(X_train, y_train)
joblib.dump(clf, 'shutterModel.pkl')
# evaluate model
y_score = clf.predict(X_test)
truePositives = 0
falsePositives = 0
falseNegatives = 0
n = len(y_test)
for i in range(0, n):
if (y_test[i] == 'closed') and (y_score[i] == 'closed'):
truePositives += 1
elif (y_test[i] == 'closed') and (y_score[i] == 'open'):
falsePositives += 1
elif (y_test[i] == 'open') and (y_score[i] == 'closed'):
falseNegatives += 1
precision = float(truePositives) / (truePositives + falsePositives)
recall = float(truePositives) / (truePositives + falseNegatives)
fscore = float(2*(precision*recall)) / (precision + recall)
print("TruePositives: ", truePositives)
print("FalsePositives: ", falsePositives)
print("falseNegatives: ", falseNegatives)
print("Precision: ", precision)
print("Recall: ", recall)
print("F-Score: ", fscore)