-
Notifications
You must be signed in to change notification settings - Fork 1
/
bert_vectors_chandni.py
241 lines (175 loc) · 8.41 KB
/
bert_vectors_chandni.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
# coding: utf-8
# # Text categorization model using the features derived from BERT
# In[ ]:
import os
import json
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import confusion_matrix, classification_report
# In[2]:
ORIGINAL_DATA_DIR = os.path.join("data")
BERT_FEATURE_DIR = "bert_output_data"
# In[3]:
train_df = pd.read_csv(os.path.join(ORIGINAL_DATA_DIR, "lang_id_train.csv"))
print(train_df.shape)
bert_vectors_train = []
with open(os.path.join(BERT_FEATURE_DIR, "train.jsonlines"), "rt") as infile:
for line in infile:
bert_data = json.loads(line)
for t in bert_data["features"]:
# Only extract the [CLS] vector used for classification
if t["token"] == "[CLS]":
# We only use the representation at the final layer of the network
bert_vectors_train.append(t["layers"][0]["values"])
break
print(len(bert_vectors_train))
X_train = np.array(bert_vectors_train)
y_train = train_df["native_language"].values
# In[4]:
eval_df = pd.read_csv(os.path.join(ORIGINAL_DATA_DIR, "lang_id_eval.csv"))
print(eval_df.shape)
bert_vectors_eval = []
with open(os.path.join(BERT_FEATURE_DIR, "eval.jsonlines"), "rt") as infile:
for line in infile:
bert_data = json.loads(line)
for t in bert_data["features"]:
# Only extract the [CLS] vector used for classification
if t["token"] == "[CLS]":
# We only use the representation at the final layer of the network
bert_vectors_eval.append(t["layers"][0]["values"])
break
print(len(bert_vectors_eval))
X_eval = np.array(bert_vectors_eval)
y_eval = eval_df["native_language"].values
# In[5]:
test_df = pd.read_csv(os.path.join(ORIGINAL_DATA_DIR, "lang_id_test.csv"))
print(test_df.shape)
bert_vectors_test = []
with open(os.path.join(BERT_FEATURE_DIR, "test.jsonlines"), "rt") as infile:
for line in infile:
bert_data = json.loads(line)
for t in bert_data["features"]:
# Only extract the [CLS] vector used for classification
if t["token"] == "[CLS]":
# We only use the representation at the final layer of the network
bert_vectors_test.append(t["layers"][0]["values"])
break
print(len(bert_vectors_test))
X_test = np.array(bert_vectors_test)
y_test = test_df["native_language"].values
# # Logistic Regression
# In[6]:
lr_model = LogisticRegression(penalty="l2", C=1.0)
lr_model.fit(X_train, y_train)
print("Training Accuarcy: ", lr_model.score(X_train, y_train))
# In[15]:
# Adding predicted value in the dataframe
test_df['predicted1'] = lr_model.predict(X_test)
# Class list
list_of_languages = sorted(test_df['native_language'].unique())
# Precision, recall, f-measure and support for each class
print("Evaluation for each class")
print(classification_report(y_test,test_df['predicted1'].values,target_names=list_of_languages))
print()
print("**********************************************************************************************")
print()
# Confusion matrix
matrix = confusion_matrix(test_df['native_language'], test_df['predicted1'])
plt.figure(figsize = (10,5))
ax = sns.heatmap(matrix, annot=True, xticklabels=list_of_languages, yticklabels=list_of_languages)
plt.show()
print("**********************************************************************************************")
print()
# Calculate misclassification
test_predicted = test_df.groupby('predicted1').count()['native_language']
test_misclassifications = []
for i in range(len(list_of_languages)):
misclassification = ((200 - matrix[i][i] + (test_predicted[i] - matrix[i][i])) / 2000) * 100
test_misclassifications.append(misclassification)
# Misclassification for each class into one dataframe
evaluation_by_class = pd.DataFrame(columns=['Language', 'Misclassification'])
for i in range(len(list_of_languages)):
evaluation_by_class = evaluation_by_class.append(pd.DataFrame([[list_of_languages[i], test_misclassifications[i]]],
columns=['Language', 'Misclassification']))
print("Misclassification for each class")
print(evaluation_by_class.to_string())
print()
print("**********************************************************************************************")
print()
# Evaluate misclassification between all classes
evaluation_between_classes = pd.DataFrame(columns=['Language', 'Predicted', 'Misclassification'])
for i in list_of_languages:
for j in list_of_languages:
if(i != j):
evaluation_between_classes = evaluation_between_classes.append(pd.DataFrame([[i, j,
matrix[list_of_languages.index(i)][list_of_languages.index(j)]]],
columns=['Language', 'Predicted', 'Misclassification']))
print("Misclassification between each pair of classes")
print(evaluation_between_classes.sort_values(by=['Misclassification']).to_string())
print()
print("**********************************************************************************************")
print()
print("Summary")
print("Total records:", test_df.shape[0])
print("Incorrect predictions:", evaluation_between_classes['Misclassification'].sum())
print("Correct predictions:", (test_df.shape[0] - evaluation_between_classes['Misclassification'].sum()))
# # Neural Network
# In[8]:
nn_model = MLPClassifier(solver='lbfgs')
nn_model.fit(X_train, y_train)
print("Training Accuarcy: ", nn_model.score(X_train, y_train))
# In[16]:
# Adding predicted value in the dataframe
test_df['predicted2'] = nn_model.predict(X_test)
# Class list
list_of_languages = sorted(test_df['native_language'].unique())
# Precision, recall, f-measure and support for each class
print("Evaluation for each class")
print(classification_report(y_test,test_df['predicted2'].values,target_names=list_of_languages))
print()
print("**********************************************************************************************")
print()
# Confusion matrix
matrix = confusion_matrix(test_df['native_language'], test_df['predicted2'])
plt.figure(figsize = (10,5))
ax = sns.heatmap(matrix, annot=True, xticklabels=list_of_languages, yticklabels=list_of_languages)
plt.show()
print("**********************************************************************************************")
print()
# Calculate misclassification
test_predicted = test_df.groupby('predicted2').count()['native_language']
test_misclassifications = []
for i in range(len(list_of_languages)):
misclassification = ((200 - matrix[i][i] + (test_predicted[i] - matrix[i][i])) / 2000) * 100
test_misclassifications.append(misclassification)
# Misclassification for each class into one dataframe
evaluation_by_class = pd.DataFrame(columns=['Language', 'Misclassification'])
for i in range(len(list_of_languages)):
evaluation_by_class = evaluation_by_class.append(pd.DataFrame([[list_of_languages[i], test_misclassifications[i]]],
columns=['Language', 'Misclassification']))
print("Misclassification for each class")
print(evaluation_by_class.to_string())
print()
print("**********************************************************************************************")
print()
# Evaluate misclassification between all classes
evaluation_between_classes = pd.DataFrame(columns=['Language', 'Predicted', 'Misclassification'])
for i in list_of_languages:
for j in list_of_languages:
if(i != j):
evaluation_between_classes = evaluation_between_classes.append(pd.DataFrame([[i, j,
matrix[list_of_languages.index(i)][list_of_languages.index(j)]]],
columns=['Language', 'Predicted', 'Misclassification']))
print("Misclassification between each pair of classes")
print(evaluation_between_classes.sort_values(by=['Misclassification']).to_string())
print()
print("**********************************************************************************************")
print()
print("Summary")
print("Total records:", test_df.shape[0])
print("Incorrect predictions:", evaluation_between_classes['Misclassification'].sum())
print("Correct predictions:", (test_df.shape[0] - evaluation_between_classes['Misclassification'].sum()))