-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEarlyfusion_classifier.py
More file actions
75 lines (60 loc) · 2.37 KB
/
Copy pathEarlyfusion_classifier.py
File metadata and controls
75 lines (60 loc) · 2.37 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
# encoding=utf8
import os
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import KFold
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, precision_score, recall_score, f1_score
data_dir = './data'
print("Loading Labels...")
with open(os.path.join(data_dir, 'labels.txt'), 'r', encoding = "utf-8") as f:
y = np.array(f.readlines())
print("Loading Text...")
with open(os.path.join(data_dir, 'EF_samples_processed.txt'), 'r', encoding = "utf-8") as f:
x = f.readlines()
print("Extract features...")
x_feats = TfidfVectorizer().fit_transform(x)
print(x_feats.shape)
print("Start training and predict...")
kf = KFold(n_splits=10)
# Naive Bayes Classifier
avg_p = 0
avg_r = 0
avg_f1 = 0
for train, test in kf.split(x_feats):
model = MultinomialNB().fit(x_feats[train], y[train])
predicts = model.predict(x_feats[test])
avg_p += precision_score(y[test],predicts, average='macro')
avg_r += recall_score(y[test],predicts, average='macro')
avg_f1 += f1_score(y[test],predicts, average='macro')
print('Average Precision is %f.' %(avg_p/10.0))
print('Average Recall is %f.' %(avg_r/10.0))
print('Average f1 score is %f.' %(avg_f1/10.0))
# KNN Classifier
avg_p = 0
avg_r = 0
avg_f1 = 0
for train, test in kf.split(x_feats):
model = KNeighborsClassifier().fit(x_feats[train], y[train])
predicts = model.predict(x_feats[test])
avg_p += precision_score(y[test],predicts, average='macro')
avg_r += recall_score(y[test],predicts, average='macro')
avg_f1 += f1_score(y[test],predicts, average='macro')
print('Average Precision is %f.' %(avg_p/10.0))
print('Average Recall is %f.' %(avg_r/10.0))
print('Average f1 score is %f.' %(avg_f1/10.0))
# Randomforest Classifier
avg_p = 0
avg_r = 0
avg_f1 = 0
for train, test in kf.split(x_feats):
model = RandomForestClassifier().fit(x_feats[train], y[train])
predicts = model.predict(x_feats[test])
avg_p += precision_score(y[test],predicts, average='macro')
avg_r += recall_score(y[test],predicts, average='macro')
avg_f1 += f1_score(y[test],predicts, average='macro')
print('Average Precision is %f.' %(avg_p/10.0))
print('Average Recall is %f.' %(avg_r/10.0))
print('Average f1 score is %f.' %(avg_f1/10.0))