forked from shockline/KnowlegeableCNN
-
Notifications
You must be signed in to change notification settings - Fork 1
/
structureTestOnMonster2.py
249 lines (212 loc) · 7.52 KB
/
structureTestOnMonster2.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
241
242
243
244
245
246
247
248
249
from theano import tensor as T, printing
import theano
import numpy
from mlp import HiddenLayer
from logistic_sgd import LogisticRegression
from DocEmbeddingNN import DocEmbeddingNN
# from DocEmbeddingNNPadding import DocEmbeddingNN
from knoweagebleClassifyFlattened import CorpusReader
import cPickle
import os
import sys
from sklearn.metrics import roc_curve, auc
def work(mode, data_name, test_dataname):
print "mode: ", mode
print "data_name: ", data_name
print "Started!"
rng = numpy.random.RandomState(23455)
docSentenceCount = T.ivector("docSentenceCount")
sentenceWordCount = T.ivector("sentenceWordCount")
corpus = T.matrix("corpus")
docLabel = T.ivector('docLabel')
# for list-type data
layer0 = DocEmbeddingNN(corpus, docSentenceCount, sentenceWordCount, rng, wordEmbeddingDim=200, \
sentenceLayerNodesNum=100, \
sentenceLayerNodesSize=[5, 200], \
docLayerNodesNum=100, \
docLayerNodesSize=[3, 100])
layer1 = HiddenLayer(
rng,
input=layer0.output,
n_in=layer0.outputDimension,
n_out=100,
activation=T.tanh
)
layer2 = LogisticRegression(input=layer1.output, n_in=100, n_out=2)
# construct the parameter array.
params = layer2.params + layer1.params + layer0.params
# Load the parameters last time, optionally.
# data_name = "car"
para_path = "data/" + data_name + "/model/scnn.model"
traintext = "data/" + data_name + "/train/text"
trainlabel = "data/" + data_name + "/train/label"
testtext = "data/" + test_dataname + "/test/text"
testlabel = "data/" + test_dataname + "/test/label"
loadParamsVal(para_path, params)
if(mode == "train"):
print "Loading train data."
cr_train = CorpusReader(minDocSentenceNum=5, minSentenceWordNum=5, dataset=traintext, labelset=trainlabel)
docMatrixes, docSentenceNums, sentenceWordNums, ids, labels = cr_train.getCorpus([0, 100000])
# print "Right answer: "
# print zip(ids, labels)
docMatrixes = transToTensor(docMatrixes, theano.config.floatX)
docSentenceNums = transToTensor(docSentenceNums, numpy.int32)
sentenceWordNums = transToTensor(sentenceWordNums, numpy.int32)
labels = transToTensor(labels, numpy.int32)
# valid_cr = CorpusReader(minDocSentenceNum=5, minSentenceWordNum=5, dataset="data/valid/split", labelset="data/valid/label.txt")
print
print "Loading test data."
cr_test = CorpusReader(minDocSentenceNum=5, minSentenceWordNum=5, dataset=testtext, labelset=testlabel)
validDocMatrixes, validDocSentenceNums, validSentenceWordNums, validIds, validLabels = cr_test.getCorpus([0, 1000])
# print "Right answer: "
# print zip(validIds, validLabels)
validDocMatrixes = transToTensor(validDocMatrixes, theano.config.floatX)
validDocSentenceNums = transToTensor(validDocSentenceNums, numpy.int32)
validSentenceWordNums = transToTensor(validSentenceWordNums, numpy.int32)
validLabels = transToTensor(validLabels, numpy.int32)
print "Data loaded."
learning_rate = 0.1
index = T.lscalar("index")
batchSize = 10
n_batches = (len(docSentenceNums.get_value()) - 1) / batchSize + 1
print
print "Train set size is ", len(docMatrixes.get_value())
print "Validating set size is ", len(validDocMatrixes.get_value())
print "Batch size is ", batchSize
print "Number of training batches is ", n_batches
error = layer2.errors(docLabel)
cost = layer2.negative_log_likelihood(docLabel)
grads = T.grad(cost, params)
updates = [
(param_i, param_i - learning_rate * grad_i)
for param_i, grad_i in zip(params, grads)
]
print "Compiling computing graph."
valid_model = theano.function(
[],
[cost, error, layer2.y_pred, docLabel, T.transpose(layer2.p_y_given_x)[1]],
givens={
corpus: validDocMatrixes,
docSentenceCount: validDocSentenceNums,
sentenceWordCount: validSentenceWordNums,
docLabel: validLabels
}
)
# for list-type data
train_model = theano.function(
[index],
[cost, error, layer2.y_pred, docLabel],
updates=updates,
givens={
corpus: docMatrixes,
docSentenceCount: docSentenceNums[index * batchSize: (index + 1) * batchSize + 1],
sentenceWordCount: sentenceWordNums,
docLabel: labels[index * batchSize: (index + 1) * batchSize]
}
)
print "Compiled."
print "Start to train."
epoch = 0
n_epochs = 2000
ite = 0
# ####Validate the model####
costNum, errorNum, pred_label, real_label, pred_prob = valid_model()
print "Valid current model:"
print "Cost: ", costNum
print "Error: ", errorNum
print "Valid Pred: ", pred_label
print "pred_prob: ", pred_prob
fpr, tpr, _ = roc_curve(real_label, pred_prob)
roc_auc = auc(fpr, tpr)
print "data_name: ", data_name
print "test_dataname: ", test_dataname
print "ROC: ", roc_auc
while (epoch < n_epochs):
epoch = epoch + 1
#######################
for i in range(n_batches):
# for list-type data
costNum, errorNum, pred_label, real_label = train_model(i)
ite = ite + 1
# for padding data
# costNum, errorNum = train_model(docMatrixes, labels)
# del docMatrixes, docSentenceNums, sentenceWordNums, labels
# print ".",
if(ite % 10 == 0):
print
print "@iter: ", ite
print "Cost: ", costNum
print "Error: ", errorNum
# Validate the model
costNum, errorNum, pred_label, real_label, pred_prob = valid_model()
print "Valid current model:"
print "Cost: ", costNum
print "Error: ", errorNum
print "pred_prob: ", pred_prob
# print "Valid Pred: ", pred_label
fpr, tpr, _ = roc_curve(real_label, pred_prob)
roc_auc = auc(fpr, tpr)
print "data_name: ", data_name
print "test_dataname: ", test_dataname
print "ROC: ", roc_auc
# Save model
print "Saving parameters."
saveParamsVal(para_path, params)
print "Saved."
elif(mode == "deploy"):
print "Compiling computing graph."
output_model = theano.function(
[corpus, docSentenceCount, sentenceWordCount],
[layer2.y_pred]
)
print "Compiled."
cr = CorpusReader(minDocSentenceNum=5, minSentenceWordNum=5, dataset="data/train_valid/split")
count = 21000
while(count <= 21000):
docMatrixes, docSentenceNums, sentenceWordNums, ids = cr.getCorpus([count, count + 100])
docMatrixes = numpy.matrix(
docMatrixes,
dtype=theano.config.floatX
)
docSentenceNums = numpy.array(
docSentenceNums,
dtype=numpy.int32
)
sentenceWordNums = numpy.array(
sentenceWordNums,
dtype=numpy.int32
)
print "start to predict."
pred_y = output_model(docMatrixes, docSentenceNums, sentenceWordNums)
print "End predicting."
print "Writing resfile."
# print zip(ids, pred_y[0])
f = file("data/test/res/res" + str(count), "w")
f.write(str(zip(ids, pred_y[0])))
f.close()
print "Written." + str(count)
count += 100
print "All finished!"
def saveParamsVal(path, params):
with open(path, 'wb') as f: # open file with write-mode
for para in params:
cPickle.dump(para.get_value(), f, protocol=cPickle.HIGHEST_PROTOCOL) # serialize and save object
def loadParamsVal(path, params):
if(not os.path.exists(path)):
return None
try:
with open(path, 'rb') as f: # open file with write-mode
for para in params:
para.set_value(cPickle.load(f), borrow=True)
except:
pass
def transToTensor(data, t):
return theano.shared(
numpy.array(
data,
dtype=t
),
borrow=True
)
if __name__ == '__main__':
work(mode=sys.argv[1], data_name=sys.argv[2], test_dataname=sys.argv[3])