forked from DL4Jets/DeepJetCore
-
Notifications
You must be signed in to change notification settings - Fork 1
/
modeltools.py
58 lines (44 loc) · 1.68 KB
/
modeltools.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
def getLayer(model, name):
for layer in model.layers:
if layer.name == name:
return layer
def printLayerInfosAndWeights(model, noweights=False):
for layer in model.layers:
g=layer.get_config()
h=layer.get_weights()
print (g)
if noweights: continue
print (h)
def fixLayersContaining(m, fixOnlyContaining, invert=False):
isseq=(not hasattr(fixOnlyContaining, "strip") and
hasattr(fixOnlyContaining, "__getitem__") or
hasattr(fixOnlyContaining, "__iter__"))
if not isseq:
fixOnlyContaining=[fixOnlyContaining]
if invert:
for layidx in range(len(m.layers)):
m.get_layer(index=layidx).trainable=False
for layidx in range(len(m.layers)):
for ident in fixOnlyContaining:
if len(ident) and ident in m.get_layer(index=layidx).name:
m.get_layer(index=layidx).trainable=True
else:
for layidx in range(len(m.layers)):
for ident in fixOnlyContaining:
if len(ident) and ident in m.get_layer(index=layidx).name:
m.get_layer(index=layidx).trainable=False
return m
def set_trainable(m, patterns, value):
if isinstance(patterns, basestring):
patterns = [patterns]
for layidx in range(len(m.layers)):
name = m.get_layer(index=layidx).name
if any(i in name for i in patterns):
m.get_layer(index=layidx).trainable = value
return m
def loadModelAndFixLayers(filename,fixOnlyContaining):
#import keras
from keras.models import load_model
m=load_model(filename)
fixLayersContaining(m, fixOnlyContaining)
return m