-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtext_cnn_lstm.py
141 lines (106 loc) · 3.65 KB
/
text_cnn_lstm.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
from __future__ import print_function
import os
import sys
import numpy as np
from pprint import pprint
from keras.preprocessing import sequence
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Input, Flatten
from keras.layers import Conv1D, MaxPooling1D, Embedding
from keras.models import Model
from keras.utils.np_utils import to_categorical
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from cnn_lstm import CNNLSTM
from sklearn.externals import joblib
selected_categories = [
'comp.graphics',
'comp.windows.x',
'rec.motorcycles',
'rec.sport.baseball',
'sci.crypt',
'sci.med',
'talk.politics.guns',
'talk.religion.misc']
newsgroups_train = fetch_20newsgroups(subset='train',
categories=selected_categories,
remove=('headers', 'footers', 'quotes'))
newsgroups_test = fetch_20newsgroups(subset='test',
categories=selected_categories,
remove=('headers', 'footers', 'quotes'))
texts = newsgroups_train['data']
labels = newsgroups_train['target']
print(len(texts))
print(np.unique(labels))
print(labels)
texts = [t for t in texts]
print(type(texts[0]))
MAX_SEQUENCE_LENGTH = 1000
MAX_NB_WORDS = 10000
EMBEDDING_DIM = 100
VALIDATION_SPLIT = 0.2
ax_features = 10000
maxlen = 1000
embedding_size = 128
# Convolution
kernel_size = 5
filters = 64
pool_size = 4
# LSTM
lstm_output_size = 70
# Training
batch_size = 30
epochs = 2
# finally, vectorize the text samples into a 2D integer tensor
tokenizer = Tokenizer(nb_words=MAX_NB_WORDS)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)
# labels = to_categorical(np.asarray(labels))
print('Shape of data tensor:', data.shape)
print('Shape of label tensor:', labels.shape)
# split the data into a training set and a validation set
indices = np.arange(data.shape[0])
np.random.shuffle(indices)
data = data[indices]
labels = labels[indices]
num_validation_samples = int(VALIDATION_SPLIT * data.shape[0])
x_train = data[:-num_validation_samples]
y_train = labels[:-num_validation_samples]
x_val = data[-num_validation_samples:]
y_val = labels[-num_validation_samples:]
#
print('Initialize model.')
model = CNNLSTM().initialize()
print('x_train shape:', x_train.shape)
print('x_test shape:', x_val.shape)
print('Train...')
model.fit(x_train, y_train, batch_size=batch_size, nb_epoch=epochs,
validation_data=(x_val, y_val), verbose=1)
score, acc = model.evaluate(x_val, y_val, batch_size=batch_size)
print('Test score:', score)
print('Test accuracy:', acc)
# Modified for documentation by Jaques Grobler
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model, datasets
logreg = linear_model.LogisticRegression(C=1e5, verbose=1)
# we create an instance of Neighbours Classifier and fit the data.
print('Training')
logreg.fit(x_train, y_train)
joblib.dump(logreg, 'logreg.pkl')
clf = joblib.load('logreg.pkl')
pred = clf.predict(x_train)
print(((pred == y_train).sum() * 100.0) / (np.shape(y_train)[0] * 1.0))
# from sklearn import datasets
# from sklearn.naive_bayes import GaussianNB
# gnb = GaussianNB()
# gnb.fit(x_train, y_train)
# joblib.dump(gnb, 'gnb.pkl')
# clf = joblib.load('gnb.pkl')
# pred = clf.predict(x_train)
# print(((pred == y_train).sum() * 100.0) / (np.shape(y_train)[0] * 1.0))