我将模型图层存储在一个文本文件中,如下所示:
{
"model" : "Sequential",
"layers": [
{
"L1": "Conv2D(filters = 64, kernel_size=(3,3), strides=(1, 1), padding='valid', data_format='channels_last', dilation_rate=None, activation='relu', use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, input_shape=(28,28,1))",
"L2": "Conv2D(filters = 32, kernel_size=(3,3), strides=(1, 1), padding='valid', data_format='channels_last', dilation_rate=None, activation='relu', use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None)" ,
"L3": "Flatten()",
"L4": "Dense(10, activation='softmax', use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None)"
}
]
}
我试图像这样在python控制台中加载模型:
with open('model.txt','r') as fb:
con = json.load(fb, object_pairs_hook=ordereddict.OrderedDict)
from keras.models import Sequential
model = Sequential()
model.add(con['layers'][0]['L1'])
但是会出现以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ashutosh/.local/lib/python2.7/site-packages/keras/engine/sequential.py", line 132, in add
'Found: ' + str(layer))
TypeError: The added layer must be an instance of class Layer. Found: Conv2D(filters = 32, kernel_size=(3,3), strides=(1, 1), padding='valid', data_format='channels_last', dilation_rate=None, activation='relu', use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None)
如何从文本文件加载Conv2D图层?
答案 0 :(得分:1)
con['layers'][0]['L1']
是一个字符串。
考虑使用eval
model.add(eval(con['layers'][0]['L1']))