-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtext_cnn.py
210 lines (161 loc) · 6.69 KB
/
text_cnn.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
# -*- coding: utf-8 -*-
"""text_cnn.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1NI8Z9OYhwxjYa30PyOt-elSEcagXchDW
"""
import os
path = '/content/drive/MyDrive/VLSP_ReINTEL'
#you should change this path to your project folder path
os.chdir(path)
!pip install pyvi
import numpy as np
from tqdm import tqdm
np.random.seed(42)
import pandas as pd
from pyvi import ViTokenizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
from keras.models import Model
from keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D
from keras.layers import BatchNormalization, MaxPooling1D, Conv1D#, Merge
from keras.layers import Reshape, Flatten, Concatenate, Dropout, SpatialDropout1D, LSTM, Bidirectional
from keras.preprocessing import text, sequence
from keras.callbacks import Callback
import warnings
warnings.filterwarnings('ignore')
from sklearn.model_selection import train_test_split
from keras.layers import Dense, Input, LSTM, Bidirectional, Conv1D
from keras.layers import Dropout, Embedding
from keras.preprocessing import text, sequence
from keras.layers import GlobalMaxPooling1D, GlobalAveragePooling1D, concatenate, SpatialDropout1D
from keras.models import Model
from keras import backend as K
from keras.models import model_from_json
from keras.models import load_model
#download fasttext
#! wget https://dl.fbaipublicfiles.com/fasttext/vectors-crawl/cc.vi.300.vec.gz
#extract fasttext
'''
import gzip
import shutil
with gzip.open('cc.vi.300.vec.gz', 'rb') as f_in:
with open('cc.vi.300.vec', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
'''
#download phow2v
#! wget https://public.vinai.io/word2vec_vi_words_300dims.zip
'''
from zipfile import ZipFile
zip = ZipFile('/content/word2vec_vi_words_300dims.zip')
zip.extractall()
'''
#download phow2v syllables
#! wget https://public.vinai.io/word2vec_vi_syllables_300dims.zip
'''
zip = ZipFile('word2vec_vi_syllables_300dims.zip')
zip.extractall()
'''
train=pd.read_csv('/content/drive/MyDrive/BERT/SA/VSLP_data/public_train.csv')
train['post_message']=train['post_message'].fillna('none')
public_test = pd.read_csv('/content/drive/MyDrive/BERT/SA/VSLP_data/public_test.csv')
private_test = pd.read_csv('/content/drive/MyDrive/BERT/SA/VSLP_data/final_private_test_dropped_no_label - final_private_test_dropped_no_label.csv')
X_train = train["post_message"].fillna("none").values
y_train = train[['label']].values
X_test = private_test["post_message"].fillna("none").values
def preprocess(text):
text = text.split(" ")
return text
max_features = 30000
maxlen = 500
embed_size = 300
batch_size = 32
epochs = 5
l2_reg = .00001
filter_sizes = [3,4,5]
num_filters = 32
EMBEDDING_FILE = 'cc.vi.300.vec'
#EMBEDDING_FILE = 'word2vec_vi_words_300dims.txt'
#you can change path here to load another word embedding pretrained model
def recall_m(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall
def precision_m(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
return precision
def f1_m(y_true, y_pred):
precision = precision_m(y_true, y_pred)
recall = recall_m(y_true, y_pred)
return 2*((precision*recall)/(precision+recall+K.epsilon()))
tokenizer = text.Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(list(X_train) + list(X_test))
X_train = tokenizer.texts_to_sequences(X_train)
X_test = tokenizer.texts_to_sequences(X_test)
x_train = sequence.pad_sequences(X_train, maxlen=maxlen)
x_test = sequence.pad_sequences(X_test, maxlen=maxlen)
embeddings_index = {}
with open(EMBEDDING_FILE, encoding='utf8') as f:
for line in f:
values = line.rstrip().rsplit(' ')
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
word_index = tokenizer.word_index
num_words = len(word_index) + 1
embedding_matrix = np.zeros((num_words, embed_size))
max_features = num_words
for word, i in word_index.items():
if i >= max_features:
continue
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
embedding_matrix[i] = embedding_vector
from keras.callbacks import ModelCheckpoint, TensorBoard, EarlyStopping
import tensorflow as tf
X_tra, X_val, y_tra, y_val = train_test_split(x_train, y_train, train_size=0.8, random_state=233)
checkpoint = ModelCheckpoint('w2v_balanced_v1.hdf5',
monitor='val_acc',
save_best_only=True,
mode='max',
verbose=1)
def get_model():
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix])(inp)
x = SpatialDropout1D(0.3)(x)
x = Reshape((maxlen, embed_size, 1))(x)
conv_0 = Conv2D(num_filters, kernel_size=(filter_sizes[0], embed_size), kernel_initializer='normal',
activation='elu')(x)
conv_1 = Conv2D(num_filters, kernel_size=(filter_sizes[1], embed_size), kernel_initializer='normal',
activation='elu')(x)
conv_2 = Conv2D(num_filters, kernel_size=(filter_sizes[2], embed_size), kernel_initializer='normal',
activation='elu')(x)
maxpool_0 = MaxPool2D(pool_size=(maxlen - filter_sizes[0] + 1, 1))(conv_0)
maxpool_1 = MaxPool2D(pool_size=(maxlen - filter_sizes[1] + 1, 1))(conv_1)
maxpool_2 = MaxPool2D(pool_size=(maxlen - filter_sizes[2] + 1, 1))(conv_2)
z = Concatenate(axis=1)([maxpool_0, maxpool_1, maxpool_2])
z = Flatten()(z)
z = Dropout(0.35)(z)
outp = Dense(1, activation="sigmoid")(z)
model = Model(inputs=inp, outputs=outp)
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['acc',f1_m,precision_m, recall_m])
return model
model = get_model()
model.summary()
history = model.fit(X_tra, y_tra, validation_data=(X_val, y_val), batch_size=batch_size, epochs=epochs, verbose=1)
from keras.models import load_model
y_pred = model.predict(x_test, batch_size=32)
model_json = model.to_json()
with open("cnn_.json", "w") as json_file:
json_file.write(model_json)
model.save('cnn_.h5')
#new_model = load_model('/content/drive/MyDrive/VSLP_ReINTEL/text cnn/CNN.h5')
y_pred = model.predict(x_test, batch_size=32)
results = pd.DataFrame({'id':private_test['id']})
results['probability']=y_pred
results.to_csv('results.csv',index=False,header=False)