在Keras中進行模型融合和集成學習通常有兩種方法:模型堆疊和模型平均。
model1 = Sequential()
model1.add(Dense(128, activation='relu', input_shape=(input_shape,)))
model1.add(Dense(64, activation='relu'))
model2 = Sequential()
model2.add(Dense(128, activation='relu', input_shape=(input_shape,)))
model2.add(Dense(64, activation='relu'))
merged_model = Sequential()
merged_model.add(Merge([model1, model2], mode='concat'))
merged_model.add(Dense(64, activation='relu'))
merged_model.add(Dense(num_classes, activation='softmax'))
model1 = Sequential()
model1.add(Dense(128, activation='relu', input_shape=(input_shape,)))
model1.add(Dense(64, activation='relu'))
model1.add(Dense(num_classes, activation='softmax'))
model2 = Sequential()
model2.add(Dense(128, activation='relu', input_shape=(input_shape,)))
model2.add(Dense(64, activation='relu'))
model2.add(Dense(num_classes, activation='softmax'))
model1.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model2.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model1.fit(X_train, y_train, batch_size=32, epochs=10)
model2.fit(X_train, y_train, batch_size=32, epochs=10)
predictions1 = model1.predict(X_test)
predictions2 = model2.predict(X_test)
average_predictions = (predictions1 + predictions2) / 2
這樣,我們就可以利用模型融合和集成學習來提高模型的性能。需要注意的是,模型融合和集成學習需要謹慎選擇模型,避免過擬合和不穩定性。