-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCRF.py
187 lines (154 loc) · 5.41 KB
/
CRF.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
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
# -*- coding: utf-8 -*-
import sys, glob, csv, os
import numpy as np
import sklearn
import scipy.stats
from sklearn.metrics import make_scorer, roc_curve, auc
import sklearn_crfsuite
from sklearn_crfsuite import scorers
from sklearn_crfsuite import metrics
import matplotlib.pyplot as plt
def train_and_test_crf(test_name):
print("===== test_name:{0} =====".format(test_name))
X_train_raw, Y_train_raw = read_train_data(test_name)
X_train, Y_train = [],[]
for i in range(len(X_train_raw) - 10):
X_train.append([(lambda x: str(1) if x > float(0.5) else str(0))(X_train_raw[i + k]) for k in range(10)])
Y_train.append([str(Y_train_raw[i + k]) for k in range(10)])
crf = sklearn_crfsuite.CRF(
algorithm = 'lbfgs',
c1 = 0.1,
c2 = 0.1,
max_iterations = 100,
all_possible_transitions=True
)
print("train start...")
crf.fit(X_train, Y_train)
print("test start...")
X_test_raw, Y_test_raw = read_test_data(test_name)
X_test, Y_test = [],[]
for i in range(len(X_test_raw) - 10):
X_test.append([(lambda x: str(1) if x > float(0.5) else str(0))(X_test_raw[i + k]) for k in range(10)])
Y_test.append([str(Y_test_raw[i + k]) for k in range(10)])
print("test data num: {0}".format(len(X_test)))
Y_pred = crf.predict(X_test)
#F score
miss_count = 0
Y_pred = [int(Y[0]) for Y in Y_pred]
Y_test = [int(Y[0]) for Y in Y_test]
tp,tn,fp,fn = 0,0,0,0
count = 0
for pred in Y_pred:
if pred == Y_test[count]:
if pred == 0:
tn += 1
else:
tp += 1
else:
if pred == 0:
fn += 1
else:
fp += 1
miss_count += 1
count += 1
print("miss count : {0}".format(miss_count))
accuracy = (tp + tn) / (tp + fn + fp + tn)
if tp + fp != 0:
precision = tp / (tp + fp)
if tp + fn == 0:
recall = 0
else:
recall = tp / (tp + fn)
if recall + precision == 0:
f_value = 0
else:
f_value = (2 * recall * precision) / (recall + precision)
else:
precision = 0
recall = 0
f_value = 0
result_path = 'result/CRF/{0}'.format(test_name)
if not os.path.exists(result_path):
os.mkdir(result_path)
f = open(os.path.join(result_path,'result.txt'.format(test_name)), 'w')
f.write('\nTHRESHOLD : 0.5')
f.write('\nTrue Negative = {0:5d} | False Negative = {1:5d}'.format(tn,fn))
f.write('\nFalse Positive = {0:5d} | True Positive = {1:5d}\n'.format(fp,tp))
f.write('\nAccuracy = %01.4f' % accuracy)
f.write('\nPrecision = %01.4f' % precision)
f.write('\nRecall = %01.4f' % recall)
f.write('\nF_value = %01.4f\n' % f_value)
#csvファイルに結果を保存(正解クラスと識別結果のペア)
result_pairs = []
for i in range(len(Y_test)):
result_pairs.append([Y_test[i], Y_pred[i]])
np.savetxt(os.path.join(result_path,'result.csv'),result_pairs,delimiter=',')
#ROCカーブを計算、画像で保存
#fpr, tpr, thresholds = roc_curve(Y_test, Y_pred)
#roc_auc = auc(fpr, tpr)
#plt.clf()
#plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)
#plt.plot([0, 1], [0, 1], 'k--')
#plt.xlim([0.0, 1.0])
#plt.ylim([0.0, 1.0])
#plt.xlabel('False Positive Rate')
#plt.ylabel('True Positive Rate')
#plt.title('ROC curve')
#plt.legend(loc="lower right")
#plt.savefig(os.path.join(result_path,'ROC.png'))
plt.clf()
plt.plot(Y_test[0:300], label='Ground Truth')
plt.plot(Y_pred[0:300], label='prediction')
plt.legend(loc="lower right")
plt.savefig(os.path.join(result_path,'vaisualize.png'))
def read_train_data(test_name):
csv_paths = glob.glob('dataset/*')
X_train,Y_train = [],[]
for csv_path in csv_paths:
if csv_path.find(test_name) > -1:
continue
f = open(csv_path, 'r')
reader = csv.reader(f)
for row in reader:
if float(row[1]) == 0:
continue
X_train.append(float(row[1]))
Y_train.append(int(float(row[0])))
#X_train = np.array(X_train, dtype=np.float32)
#Y_train = np.array(Y_train, dtype=np.uint8)
return X_train, Y_train
def read_test_data(test_name):
X_test,Y_test = [],[]
f = open('dataset/{0}.csv'.format(test_name), 'r')
reader = csv.reader(f)
for row in reader:
if float(row[1]) == 0:
continue
X_test.append(float(row[1]))
Y_test.append(int(float(row[0])))
X_test = np.array(X_test, dtype=np.float32)
Y_test = np.array(Y_test, dtype=np.uint8)
return X_test, Y_test
if __name__ == '__main__':
if len(sys.argv) == 2:
test_name = sys.argv[1]
train_and_test_crf(test_name)
else:
test_names = ['Avec',
'Aziz',
'Derek',
'Elle',
'Emma',
'Hiyane',
'Imaizumi',
'James',
'Kendall',
'Kitazumi',
'Liza',
'Neil',
'Ogawa',
'Selena',
'Shiraishi',
'Taylor']
for test_name in test_names:
train_and_test_crf(test_name)