/
grid_learn.py
174 lines (146 loc) · 5.53 KB
/
grid_learn.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
import numpy as np
import theano.tensor as T
import theano
import matplotlib.pyplot as plt
from theano_toolkit import utils as U
from theano_toolkit import updates
from collections import Counter
from matplotlib import animation
from itertools import product
import matplotlib.cm as cm
import seaborn as sns
def build_model(hidden_size,predict_only=False):
X = T.matrix('X')
Y = T.ivector('Y')
#* (0.001 * U.initial_weights(2,hidden_size) + np.array([[0,0,1,1],[1,1,0,0]])))
W_input_hidden = U.create_shared(U.initial_weights(2,hidden_size))
b_hidden = U.create_shared(U.initial_weights(hidden_size))
W_hidden_predict = U.create_shared(U.initial_weights(hidden_size,2))
b_predict = U.create_shared(U.initial_weights(2))
params = [W_input_hidden,b_hidden,W_hidden_predict,b_predict]
hidden_lin = T.dot(X,W_input_hidden) + b_hidden
hidden = T.nnet.sigmoid(hidden_lin)
predict = T.nnet.softmax(T.dot(hidden,W_hidden_predict) + b_predict)
cost = -T.mean(T.log(predict[T.arange(Y.shape[0]),Y])) + 1e-3*adjacency_constraint(hidden_lin)# + 1e-4 * sum(T.sum(p**2) for p in params)
accuracy = T.mean(T.eq(T.argmax(predict,axis=1),Y))
grad = T.grad(cost,params)
train = theano.function(
inputs = [X,Y],
#updates = updates.momentum(params,grad,0.9999,0.1) if not predict_only else None,
#updates = updates.momentum(params,grad,0.999,0.0005),
updates = updates.adadelta(params,grad),
outputs = [accuracy,W_input_hidden,b_hidden,(hidden>0.5)]
)
predict = theano.function(
inputs = [X],
outputs = predict[:,0]
)
i = T.iscalar('i')
hidden_p = theano.function(
inputs = [X,i],
outputs = hidden[:,i]
)
return train,predict,hidden_p,params
def create_normal_data(line_count,point_count):
points = []
labels = []
for i in xrange(line_count):
for j in xrange(line_count):
points.append(0.1*np.random.randn(point_count/4,2) +\
np.array([i,j]) - 1.5)
if i%2 == j%2:
labels.append(np.zeros(point_count/4,dtype=bool))
else:
labels.append(np.ones(point_count/4,dtype=bool))
return np.vstack(points),np.hstack(labels)
def create_data(line_count,point_count):
points = np.asarray(line_count * np.random.rand(point_count,2) - 2)
ceil = np.ceil(points) + 1
label = (ceil[:,0] % 2 == ceil[:,1] % 2)
#label = ceil[:,0] > ceil[:,1]
return points, label
def plot(points,label,N,histogram=True):
fig = plt.figure(figsize=(6,8))
bounds = [-2.5,2.5]
left_right = np.array(bounds)
intervals = np.arange(bounds[0],bounds[1]+0.1,0.1)
ctr_pts = np.meshgrid(intervals,intervals)
labels = [''.join(i) for i in product('01',repeat=N)]
lbl_colors = dict(zip(labels,sns.color_palette("husl", len(labels))))
# ax = plt.axes(xlim=(left_right[0],left_right[1]), ylim=(-2.5, 2.5))
# ax = plt.subplot(121)
if histogram:
ax1 = plt.subplot2grid((3, 2), (0, 0),rowspan=2,colspan=2)
ax2 = plt.subplot2grid((3, 2), (2, 0),colspan=2)
else:
ax1 = plt.subplot(111)
ax2 = None
pos = np.arange(len(labels))
width = 5.0/len(labels)
if histogram:
rects = ax2.bar(pos,np.zeros(len(labels)),width)
ax2.set_xticks(pos + (width / 2))
ax2.set_xticklabels(labels,rotation='vertical')
else:
rects = None
# for i,c in zip(ax2.get_xticklabels(),lbl_colors): i.set_color(c)
#im = ax1.imshow(np.ones(ctr_pts[0].shape), interpolation='bilinear', origin='lower',cmap=cm.gray,extent=(left_right[0],left_right[1])*2,animated=True)
Z = np.ones(ctr_pts[0].shape)
im = ax1.imshow(
Z,
interpolation='bilinear',
origin='lower',
animated=True,
cmap=cm.gray,
extent=(left_right[0],left_right[1])*2,
alpha=0.5,
vmin=0,vmax=1,
)
ax1.set_xlim(bounds)
ax1.set_ylim(bounds)
class1 = points[ label]
class2 = points[~label]
ax1.plot(class1[:,0],class1[:,1], 'ro')
ax1.plot(class2[:,0],class2[:,1], 'bo')
return fig,ax1,ax2,left_right,labels,lbl_colors,rects,ctr_pts,im,Z
if __name__ == "__main__":
line_count = 4
grid_size = 3
instances = 1000
points, label = create_normal_data(grid_size,instances)
train,predict,hidden_p,params = build_model(line_count)
fig,ax,ax_hist,left_right,labels,lbl_colors,rects,ctr_pts,im,Z = plot(points,label,line_count)
lines = [ax.plot([], [], lw=2)[0] for _ in xrange(line_count)]
acc_text = ax.text(0.02, 1.01, '', transform=ax.transAxes)
acc_text.set_text('')
def data_gen():
acc,coeffs,bias,hidden = train(points,label)
ctr_z = predict(np.dstack(ctr_pts).reshape(-1, 2))
while acc < 0.999:
print acc
yield acc,coeffs,bias,hidden,ctr_z
acc,coeffs,bias,hidden = train(points,label)
ctr_z,_ = predict(np.dstack(ctr_pts).reshape(-1, 2))
for _ in xrange(100):
print acc
yield acc,coeffs,bias,hidden,ctr_z
acc,coeffs,bias,hidden = train(points,label)
ctr_z,_ = predict(np.dstack(ctr_pts).reshape(-1, 2))
it = data_gen()
def animate(data):
acc,coeffs,bias,hidden,ctr_z = it.next()
acc_text.set_text("accuracy=%0.2f"%acc)
M = - coeffs[0]/coeffs[1]
C = - bias / coeffs[1]
for i in xrange(len(lines)):
lines[i].set_data(left_right, M[i]*left_right + C[i])
#Z[:,:] =
#im = ax.imshow(Z, interpolation='bilinear', origin='lower',cmap=cm.gray,extent=(left_right[0],left_right[1])*2)
im.set_data(ctr_z.reshape(ctr_pts[0].shape))
activations = Counter(''.join(str(e) for e in row) for row in hidden)
labels.sort(key=lambda x:-activations.get(x,0))
for i in ax_hist.get_xticklabels(): i.set_color(lbl_colors[i.get_text()])
for lbl,rct in zip(labels,rects):
rct.set_height(activations.get(lbl,0)/float(instances))
anim = animation.FuncAnimation(fig,animate,frames=2500, interval=20, blit=True)
anim.save('grid_learn_init_spec.mp4', fps=60,bitrate=512)