forked from bipulshahi/codes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Spam.py
206 lines (152 loc) · 5.12 KB
/
Spam.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
# coding: utf-8
# In[3]:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory
from subprocess import check_output
print(check_output(["ls", "D:/"]).decode("utf8"))
# Any results you write to the current directory are saved as output.
# In[4]:
DATA_FILE = '../input/spam.csv'
df = pd.read_csv(DATA_FILE,encoding='latin-1')
print(df.head())
tags = df.v1
texts = df.v2
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import Conv1D, GlobalMaxPooling1D
from keras.preprocessing.text import Tokenizer
from keras.preprocessing import sequence
from sklearn.preprocessing import LabelEncoder
import time
from keras import metrics
print('import done')
# In[5]:
num_max = 1000
# preprocess
le = LabelEncoder()
tags = le.fit_transform(tags)
tok = Tokenizer(num_words=num_max)
tok.fit_on_texts(texts)
mat_texts = tok.texts_to_matrix(texts,mode='count')
print(tags[:5])
print(mat_texts[:5])
print(tags.shape,mat_texts.shape)
# In[6]:
# try a simple model first
def get_simple_model():
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(num_max,)))
model.add(Dropout(0.2))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))
model.summary()
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['acc',metrics.binary_accuracy])
print('compile done')
return model
def check_model(model,x,y):
model.fit(x,y,batch_size=32,epochs=10,verbose=1,validation_split=0.2)
m = get_simple_model()
check_model(m,mat_texts,tags)
# In[7]:
# for cnn preproces
max_len = 100
cnn_texts_seq = tok.texts_to_sequences(texts)
print(cnn_texts_seq[0])
cnn_texts_mat = sequence.pad_sequences(cnn_texts_seq,maxlen=max_len)
print(cnn_texts_mat[0])
print(cnn_texts_mat.shape)
# In[8]:
def get_cnn_model_v1():
model = Sequential()
# we start off with an efficient embedding layer which maps
# our vocab indices into embedding_dims dimensions
# 1000 is num_max
model.add(Embedding(1000,
20,
input_length=max_len))
model.add(Dropout(0.2))
model.add(Conv1D(64,
3,
padding='valid',
activation='relu',
strides=1))
model.add(GlobalMaxPooling1D())
model.add(Dense(256))
model.add(Dropout(0.2))
model.add(Activation('relu'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.summary()
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['acc',metrics.binary_accuracy])
return model
m = get_cnn_model_v1()
check_model(m,cnn_texts_mat,tags)
# In[9]:
def get_cnn_model_v2(): # added embed
model = Sequential()
# we start off with an efficient embedding layer which maps
# our vocab indices into embedding_dims dimensions
# 1000 is num_max
model.add(Embedding(1000,
50, #!!!!!!!!!!!!!!!!!!!!!!!
input_length=max_len))
model.add(Dropout(0.2))
model.add(Conv1D(64,
3,
padding='valid',
activation='relu',
strides=1))
model.add(GlobalMaxPooling1D())
model.add(Dense(256))
model.add(Dropout(0.2))
model.add(Activation('relu'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.summary()
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['acc',metrics.binary_accuracy])
return model
m = get_cnn_model_v2()
check_model(m,cnn_texts_mat,tags)
# In[10]:
def get_cnn_model_v3(): # added filter
model = Sequential()
# we start off with an efficient embedding layer which maps
# our vocab indices into embedding_dims dimensions
# 1000 is num_max
model.add(Embedding(1000,
20,
input_length=max_len))
model.add(Dropout(0.2))
model.add(Conv1D(256, #!!!!!!!!!!!!!!!!!!!
3,
padding='valid',
activation='relu',
strides=1))
model.add(GlobalMaxPooling1D())
model.add(Dense(256))
model.add(Dropout(0.2))
model.add(Activation('relu'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.summary()
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['acc',metrics.binary_accuracy])
return model
m = get_cnn_model_v3()
check_model(m,cnn_texts_mat,tags)
# In[ ]:
# In[ ]: