-
Notifications
You must be signed in to change notification settings - Fork 0
/
keras_final_project.py
159 lines (116 loc) · 5.25 KB
/
keras_final_project.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
# -*- coding: utf-8 -*-
"""Keras-Final-Project.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1-ZxA-xEilzc3kRseYVZfTh7IE-UUyZLc
"""
import sys
import os
import re
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import GRU
from keras.preprocessing.text import Tokenizer
from keras.layers.convolutional import Convolution1D
from keras import backend as K
!pip install hazm
lineList = list()
with open('stop_words.txt') as f:
for line in f:
lineList.append(line)
lineList = [x.strip() for x in lineList]
from google.colab import drive
drive.mount('/content/drive')
df = pd.read_csv('/content/drive/MyDrive/train.csv')
from __future__ import unicode_literals
from hazm import *
import re, string
def remove_stopwords(text):
text = [word for word in text.split() if word not in lineList]
return " ".join(text)
normalizer = Normalizer()
special = re.compile(r'\W')
single = re.compile(r'\s+', flags=re.I)
number = re.compile(r"[-+]?[0-9]+")
pnumber = re.compile(r"[-+][\u06F0-\u06F90-9]+")
url = re.compile(r"https?://\S+|www\.\S+")
html = re.compile(r"<.*?>")
emoji_pattern = re.compile(
"["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
u"\U00002702-\U000027B0"
u"\U000024C2-\U0001F251"
"]+",
flags=re.UNICODE,
)
df["Text"] = df.Text.map(remove_stopwords)
df["Text"] = df.Text.map(lambda x: url.sub(r" ",x))
df["Text"] = df.Text.map(lambda x: html.sub(r" ",x))
df["Text"] = df.Text.map(lambda x: emoji_pattern.sub(r" ",x))
df["Text"] = df.Text.map(lambda x: number.sub(r" ",x))
df["Text"] = df.Text.map(lambda x: pnumber.sub(r" ",x))
df["Text"] = df.Text.map(lambda x: x.translate(str.maketrans(" ", " ", string.punctuation)))
df["Text"] = df.Text.map(lambda x: special.sub(r" ",x))
df["Text"] = df.Text.map(lambda x: single.sub(r" ", x))
df["Text"] = df.Text.map(lambda x: normalizer.normalize(x))
df.Category = df.Category.astype('category')
nb_classes = df.Category.cat.codes.max() + 1
df["CategoryCodes"] = df.Category.cat.codes
X_train, X_test, y_train, y_test = train_test_split(df.Text, df.CategoryCodes, test_size=0.1, random_state=42)
max_features = 20000
maxlen = 1000
tokenizer = Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(X_train)
sequences_train = tokenizer.texts_to_sequences(X_train)
sequences_test = tokenizer.texts_to_sequences(X_test)
# max_features = len(tokenizer.word_index) + 1
# maxlen = max([len(s.split()) for s in df.Text])
X_train = sequence.pad_sequences(sequences_train, maxlen=maxlen, padding='post')
X_test = sequence.pad_sequences(sequences_test, maxlen=maxlen, padding='post')
# Y_train = np_utils.to_categorical(y_train, nb_classes)
# Y_test = np_utils.to_categorical(y_test, nb_classes)
print('X_train shape:', X_train.shape)
print('X_test shape:', X_test.shape)
batch_size = 32
from keras.callbacks import ModelCheckpoint
model = Sequential()
model.add(Embedding(max_features, 256, input_length=maxlen))
model.add(GRU(512, return_sequences=False))
# model.add(Dropout(0.5))
model.add(Dense(nb_classes, activation='sigmoid'))
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
filepath="weights-improvement-{epoch:02d}-{val_accuracy:.2f}.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]
model.fit(X_train, y_train, batch_size=batch_size, epochs=5,
validation_data=(X_test, y_test), callbacks=callbacks_list)
df_test = pd.read_csv('/content/drive/MyDrive/test.csv.zip')
df_test["Text"] = df_test.Text.map(remove_stopwords)
df_test["Text"] = df_test.Text.map(lambda x: url.sub(r" ",x))
df_test["Text"] = df_test.Text.map(lambda x: html.sub(r" ",x))
df_test["Text"] = df_test.Text.map(lambda x: emoji_pattern.sub(r" ",x))
df_test["Text"] = df_test.Text.map(lambda x: number.sub(r" ",x))
df_test["Text"] = df_test.Text.map(lambda x: pnumber.sub(r" ",x))
df_test["Text"] = df_test.Text.map(lambda x: x.translate(str.maketrans(" ", " ", string.punctuation)))
df_test["Text"] = df_test.Text.map(lambda x: special.sub(r" ",x))
df_test["Text"] = df_test.Text.map(lambda x: single.sub(r" ", x))
df_test["Text"] = df_test.Text.map(lambda x: normalizer.normalize(x))
sequences_final = tokenizer.texts_to_sequences(df_test.Text)
X_final = sequence.pad_sequences(sequences_final, maxlen=maxlen, padding='post')
model.load_weights("/content/weights-improvement-02-0.84.hdf5")
Y_final = model.predict(X_final)
Y_classes = Y_final.argmax(axis=-1)
# df = pd.read_csv('/content/drive/MyDrive/train.csv')
# df.Category = df.Category.astype('category')
Y_classes_Name = df.Category.cat.categories[Y_classes]
df_test = df_test.rename(columns = {"Text":"Category"})
df_test.Category = Y_classes_Name
df_test.to_csv("Final.csv", index=False)