我用这种方式实现了Keras功能模型的快捷方式:
inputs = ...
# shortcut path
shortcut = ShortcutLayer()(inputs)
# main path
outputs = MainLayer()(inputs)
# add main and shortcut together
outputs = Add()([outputs, shortcut])
是否可以将其转换为顺序模型,以便我不需要事先知道inputs
?
基本上,我想要实现的目标如下:
def my_model_with_shortcut():
# returns a Sequential model equivalent to the functional one above
model = my_model_with_shortcut()
inputs = ...
outputs = model(inputs)
答案 0 :(得分:0)
我会尝试以下内容;
def my_model_with_shortcut():
def _create_shortcut(inputs):
# here create model as in case you know inputs, e.g.:
aux = Dense(10, activation='relu')(inputs)
output = Dense(10, activation='relu')(aux)
return output
return _create_shortcut
现在你应该有你的场景。
答案 1 :(得分:0)
通常我会创建一个维护模型的可调用对象。 当我希望这段重复使用重量相同时,我会这样做。
您可以尝试Marcin的方法,但每次调用该函数时都会创建一个新模型。根据您的目的,这对您来说可能已经足够了。我的回答有这些不同之处:
代码:
from keras.models import Model
from keras.layers import *
import numpy as np
class ModelSegment():
def __init__(self):
self.shortcutLayer = Dense(10,activation='sigmoid')
self.mainLayer = Dense(10,activation='sigmoid')
self.addLayer = Add()
self.model = None
def __call__(self,inputs):
if self.model is None:
shortcut = self.shortcutLayer(inputs)
outputs = self.mainLayer(inputs)
outputs = self.addLayer([outputs,shortcut])
#creating this model is not really necessary
#you can skip the following code line and discard the if clause
#but since you stated you wanted a "model" I added it here
self.model = Model(inputs,outputs)
return outputs
else:
return self.model(inputs)
segment = ModelSegment()
inputTensor = Input((13,))
inputTensor2 = Input((13,))
out = segment(inputTensor)
out2 = segment(inputTensor2)
m1 = Model(inputTensor,out)
m2 = Model(inputTensor2,out2)
m1.summary()
m2.summary()
w1 = m1.get_weights()
w2 = m2.get_weights()
for arr1,arr2 in zip(w1,w2):
print((arr1==arr2).all())