因此,我尝试使用以下代码从3个顺序子模型中创建一个整体模型:
def create_ensemble(models,model_input):
# take-in all outputs fro all models
outModels = [model(model_input) for model in models]
# calculate average of all results
outAvg = layers.average(outModels)
# merge into one model
modelMerge = Model(inputs=model_input,outputs=outAvg,name='ensemble')
return modelMerge
model_input = Input(shape=models[0].input_shape[1:])
modelEns = create_ensemble(models,model_input)
我得到这个模型:
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_1 (InputLayer) (None, 1, 1) 0
__________________________________________________________________________________________________
model_1 (Sequential) multiple 14 input_1[0][0]
__________________________________________________________________________________________________
model_2 (Sequential) multiple 14 input_1[0][0]
__________________________________________________________________________________________________
model_3 (Sequential) multiple 14 input_1[0][0]
__________________________________________________________________________________________________
average_1 (Average) (None, 1) 0 model_1[1][0]
model_2[1][0]
model_3[1][0]
==================================================================================================
所有子模型如下:
Layer (type) Output Shape Param #
=================================================================
lstm_1 (LSTM) (1, 1) 12
_________________________________________________________________
dense_1 (Dense) (1, 1) 2
=================================================================
这是我提供数据的方式:
def fit_lstm(train, batch_size, nb_epoch, nb_neurons):
X, y = train[:, 0:-1], train[:, -1]
X = X.reshape(X.shape[0], 1, X.shape[1])
model = Sequential()
model.add(LSTM(nb_neurons, batch_input_shape=(batch_size, X.shape[1], X.shape[2]), stateful=True))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
for i in range(nb_epoch):
model.fit(X, y, epochs=1, batch_size=batch_size, verbose=0, shuffle=False)
model.reset_states()
return model
我正在尝试为集成模型提供与子模型相同的数据,但是标题出现错误。我怎么了?
答案 0 :(得分:0)
由于您正在使用Sequestial
api,因此无法正常工作
model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
为了将模型合并在一起,您需要使用Functional
api:
a = Input(shape=(32,))
b = Dense(32)(a)
model = Model(inputs=a, outputs=b)