-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLatefusion_classifier.py
More file actions
218 lines (189 loc) · 7.85 KB
/
Copy pathLatefusion_classifier.py
File metadata and controls
218 lines (189 loc) · 7.85 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
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# 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
#################### Load pre-processed data ########################
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, 'samples_processed.txt'), 'r', encoding = "utf-8") as f_text:
x_text = f_text.readlines()
print("Loading user descriptions...")
with open(os.path.join(data_dir, 'description_processed.txt'), 'r', encoding = "utf-8") as f_description:
x_description = f_description.readlines()
print("Loading hashtags...")
with open(os.path.join(data_dir, 'hashtags_processed.txt'), 'r', encoding = "utf-8") as f_hashtag:
x_hashtag = f_hashtag.readlines()
print("Loading location features...")
with open(os.path.join(data_dir, 'geo_processed.txt'), 'r', encoding = "utf-8") as f_geo:
x_geo = f_geo.readlines()
print("Extract features...")
x_text_feats = TfidfVectorizer().fit_transform(x_text)
x_description_feats = TfidfVectorizer().fit_transform(x_description)
x_hashtag_feats = TfidfVectorizer().fit_transform(x_hashtag)
x_geo_feats = TfidfVectorizer().fit_transform(x_geo)
print(x_text_feats.shape)
print(x_description_feats.shape)
print(x_hashtag_feats.shape)
print(x_geo_feats.shape)
print("Start training and predict...")
kf = KFold(n_splits=10)
#################### Optimising different ML model ########################
#Model_test = [MultinomialNB(), KNeighborsClassifier(), RandomForestClassifier()]
#
## Classifier for text
#for modelx in Model_test:
# text_pred = []
# avg_p = 0
# avg_r = 0
# for train, test in kf.split(x_text_feats):
# model = modelx.fit(x_text_feats[train], y[train])
# predicts = model.predict(x_text_feats[test])
# #print(classification_report(y[test],predicts))
# avg_p += precision_score(y[test],predicts, average='macro')
# avg_r += recall_score(y[test],predicts, average='macro')
#
# print('Average Precision text is %f.' %(avg_p/10.0))
# print('Average Recall text is %f.' %(avg_r/10.0))
#
#
## Classifier for user description
#for modelx in Model_test:
# description_pred = []
# avg_p = 0
# avg_r = 0
# for train, test in kf.split(x_description_feats):
# model = modelx.fit(x_description_feats[train], y[train])
# predicts = model.predict(x_description_feats[test])
# #print(classification_report(y[test],predicts))
# avg_p += precision_score(y[test],predicts, average='macro')
# avg_r += recall_score(y[test],predicts, average='macro')
#
# print('Average Precision description is %f.' %(avg_p/10.0))
# print('Average Recall description is %f.' %(avg_r/10.0))
#
#
## Classifier for hash tags
#for modelx in Model_test:
# hashtag_pred = []
# avg_p = 0
# avg_r = 0
# for train, test in kf.split(x_hashtag_feats):
# model = modelx.fit(x_hashtag_feats[train], y[train])
# predicts = model.predict(x_hashtag_feats[test])
# #print(classification_report(y[test],predicts))
# avg_p += precision_score(y[test],predicts, average='macro')
# avg_r += recall_score(y[test],predicts, average='macro')
#
# print('Average Precision hashtag is %f.' %(avg_p/10.0))
# print('Average Recall hashtag is %f.' %(avg_r/10.0))
#
#
## Classifier for location
#for modelx in Model_test:
# geo_pred = []
# avg_p = 0
# avg_r = 0
# for train, test in kf.split(x_geo_feats):
# model = modelx.fit(x_geo_feats[train], y[train])
# predicts = model.predict(x_geo_feats[test])
# #print(classification_report(y[test],predicts))
# avg_p += precision_score(y[test],predicts, average='macro')
# avg_r += recall_score(y[test],predicts, average='macro')
#
# print('Average Precision location is %f.' %(avg_p/10.0))
# print('Average Recall location is %f.' %(avg_r/10.0))
# Based on the optimisation, the best model for Text, description, hashtags is Niave Bayes and location is random forest
##################### Train final model ###############################
# Classifier for text
text_pred = np.empty([0, 10])
for train, test in kf.split(x_text_feats):
model = MultinomialNB().fit(x_text_feats[train], y[train])
predicts = model.predict_proba(x_text_feats[test])
text_pred = np.concatenate((text_pred, predicts))
# Classifier for user description
description_pred = np.empty([0, 10])
for train, test in kf.split(x_description_feats):
model = MultinomialNB().fit(x_description_feats[train], y[train])
predicts = model.predict_proba(x_description_feats[test])
description_pred = np.concatenate((description_pred, predicts))
# Classifier for hash tags
hashtag_pred = np.empty([0, 10])
for train, test in kf.split(x_hashtag_feats):
model = MultinomialNB().fit(x_hashtag_feats[train], y[train])
predicts = model.predict_proba(x_hashtag_feats[test])
hashtag_pred = np.concatenate((hashtag_pred, predicts))
# Classifier for location
geo_pred = np.empty([0, 10])
for train, test in kf.split(x_geo_feats):
modelG = RandomForestClassifier().fit(x_geo_feats[train], y[train])
predicts = modelG.predict_proba(x_geo_feats[test])
geo_pred = np.concatenate((geo_pred, predicts))
# Assign different weights to different classifer
grid = np.array([(T, D, H, G) for T in np.arange(0,1,0.05) for D in np.arange(0,1,0.05) for H in np.arange(0,1,0.05) for G in np.arange(0,1,0.05)])
grid_new = []
for i in range(len(grid)):
if sum(grid[i]) == 1:
grid_new.append(grid[i])
precisions = []
recalls = []
f1_scores = []
y = np.float64(y)
for i in range(len(grid_new)):
combine_pred = grid_new[i][0]*text_pred + grid_new[i][1]*description_pred + grid_new[i][2]*hashtag_pred + grid_new[i][3]*geo_pred
prediction = np.apply_along_axis(np.argmax, 1, combine_pred)
avg_p = precision_score(y, prediction, average='macro')
avg_r = recall_score(y, prediction, average='macro')
avg_f1 = f1_score(y, prediction, average='macro')
precisions.append(avg_p)
recalls.append(avg_r)
f1_scores.append(avg_f1)
opt_id = np.argmax(f1_scores)
print(grid_new[opt_id])
print('Optimal Precision is %f.' %precisions[opt_id])
print('Optimal Recall is %f.' %recalls[opt_id])
print('Optimal F1 score is %f.' %f1_scores[opt_id])
##################### Train model with only 1 addtional feature ###############################
# only description
#grid = np.array([(T, D) for T in np.arange(0,1,0.1) for D in np.arange(0,1,0.1)])
# only hashtag
#grid = np.array([(T, H) for T in np.arange(0,1,0.1) for H in np.arange(0,1,0.1)])
# only location
#grid = np.array([(T,G) for T in np.arange(0,1,0.1) for G in np.arange(0,1,0.1)])
#
#grid_new = []
#for i in range(len(grid)):
# if sum(grid[i]) == 1:
# grid_new.append(grid[i])
#
#precisions = []
#recalls = []
#f1_scores = []
#y = np.float64(y)
#
#for i in range(len(grid_new)):
# combine_pred = grid_new[i][0]*text_pred + grid_new[i][1]*description_pred
# combine_pred = grid_new[i][0]*text_pred + grid_new[i][1]*hashtag_pred
# combine_pred = grid_new[i][0]*text_pred + grid_new[i][1]*geo_pred
# prediction = np.apply_along_axis(np.argmax, 1, combine_pred)
#
# avg_p = precision_score(y, prediction, average='macro')
# avg_r = recall_score(y, prediction, average='macro')
# avg_f1 = f1_score(y, prediction, average='macro')
#
# precisions.append(avg_p)
# recalls.append(avg_r)
# f1_scores.append(avg_f1)
#
#opt_id = np.argmax(f1_scores)
#print(grid_new[opt_id])
#print('Optimal Precision is %f.' %precisions[opt_id])
#print('Optimal Recall is %f.' %recalls[opt_id])
#print('Optimal F1 score is %f.' %f1_scores[opt_id])