-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconv_net_eval_alt.py
184 lines (171 loc) · 6.11 KB
/
conv_net_eval_alt.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
import cPickle
import numpy as np
from collections import defaultdict, OrderedDict
import theano
import theano.tensor as T
import re
import warnings
import sys
import pdb
from conv_net_classes import LeNetConvPoolLayer
from conv_net_classes import MLPDropout
import os
import csv
this_dir, this_filename = os.path.split(__file__)
def ReLU(x):
y = T.maximum(0.0, x)
return(y)
def Sigmoid(x):
y = T.nnet.sigmoid(x)
return(y)
def Tanh(x):
y = T.tanh(x)
return(y)
def Iden(x):
y = x
return(y)
def get_idx_from_sent(sent, word_idx_map, max_l=51, filter_h=5):
"""
Transforms sentence into a list of indices. Pad with zeroes.
"""
x = []
pad = filter_h - 1
for i in xrange(pad):
x.append(0)
words = sent.split()
for word in words:
if word in word_idx_map:
x.append(word_idx_map[word])
else:
x.append(word_idx_map["UUUKKK"])
while len(x) < max_l+2*pad:
x.append(0)
return x[:max_l+2*pad]
def make_idx_data_all(revs, word_idx_map, max_l=51, k=300, filter_h=5):
"""
Transforms sentences into a 2-d matrix.
"""
train, test = [], []
revsin = []
for rev in revs:
if rev['num_words'] > 8:
sent = get_idx_from_sent(rev["text"], word_idx_map, max_l, filter_h)
sent.append(rev["y"])
test.append(sent)
train.append(sent)
revsin.append(rev)
train = np.array(train,dtype="int")
test = np.array(test[1:100],dtype="int")
return [train, test, revsin]
if __name__=="__main__":
mrppath = os.path.join(this_dir, "mr.p")
x = cPickle.load(open(mrppath,"rb"))
revs, W, word_idx_map, vocab, numclasses, W2 = x[0], x[1], x[2], x[3], x[4] , x[5]
U = W
classifierpath = os.path.join(this_dir, "classifier.save")
savedparams = cPickle.load(open(classifierpath,'rb'))
mode2 = savedparams[1]
mode = savedparams[2]
savedparams = savedparams[0]
if mode2 == "-rand":
hunits = 10
dims = 25
U = W2
else:
hunits = 25
dims = 300
U = W
if mode == "-nonstatic":
U = savedparams[-1]
datasets = make_idx_data_all(revs, word_idx_map, max_l=70, k=dims, filter_h=5)
revsin = datasets[2]
filter_hs=[3,4,5]
conv_non_linear="relu"
hidden_units=[hunits,numclasses]
dropout_rate=[0.5]
activations=[Iden]
img_h = 70 + 4 + 4
img_w = dims
rng = np.random.RandomState(3435)
batch_size=50
filter_w = img_w
feature_maps = hidden_units[0]
filter_shapes = []
pool_sizes = []
for filter_h in filter_hs:
filter_shapes.append((feature_maps, 1, filter_h, filter_w))
pool_sizes.append((img_h-filter_h+1, img_w-filter_w+1))
#define model architecture
x = T.matrix('x')
Words = theano.shared(value = U, name = "Words")
zero_vec_tensor = T.vector()
layer0_input = Words[T.cast(x.flatten(),dtype="int32")].reshape((x.shape[0],1,x.shape[1],Words.shape[1]))
conv_layers = []
layer1_inputs = []
for i in xrange(len(filter_hs)):
filter_shape = filter_shapes[i]
pool_size = pool_sizes[i]
conv_layer = LeNetConvPoolLayer(rng, input=layer0_input,image_shape=(batch_size, 1, img_h, img_w),
filter_shape=filter_shape, poolsize=pool_size, non_linear=conv_non_linear)
layer1_input = conv_layer.output.flatten(2)
conv_layers.append(conv_layer)
layer1_inputs.append(layer1_input)
layer1_input = T.concatenate(layer1_inputs,1)
hidden_units[0] = feature_maps*len(filter_hs)
classifier = MLPDropout(rng, input=layer1_input, layer_sizes=hidden_units, activations=activations, dropout_rates=dropout_rate)
classifier.params[0].set_value(savedparams[0])
classifier.params[1].set_value(savedparams[1])
k = 2
for conv_layer in conv_layers:
conv_layer.params[0].set_value( savedparams[k])
conv_layer.params[1].set_value( savedparams[k+1])
k = k + 2
test_set_x = datasets[0][:,:img_h]
test_set_y = np.asarray(datasets[0][:,-1],"int32")
test_pred_layers = []
test_size = 1
test_layer0_input = Words[T.cast(x.flatten(),dtype="int32")].reshape((test_size,1,img_h,Words.shape[1]))
for conv_layer in conv_layers:
test_layer0_output = conv_layer.predict(test_layer0_input, test_size)
test_pred_layers.append(test_layer0_output.flatten(2))
test_layer1_input = T.concatenate(test_pred_layers, 1)
test_y_pred = classifier.predict_p(test_layer1_input)
#test_error = T.mean(T.neq(test_y_pred, y))
pdb.set_trace()
model = theano.function([x],test_y_pred,allow_input_downcast=True)
currentClass = 0
currentBestScore = 0
currentBestSentence = ""
correct = 0
docMean = 0
docSent = 0
with open('output.csv', 'w') as fp:
writer = csv.writer(fp, delimiter=',')
writer.writerow(['class','score', 'sdscore','sentence'])
print "document " + str(currentClass)
for i in range(0,test_set_x.shape[0]):
rev = revsin[i]
result = model(test_set_x[i,None])
correctScore = result[0][rev['y']]
sdscore = np.std(result[0])
writer.writerow([rev['y'], correctScore, sdscore, rev['original']])
if correctScore >= np.max(result[0]):
correct = correct + 1
#print rev['original']
if rev['y'] > currentClass:
print "docMean: " + str(docMean/docSent)
if docMean/docSent > currentBestScore:
currentBestScore = docMean/docSent
currentBestSentence = currentClass
currentClass = rev['y']
docMean = correctScore
docSent = 1
print " "
print "document " + str(currentClass)
else:
docMean += correctScore
docSent += 1
#print rev['original'] +" - " + str(correctScore)
print "correct: " + str(correct)
print str(currentBestScore)
print str(currentBestSentence)