/
fabeec_imbalance.py
341 lines (268 loc) · 12.1 KB
/
fabeec_imbalance.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import pandas as pd
import numpy as np
from sentence_transformers import SentenceTransformer
import gensim
from gensim.utils import tokenize
from gensim.models import FastText
from gensim.models.phrases import Phrases, Phraser
from gensim.parsing.preprocessing import remove_stopwords, strip_punctuation, strip_non_alphanum
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from keras.models import Sequential
from keras.layers import Dense, Activation, Embedding, Flatten, MaxPooling1D, GlobalMaxPool1D, Dropout, Conv1D
from keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint
from keras.losses import binary_crossentropy
from keras.optimizers import Adam
from keras.utils import to_categorical
from keras import models
# Config Variables
tfidf_based = True
from_scratch = True
FT_VECTOR_SIZE = 300
f = open('goemotions/data/emotions.txt')
lines = f.readlines()
emotions = {}
for idx, label in enumerate(lines):
emotions[idx] = label.strip()
emotions
dfTrain = pd.read_csv('goemotions/data/train.tsv', sep='\t', header=None, names=['text', 'label', 'rater'])
dfDev = pd.read_csv('goemotions/data/dev.tsv', sep='\t', header=None, names=['text', 'label', 'rater'])
dfTest = pd.read_csv('goemotions/data/test.tsv', sep='\t', header=None, names=['text', 'label', 'rater'])
data = pd.concat([dfTrain, dfTest, dfDev], ignore_index=True)
data.text = data.text.apply(lambda s: s.lower())
def fasttext_model_train(data, from_scratch):
# Preprocessing like stopword removal @TODO
ge_sentences = [list(tokenize(s)) for s in data['text'].to_list()]
if from_scratch:
model = FastText(bucket=1000000, window=3, min_count=1, size=300)
model.build_vocab(sentences=ge_sentences)
model.train(sentences=ge_sentences, total_examples=len(ge_sentences), epochs=10)
else:
print("salam")
model = FastText.load_fasttext_format('content/cc.en.300')
model.build_vocab(ge_sentences, update=True)
# model.train(sentences=ge_sentences, total_examples = len(sent), epochs=5)
return model
# now the model has been trained, there are two ways to get the sentence vectors,
# first, simple averaging over the word vectors, like numpy.mean(...)
# second, using the tfidf to applying a weighted average method,
# There is an option using the original fastext library in python where the sentence vecotr is available but can be formolated here simply by adding two more functions
# TF-IDF Using SK_learn # needs a list of lists for words and docs along with a fasttext 'model'
def tfidf_model_train(data):
tf_idf_vect = TfidfVectorizer(stop_words=None)
tf_idf_vect.fit(data)
final_tf_idf = tf_idf_vect.transform(data)
tfidf_feat = tf_idf_vect.get_feature_names()
return tfidf_feat, final_tf_idf
# @TODO new document should be concatenated to the DATA and then the tfidf matrix should be computed again we need another method
# to do so >>> https://stackoverflow.com/questions/40112373/how-to-classify-new-documents-with-tf-idf4444444466444
fastText_model = fasttext_model_train(data, from_scratch) # training fastext
dictionary, tfidf_model = tfidf_model_train(data["text"].to_list())
# Sum( tfidf[word] * wvector) / sum(tfidf(words))
# @TODO maybe later develop the BM25 alg.
def get_sentence_vector(row, sent_tokens, dictionary, tfidf_model, ft_model, tfidf_based=False):
if not tfidf_based:
word_vectors = []
for token in sent_tokens:
w_vector = ft_model.wv[token]
word_vectors.append(w_vector)
return np.mean(word_vectors, axis=0)
else:
vec_sum = np.zeros(FT_VECTOR_SIZE)
weight = 0;
for token in sent_tokens:
# print(token)
try:
index = dictionary.index(token)
except:
index = -1
if index != -1:
w_vector = ft_model.wv[token]
# print("Vecotr ",w_vector)
tfidf_score = tfidf_model[row, index]
# print(tfidf_score)
vec_sum += (tfidf_score * w_vector)
weight += tfidf_score
return vec_sum / weight
from tqdm import tqdm
# Fasttext word embedding
def fasttext_embedding(model, data, dictionary, tfidf_model, tfidf_based):
sentence_vectors = []
row = 0;
for sentence in tqdm(data, position=0, leave=True):
sent_tokens = tokenize(sentence.lower())
sentence_vectors.append(get_sentence_vector(row, sent_tokens, dictionary, tfidf_model, model, tfidf_based))
row += 1
# print(sentence_vectors)
return sentence_vectors
# fastext_raw = fasttext_embedding(fastText_model, data.text.to_list(), dictionary, tfidf_model,False)
fasttext_tfidf = fasttext_embedding(fastText_model, data.text.to_list(), dictionary, tfidf_model, True)
# data['fasttext_raw'] = fastext_raw
data['fasttext_tfidf'] = fasttext_tfidf
from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
x = mlb.fit_transform([tuple(int(x) for x in i.split(',')) for i in data.label.to_list()])
data['new_label'] = list(x)
len(data.new_label[0])
###Bert
modelBert = SentenceTransformer('monologg/bert-base-cased-goemotions-original')
def bert_embedding(sentences):
sentence_embeddings = modelBert.encode(sentences)
return sentence_embeddings
bert_features = bert_embedding(data.text.to_list())
fabeec = []
for i in range(len(bert_features)):
fabeec.append(bert_features[i].tolist() + fasttext_tfidf[i].tolist())
# imbalance
data['fabeec'] = fabeec
start = 0
end = dfTrain.shape[0]
dfTrain['fabeec'] = data.fabeec[start:end]
dfTrain['new_label'] = data.new_label[start:end]
start = dfTrain.shape[0]
end = start + dfTest.shape[0]
dfTest['fabeec'] = data.fabeec[start:end].values
dfTest['new_label'] = data.new_label[start:end].values
start = end
dfDev['fabeec'] = data.fabeec[start:].values
dfDev['new_label'] = data.new_label[start:].values
def get_nan_ids(df):
j = 0
to_drop = []
for i in df.fabeec.to_list():
if np.any(np.isnan(i)):
to_drop.append(j)
j += 1
return to_drop
# remove nan for Train set
to_drop = get_nan_ids(dfTrain)
dfTrain = dfTrain.drop(to_drop)
print("Number of removed items in trainin set that contains Nan : {}, the removed inexes {}".format(len(to_drop),
to_drop))
# remove nan for dev test
to_drop = get_nan_ids(dfDev)
dfDev = dfDev.drop(to_drop)
print("Number of removed items in Dev set that contains Nan : {}, the removed inexes {}".format(len(to_drop), to_drop))
# remove nan for test data
to_drop = get_nan_ids(dfTest)
dfTest = dfTest.drop(to_drop)
print(
"Number of removed items in Test set that contains Nan : {}, the removed inexes {}".format(len(to_drop), to_drop))
from sklearn import tree
from sklearn.multioutput import MultiOutputClassifier
from sklearn.svm import LinearSVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import precision_recall_fscore_support
from sklearn.model_selection import GridSearchCV
import xgboost as xgb
from sklearn.ensemble import RandomForestClassifier
def classifier_pipline(X_train, Y_train, X_test):
svm = LinearSVC(random_state=42)
xgmodel_default = xgb.XGBClassifier()
xgmodel_tuned = xgb.XGBClassifier(max_depth=20, sub_sample=0.7, colsample_bytree=0.7, eta=0.5)
classifiers = [
# KNeighborsClassifier(),
# MultiOutputClassifier(svm, n_jobs=-1),
MultiOutputClassifier(xgmodel_default, n_jobs=-1),
# MultiOutputClassifier(xgmodel_tuned, n_jobs=-1),
RandomForestClassifier(max_samples=8000, max_depth=50),
# tree.DecisionTreeClassifier(max_depth=200)
]
preds = []
for item in classifiers:
clf = item
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
preds.append(y_pred)
return preds
X_train = np.array(dfTrain.fabeec.to_list() + dfDev.fabeec.to_list())
X_test = np.array(dfTest.fabeec.to_list())
y_train = np.array(dfTrain.new_label.to_list() + dfDev.new_label.to_list())
y_test = np.array(dfTest.new_label.to_list())
np.savetxt('X_train.csv', X_train, delimiter=',')
np.savetxt('X_test.csv', X_test, delimiter=',')
np.savetxt('y_train.csv', y_train, delimiter=',')
np.savetxt('y_test.csv', y_test, delimiter=',')
y_pred = classifier_pipline(X_train, y_train, X_test)
def Calculate_metric(y_test, y_pred):
y_test[y_test > .3] = 1
y_test[y_test <= .3] = 0
results = {}
results["macro_precision"], results["macro_recall"], results["macro_f1"], _ = precision_recall_fscore_support(
y_test, y_pred, average='macro')
results["micro_precision"], results["micro_recall"], results["micro_f1"], _ = precision_recall_fscore_support(
y_test, y_pred, average='micro')
results["weighted_precision"], results["weighted_recall"], results[
"weighted_f1"], _ = precision_recall_fscore_support(y_test, y_pred, average='weighted')
# num_emotions = len(emotions)
# idx2emotion = {i: e for i, e in enumerate(emotions)}
# preds_mat = np.zeros((len(preds), num_emotions))
# true_mat = np.zeros((len(preds), num_emotions))
# for i in range(len(preds)):
# true_labels = [int(idx) for idx in true.loc[i, "labels"].split(",")]
# for j in range(num_emotions):
# preds_mat[i, j] = preds.loc[i, idx2emotion[j]]
# true_mat[i, j] = 1 if j in true_labels else 0
# threshold = 0.3 # FLAGS.threshold
# pred_ind = preds_mat.copy()
# pred_ind[pred_ind > threshold] = 1
# pred_ind[pred_ind <= threshold] = 0
# results = {}
# results["accuracy"] = accuracy_score(true_mat, pred_ind)
# results["macro_precision"], results["macro_recall"], results[
# "macro_f1"], _ = precision_recall_fscore_support(
# true_mat, pred_ind, average="macro")
# results["micro_precision"], results["micro_recall"], results[
# "micro_f1"], _ = precision_recall_fscore_support(
# true_mat, pred_ind, average="micro")
# results["weighted_precision"], results["weighted_recall"], results[
# "weighted_f1"], _ = precision_recall_fscore_support(
# true_mat, pred_ind, average="weighted")
# for i in range(num_emotions):
# emotion = idx2emotion[i]
# emotion_true = true_mat[:, i]
# emotion_pred = pred_ind[:, i]
# results[emotion + "_accuracy"] = accuracy_score(emotion_true, emotion_pred)
# results[emotion + "_precision"], results[emotion + "_recall"], results[
# emotion + "_f1"], _ = precision_recall_fscore_support(
# emotion_true, emotion_pred, average="binary")
return results
met_results = []
for met in y_pred:
temp = Calculate_metric(y_test, met)
met_results.append(temp)
print(temp)
# CNN
X_train_cnn = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
y_train_cnn = y_train.reshape(y_train.shape[0], y_train.shape[1])
X_test_cnn = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)
y_test_cnn = y_test.reshape(y_test.shape[0], y_test.shape[1], 1)
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(1068, 1)))
model.add(Dropout(0.5))
model.add(MaxPooling1D(pool_size=2))
model.add(Conv1D(filters=32, kernel_size=3, activation='relu'))
model.add(Dropout(0.5))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(100, activation='relu'))
model.add(Dense(28, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['categorical_accuracy'])
callbacks = [
ReduceLROnPlateau(),
EarlyStopping(patience=4),
ModelCheckpoint(filepath='model-conv1d.h5', save_best_only=True)
]
history = model.fit(X_train_cnn, y_train_cnn,
epochs=20,
batch_size=32,
validation_split=0.1,
callbacks=callbacks)
y_pred = model.predict(X_test_cnn)
y_pred[y_pred > .3] = 1
y_pred[y_pred <= .3] = 0
print(y_pred)
print(y_test)
results = Calculate_metric(y_test, y_pred)
print(results)