Skip to content

Commit 6000d29

Browse files
author
yxdragon
committed
load weights
1 parent 0797fb1 commit 6000d29

3 files changed

Lines changed: 18 additions & 22 deletions

File tree

cnnumpy/layer.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ def backward(self, grad_y): pass
1212

1313
def para(self): return None
1414

15+
def load(self, buf): return 0
16+
1517
def __call__(self, x):
1618
return self.forward(x)
1719

@@ -28,9 +30,11 @@ def forward(self, x):
2830
y += self.bias.reshape((1, -1))
2931
return y
3032

31-
def load(self, weights, bias):
32-
self.K = weights.copy()
33-
self.bias = bias.copy()
33+
def load(self, buf):
34+
sk, sb = self.K.size, self.bias.size
35+
self.K.ravel()[:] = buf[:sk]
36+
self.bias.ravel()[:] = buf[sk:sk+sb]
37+
return sk + sb
3438

3539
class Conv2d(Layer):
3640
name = 'conv'
@@ -46,9 +50,11 @@ def forward(self, x):
4650
out += self.bias.reshape((1, -1, 1, 1))
4751
return out
4852

49-
def load(self, weights, bias):
50-
self.K = weights.copy()
51-
self.bias = bias.copy()
53+
def load(self, buf):
54+
sk, sb = self.K.size, self.bias.size
55+
self.K.ravel()[:] = buf[:sk]
56+
self.bias.ravel()[:] = buf[sk:sk+sb]
57+
return sk + sb
5258

5359
class ReLU(Layer):
5460
name = 'relu'

cnnumpy/net.py

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -67,18 +67,10 @@ def flw2code(self, style='list'):
6767
body.append('')
6868
return '\n'.join(body)
6969

70-
def load_data(self, data, shpkey):
70+
def load_weights(self, data):
7171
s = 0
72-
for i in shpkey:
73-
for j in range(len(shpkey[i])):
74-
sp = shpkey[i][j]
75-
l = np.cumprod(sp)[-1]
76-
shpkey[i][j] = data[s:s+l].reshape(sp)
77-
s += l
78-
dic = dict(self.body)
79-
for i in shpkey:
80-
dic[i].K = shpkey[i][0]
81-
dic[i].bias = shpkey[i][1]
72+
for i in self.body:
73+
s += i[1].load(data[s:])
8274

8375
def __call__(self, x):
8476
return self.forward(x)
@@ -88,10 +80,8 @@ def read_net(path):
8880
with open(path+'.lay') as f: lay = json.load(f)
8981
with open(path+'.flw') as f: flw = json.load(f)
9082
net.load_json(lay, flw)
91-
data = np.load(path+'.npy')
92-
with open(path+'.shp') as f: shp = json.load(f)
93-
net.load_data(data, shp)
83+
net.load_weights(np.load(path+'.npy'))
9484
return net
9585

9686
if __name__ == '__main__':
97-
pass
87+
pass

demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def forward(self, x):
5656
shp = {'conv':[[64, 3, 3, 3], [1, 64]]}
5757
data = np.zeros(64*3*3*3+1*64, dtype=np.float32)
5858

59-
net.load_data(data, shp)
59+
net.load_weights(data)
6060

6161
load_a_net = '''
6262
write the layer, flow, shp as json format,

0 commit comments

Comments
 (0)