-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbasic_model.py
202 lines (145 loc) · 7.38 KB
/
basic_model.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import time
import matplotlib
import numpy as np
from sklearn import preprocessing, svm
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from construct_sample_features import get_TPNF_dataset, get_train_test_split, get_dataset_feature_names
matplotlib.use('agg')
import matplotlib.pyplot as plt
def get_classifier_by_name(classifier_name):
if classifier_name == "GaussianNB":
return GaussianNB()
elif classifier_name == "LogisticRegression":
return LogisticRegression(solver='lbfgs')
elif classifier_name == "DecisionTreeClassifier":
return DecisionTreeClassifier()
elif classifier_name == "RandomForestClassifier":
return RandomForestClassifier(n_estimators=50)
elif classifier_name == "SVM -linear kernel":
return svm.SVC(kernel='linear')
def train_model(classifier_name, X_train, X_test, y_train, y_test):
accuracy_values = []
precision_values = []
recall_values = []
f1_score_values = []
for i in range(5):
classifier_clone = get_classifier_by_name(classifier_name)
classifier_clone.fit(X_train, y_train)
predicted_output = classifier_clone.predict(X_test)
accuracy, precision, recall, f1_score_val = get_metrics(y_test, predicted_output, one_hot_rep=False)
accuracy_values.append(accuracy)
precision_values.append(precision)
recall_values.append(recall)
f1_score_values.append(f1_score_val)
print_metrics(np.mean(accuracy_values), np.mean(precision_values), np.mean(recall_values), np.mean(f1_score_values))
def print_metrics(accuracy, precision, recall, f1_score_val):
print("Accuracy : {}".format(accuracy))
print("Precision : {}".format(precision))
print("Recall : {}".format(recall))
print("F1 : {}".format(f1_score_val))
def get_metrics(target, logits, one_hot_rep=True):
"""
Two numpy one hot arrays
:param target:
:param logits:
:return:
"""
if one_hot_rep:
label = np.argmax(target, axis=1)
predict = np.argmax(logits, axis=1)
else:
label = target
predict = logits
accuracy = accuracy_score(label, predict)
precision = precision_score(label, predict)
recall = recall_score(label, predict)
f1_score_val = f1_score(label, predict)
return accuracy, precision, recall, f1_score_val
def get_basic_model_results(X_train, X_test, y_train, y_test):
scaler = preprocessing.StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
classifiers = [GaussianNB(), LogisticRegression(), DecisionTreeClassifier(),
RandomForestClassifier(n_estimators=100),
svm.SVC()]
classifier_names = ["GaussianNB", "LogisticRegression", "DecisionTreeClassifier", "RandomForestClassifier",
"SVM -linear kernel"]
for idx in range(len(classifiers)):
print("======={}=======".format(classifier_names[idx]))
train_model(classifier_names[idx], X_train, X_test, y_train, y_test)
def get_classificaton_results_tpnf(data_dir, news_source, time_interval, use_cache=False):
include_micro = True
include_macro = True
include_structural = True
include_temporal = True
include_linguistic = True
sample_feature_array = get_TPNF_dataset(data_dir, news_source, include_micro, include_macro, include_structural,
include_temporal, include_linguistic, time_interval, use_cache=use_cache)
print("Sample feature array dimensions")
print(sample_feature_array.shape, flush=True)
num_samples = int(len(sample_feature_array) / 2)
target_labels = np.concatenate([np.ones(num_samples), np.zeros(num_samples)], axis=0)
X_train, X_test, y_train, y_test = get_train_test_split(sample_feature_array, target_labels)
get_basic_model_results(X_train, X_test, y_train, y_test)
def plot_feature_importances(coef, names):
imp = coef
imp, names = zip(*sorted(zip(imp, names)))
plt.barh(range(len(names)), imp, align='center')
plt.yticks(range(len(names)), names)
plt.savefig('feature_importance.png', bbox_inches='tight')
plt.show()
def dump_random_forest_feature_importance(data_dir, news_source):
include_micro = True
include_macro = True
include_structural = True
include_temporal = True
include_linguistic = True
sample_feature_array = get_TPNF_dataset(data_dir, news_source, include_micro, include_macro, include_structural,
include_temporal, include_linguistic, use_cache=True)
sample_feature_array = sample_feature_array[:, :-1]
feature_names, short_feature_names = get_dataset_feature_names(include_micro, include_macro, include_structural,
include_temporal, include_linguistic)
feature_names = feature_names[:-1]
short_feature_names = short_feature_names[:-1]
num_samples = int(len(sample_feature_array) / 2)
target_labels = np.concatenate([np.ones(num_samples), np.zeros(num_samples)], axis=0)
X_train, X_test, y_train, y_test = get_train_test_split(sample_feature_array, target_labels)
# Build a forest and compute the feature importances
forest = ExtraTreesClassifier(n_estimators=100, random_state=0)
forest.fit(X_train, y_train)
importances = forest.feature_importances_
std = np.std([tree.feature_importances_ for tree in forest.estimators_],
axis=0)
indices = np.argsort(importances)[::-1]
# Print the feature ranking
print("Feature ranking:")
for f in range(X_train.shape[1]):
print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))
matplotlib.rcParams['figure.figsize'] = 5, 2
# Plot the feature importances of the forest
plt.figure()
plt.bar(range(X_train.shape[1]), importances[indices],
color="b", yerr=std[indices], align="center")
plt.xticks(range(X_train.shape[1]), np.array(short_feature_names)[indices], rotation=75, fontsize=9.5)
plt.xlim([-1, X_train.shape[1]])
plt.savefig('{}_feature_importance.png'.format(news_source), bbox_inches='tight')
plt.show()
def get_classificaton_results_tpnf_by_time(news_source: str):
# Time Interval in hours for early-fake news detection
time_intervals = [3, 6, 12, 24, 36, 48, 60, 72, 84, 96]
for time_interval in time_intervals:
print("=============Time Interval : {} ==========".format(time_interval))
start_time = time.time()
get_classificaton_results_tpnf("data/features", news_source, time_interval)
print("\n\n================Exectuion time - {} ==================================\n".format(
time.time() - start_time))
if __name__ == "__main__":
get_classificaton_results_tpnf("data/features", "politifact", time_interval=None, use_cache=False)
get_classificaton_results_tpnf("data/features", "gossipcop", time_interval=None, use_cache=False)
# Filter the graphs by time interval (for early fake news detection) and get the classification results
# get_classificaton_results_tpnf_by_time("politifact")
# get_classificaton_results_tpnf_by_time("gossipcop")