-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathnet.py
More file actions
194 lines (164 loc) · 7.9 KB
/
Copy pathnet.py
File metadata and controls
194 lines (164 loc) · 7.9 KB
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
from layers.input import InputLayer
from layers.dropout import DropoutLayer
from layers.nonlinearities import ReluLayer, SigmoidLayer, MaxoutLayer, TanhLayer
from layers.loss import SoftmaxLayer, RegressionLayer, SVMLayer
from layers.normalization import LocalResponseNormalizationLayer
from layers.pooling import PoolLayer
from layers.dotproducts import ConvLayer, FullyConnectedLayer
from layers.similarity import SimilarityLayer, MexLayer
from layers.operations import AddLayer
class Net(object):
"""
Net manages a set of layers.
For now: Simple linear order of layers, first layer input and last layer a cost layer
"""
def __init__(self, layers=None):
self.layers = []
if layers and type(layers) == list:
self.makeLayers(layers)
def __str__(self):
return '\n'.join(
'{} {} {} {}'.format(
layer.layer_type,
layer.out_sx,
layer.out_sy,
layer.out_depth
) for layer in self.layers
)
def makeLayers(self, layers):
# Takes a list of layer definitions and creates the network layer objects
# Checks
if len(layers) < 2:
print 'Error: Net must have at least one input and one softmax layer.'
if layers[0]['type'] != 'input':
print 'Error: First layer should be input.'
# Add activations and dropouts
def addExtraLayers():
newLayers = []
for layer in layers:
layerType = layer['type']
layerKeys = layer.keys()
if layerType == 'softmax' or layerType == 'svm':
# add an fc layer
newLayers.append({
'type': 'fc',
'num_neurons': layer['num_classes']
})
if layerType == 'regression':
# add an fc layer
newLayers.append({
'type': 'fc',
'num_neurons': layer['num_neurons']
})
if ((layerType == 'fc' or layerType == 'conv')
and ('bias_pref' not in layerKeys)):
layer['bias_pref'] = 0.0
if 'activation' in layerKeys and layer['activation'] == 'relu':
layer['bias_pref'] = 0.1 # prevent dead relu by chance
if layerType != 'capsule':
newLayers.append(layer)
if 'activation' in layerKeys:
layerAct = layer['activation']
if layerAct in ['relu', 'sigmoid', 'tanh', 'mex']:
newLayers.append({'type': layerAct})
elif layerAct == 'maxout':
newLayers.append({
'type': 'maxout',
'group_size': layer['group_size'] if group_size in layerKeys else 2
})
else:
print 'Error: Unsupported activation'
if 'drop_prob' in layerKeys and layerType != 'dropout':
newLayers.append({
'type': 'dropout',
'drop_prob': layer['drop_prob']
})
if layerType == 'capsule':
fc_recog = {'type': 'fc', 'num_neurons': layer['num_recog']}
pose = {'type': 'add', 'delta': [layer['dx'], layer['dy']],
'skip': 1, 'num_neurons': layer['num_pose']}
fc_gen = {'type': 'fc', 'num_neurons': layer['num_gen']}
newLayers.append(fc_recog)
newLayers.append(pose)
newLayers.append(fc_gen)
return newLayers
all_layers = addExtraLayers()
# Create the layers
for i in xrange(len(all_layers)):
layer = all_layers[i]
if i > 0:
prev = self.layers[i - 1]
layer['in_sx'] = prev.out_sx
layer['in_sy'] = prev.out_sy
layer['in_depth'] = prev.out_depth
layerType = layer['type']
obj = None
if layerType == 'fc': obj = FullyConnectedLayer(layer)
elif layerType == 'lrn': obj = LocalResponseNormalizationLayer(layer)
elif layerType == 'dropout': obj = DropoutLayer(layer)
elif layerType == 'input': obj = InputLayer(layer)
elif layerType == 'softmax': obj = SoftmaxLayer(layer)
elif layerType == 'regression': obj = RegressionLayer(layer)
elif layerType == 'conv': obj = ConvLayer(layer)
elif layerType == 'pool': obj = PoolLayer(layer)
elif layerType == 'relu': obj = ReluLayer(layer)
elif layerType == 'sigmoid': obj = SigmoidLayer(layer)
elif layerType == 'tanh': obj = TanhLayer(layer)
elif layerType == 'maxout': obj = MaxoutLayer(layer)
elif layerType == 'svm': obj = SVMLayer(layer)
elif layerType == 'sim': obj = SimilarityLayer(layer)
elif layerType == 'mex': obj = MexLayer(layer)
elif layerType == 'add': obj = AddLayer(layer)
elif layerType == 'capsule': pass
else: print 'Unrecognized layer type'
if obj: self.layers.append(obj)
def forward(self, V, is_training=False):
# Forward propogate through the network.
# Trainer will pass is_training=True
activation = self.layers[0].forward(V, is_training)
for i in xrange(1, len(self.layers)):
activation = self.layers[i].forward(activation, is_training)
return activation
def getCostLoss(self, V, y):
self.forward(V, False)
loss = self.layers[-1].backward(y)
return loss
def backward(self, y):
# Backprop: compute gradients wrt all parameters
loss = self.layers[-1].backward(y) #last layer assumed loss layer
for i in xrange(len(self.layers) - 2, 0, -1): # first layer assumed input
self.layers[i].backward()
return loss
def getParamsAndGrads(self):
# Accumulate parameters and gradients for the entire network
return [ pg
for layer in self.layers
for pg in layer.getParamsAndGrads() ]
def getPrediction(self):
softmax = self.layers[-1]
p = softmax.out_act.w
return p.index(max(p))
def toJSON(self):
return { 'layers': [ layer.toJSON() for layer in self.layers ] }
def fromJSON(self, json):
self.layers = []
for layer in json['layers']:
layerType = layer['type']
obj = None
if layerType == 'fc': obj = FullyConnectedLayer(layer)
elif layerType == 'lrn': obj = LocalResponseNormalizationLayer(layer)
elif layerType == 'dropout': obj = DropoutLayer(layer)
elif layerType == 'input': obj = InputLayer(layer)
elif layerType == 'softmax': obj = SoftmaxLayer(layer)
elif layerType == 'regression': obj = RegressionLayer(layer)
elif layerType == 'conv': obj = ConvLayer(layer)
elif layerType == 'pool': obj = PoolLayer(layer)
elif layerType == 'relu': obj = ReluLayer(layer)
elif layerType == 'sigmoid': obj = SigmoidLayer(layer)
elif layerType == 'tanh': obj = TanhLayer(layer)
elif layerType == 'maxout': obj = MaxoutLayer(layer)
elif layerType == 'svm': obj = SVMLayer(layer)
elif layerType == 'sim': obj = SimilarityLayer(layer)
elif layerType == 'mex': obj = MexLayer(layer)
obj.fromJSON(layer)
self.layers.append(obj)