forked from DL4Jets/DeepJetCore
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodeltools.py
95 lines (75 loc) · 2.62 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
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
import imp
try:
imp.find_module('Losses')
from Losses import *
except ImportError:
print 'No Losses module found, ignoring at your own risk'
global_loss_list = {}
try:
imp.find_module('Layers')
from Layers import *
except ImportError:
print 'No Layers module found, ignoring at your own risk'
global_layers_list = {}
try:
imp.find_module('Metrics')
from Metrics import *
except ImportError:
print 'No metrics module found, ignoring at your own risk'
global_metrics_list = {}
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 setAllTrainable(m):
for layidx in range(len(m.layers)):
m.get_layer(index=layidx).trainable = True
return m
def loadModelAndFixLayers(filename,fixOnlyContaining):
#import keras
from keras.models import load_model
m=load_model(filename)
fixLayersContaining(m, fixOnlyContaining)
return m
def load_model(filename):
from keras.models import load_model
custom_objs = {}
custom_objs.update(global_loss_list)
custom_objs.update(global_layers_list)
custom_objs.update(global_metrics_list)
model=load_model(filename, custom_objects=custom_objs)
return model