-
Notifications
You must be signed in to change notification settings - Fork 0
/
fake_classfier.py
201 lines (167 loc) · 6.94 KB
/
fake_classfier.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
# -*- coding: utf-8 -*-
# Author: Kay Zhou
# Date: 2019-02-24 16:42:55
import gc
from itertools import chain
from nltk import ngrams
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_selection import SelectFromModel
from sklearn.model_selection import train_test_split
import SQLite_handler
from joblib import dump, load
from my_weapon import *
from myclf import *
from Trump_Clinton_Classifer.TwProcess import CustomTweetTokenizer
from Trump_Clinton_Classifer.TwSentiment import (bag_of_words,
bag_of_words_and_bigrams)
class Fake_Classifer(object):
def __init__(self):
self.MAP_LABELS = {
"0": "fake",
"1": "extreme bias (right)",
"2": "right",
"3": "right leaning",
"4": "center",
"5": "left leaning",
"6": "left",
"7": "extreme bias (left)"
}
def get_train_data(self):
"""
获取训练文本
"""
print("loading all tweets_csv ...")
all_tweets = pd.read_csv("disk/all-tweets.csv", dtype=str, usecols=["tweet_id", "media_type"])
print("finished!")
map_labels = {
"0": "fake",
"1": "extreme bias (right)",
"2": "right",
"3": "right leaning",
"4": "center",
"5": "left leaning",
"6": "left",
"7": "extreme bias (left)"
}
for _type, f_label in map_labels.items():
print(_type, "...")
tweets_id = all_tweets[all_tweets["media_type"] == _type].tweet_id
rst = SQLite_handler.find_tweets(tweets_id)
print(len(rst))
with open("disk/train_data_fake/{}.txt".format(_type), "w") as f:
for d in rst:
if "text" not in d:
continue
# elif d["text"].startswith("RT"):
# continue
f.write(d["text"] + "\n")
def get_tokens(self):
"""
text > tokens
"""
tokenizer = CustomTweetTokenizer()
for _type, f_label in self.MAP_LABELS.items():
with open("disk/tokens_fake/{}.txt".format(_type), "w") as f:
for line in open("disk/train_data_fake/{}.txt".format(_type)):
words = tokenizer.tokenize(line.strip())
if len(words) > 0 and words[0] != "RT":
f.write(" ".join(words) + "\n")
def train(self):
"""
fake, non-fake
fake, left, center, right √ 优先
left, center, right
"""
# read data
X = []
y = []
for _type, f_label in tqdm(self.MAP_LABELS.items()):
if f_label == "fake":
y_i = 0
elif f_label in ["extreme bias (right)", "right", "right leaning"]:
y_i = 1
elif f_label == "center":
y_i = 2
elif f_label in ["extreme bias (left)", "left", "left leaning"]:
y_i = 3
for i, line in enumerate(open("disk/tokens_fake/{}.txt".format(_type))):
w = line.strip().split(" ")
# if len(w) > 0 and w[0] != "RT":
X.append(bag_of_words_and_bigrams(w))
# print(X[-1])
y.append(y_i)
print("Reading data finished! count:", len(y))
# split train and test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
del X, y
gc.collect()
print("Splitting data finished!")
# build one hot embedding
v = DictVectorizer(dtype=np.int8, sparse=True, sort=False)
X_train = v.fit_transform(X_train)
X_test = v.transform(X_test)
print("Building word embedding finished!")
print(X_train[0].shape, X_train[1].shape)
print(X_train.shape, X_test.shape)
# machine learning model
# list_classifiers = ['LR', 'GBDT', 'NB', 'RF']
list_classifiers = ['GBDT']
classifiers = {
'NB': naive_bayes_classifier,
'KNN': knn_classifier,
'LR': logistic_regression_classifier,
'RF': random_forest_classifier,
'DT': decision_tree_classifier,
'SVM': svm_classifier,
'SVMCV': svm_cross_validation,
'GBDT': gradient_boosting_classifier,
'SVMLINER': svm_linear_classifier,
}
for classifier in list_classifiers:
print('******************* {} ********************'.format(classifier))
if classifier == "LR":
clf = LogisticRegression(penalty='l2', multi_class="multinomial", solver="sag", max_iter=10e8)
clf.fit(X_train, y_train)
elif classifier == "GBDT":
clf = GradientBoostingClassifier(learning_rate=0.1, max_depth=3)
clf.fit(X_train, y_train)
else:
clf = classifiers[classifier](X_train, y_train)
# print("fitting finished! Lets evaluate!")
self.evaluate(clf, X_train, y_train, X_test, y_test)
dump(clf, 'model/{}.joblib'.format(classifier))
# original_params = {'n_estimators': 1000, 'max_leaf_nodes': 4, 'max_depth': 3, 'random_state': 23,
# 'min_samples_split': 5}
# for GDBT
# for i, setting in enumerate([{'learning_rate': 1.0, 'subsample': 1.0},
# {'learning_rate': 0.1, 'subsample': 1.0},
# {'learning_rate': 1.0, 'subsample': 0.5},
# {'learning_rate': 0.1, 'subsample': 0.5},
# {'learning_rate': 0.1, 'max_features': 2}]):
# print('******************* {} ********************'.format(i))
# params = dict(original_params)
# params.update(setting)
# clf = GradientBoostingClassifier(**params)
# clf.fit(X_train, y_train)
# self.evaluate(clf, X_train, y_train, X_test, y_test)
# original_params = {}
# LinearSVC
# for i, setting in enumerate([{'C':0.125}, {'C': 0.25}, {'C':0.5}, {'C':1.0}, {'C':2.0}, {'C': 4.0}, {'C':8.0}]):
# print('******************* {} ********************'.format(i))
# print(setting)
# params = dict(original_params)
# params.update(setting)
# clf = LinearSVC(**params)
# clf.fit(X_train, y_train)
# self.evaluate(clf, X_train, y_train, X_test, y_test)
def evaluate(self, clf, X_train, y_train, X_test, y_test):
# CV
print('accuracy of CV=5:', cross_val_score(clf, X_train, y_train, cv=5).mean())
# 模型评估
y_pred = clf.predict(X_test)
print(classification_report(y_test, y_pred))
if __name__ == "__main__":
Lebron = Fake_Classifer()
# Lebron.get_train_data()
# Lebron.get_tokens()
Lebron.train()